summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Makefile28
-rwxr-xr-xdocs/_scripts/filter_api.py14
-rwxr-xr-xdocs/_scripts/filter_c.py101
-rwxr-xr-xdocs/_scripts/filter_h.py16
-rw-r--r--docs/_scripts/includes_renderer.py7
-rw-r--r--docs/_scripts/siphon/generate.py83
-rw-r--r--docs/_scripts/siphon/generate_clicmd.py13
-rw-r--r--docs/_scripts/siphon/generate_syscfg.py14
-rw-r--r--docs/_scripts/siphon/parsers.py52
-rw-r--r--docs/_scripts/siphon/process.py109
-rw-r--r--docs/_scripts/siphon/process_clicmd.py30
-rw-r--r--docs/conf.py87
-rwxr-xr-xextras/deprecated/perfmon/intel_json_to_c.py64
-rw-r--r--extras/deprecated/plugins/gbp/test_gbp.py5510
-rw-r--r--extras/deprecated/vnet/vxlan-gbp/test_vxlan_gbp.py143
-rw-r--r--extras/deprecated/vnet/vxlan-gbp/vpp_vxlan_gbp_tunnel.py64
-rw-r--r--extras/deprecated/vom/test/test_vom.py23
-rwxr-xr-xextras/scripts/crcchecker.py207
-rwxr-xr-xextras/scripts/list_api_changes.py23
-rwxr-xr-xextras/vpp_config/scripts/dpdk-devbind.py213
-rw-r--r--extras/vpp_config/setup.py60
-rwxr-xr-xextras/vpp_config/vpp_config.py354
-rw-r--r--extras/vpp_config/vpplib/AutoConfig.py1205
-rw-r--r--extras/vpp_config/vpplib/CpuUtils.py88
-rw-r--r--extras/vpp_config/vpplib/QemuUtils.py484
-rw-r--r--extras/vpp_config/vpplib/VPPUtil.py435
-rw-r--r--extras/vpp_config/vpplib/VppGrubUtil.py146
-rw-r--r--extras/vpp_config/vpplib/VppHugePageUtil.py76
-rw-r--r--extras/vpp_config/vpplib/VppPCIUtil.py165
-rw-r--r--extras/vpp_config/vpplib/constants.py18
-rwxr-xr-xsrc/plugins/map/examples/gen-rules.py160
-rwxr-xr-xsrc/plugins/map/examples/test_map.py119
-rwxr-xr-xsrc/plugins/map/gen-rules.py123
-rw-r--r--src/plugins/nat/extras/nat_100ks.py24
-rw-r--r--src/plugins/nat/extras/nat_10Ms.py24
-rw-r--r--src/plugins/nat/extras/nat_10ks.py24
-rw-r--r--src/plugins/nat/extras/nat_1Ms.py24
-rw-r--r--src/plugins/nat/extras/nat_out2in_100ks.py24
-rw-r--r--src/plugins/nat/extras/nat_out2in_10Ms.py24
-rw-r--r--src/plugins/nat/extras/nat_out2in_10ks.py24
-rw-r--r--src/plugins/nat/extras/nat_out2in_1Ms.py24
-rw-r--r--src/plugins/nat/extras/nat_ses_open.py83
-rwxr-xr-xsrc/plugins/nat/extras/nat_static_gen_cfg.py34
-rw-r--r--src/plugins/nat/extras/nat_test_fast_path.py64
-rw-r--r--src/plugins/nat/extras/nat_test_slow_path.py60
-rw-r--r--src/plugins/nat/extras/nat_test_slow_path_with_latency.py81
-rwxr-xr-xsrc/plugins/nat/pnat/tests/test_genpackets.py30
-rwxr-xr-xsrc/plugins/srv6-mobile/extra/runner.py824
-rwxr-xr-xsrc/scripts/fts.py215
-rwxr-xr-xsrc/scripts/host-stack/cc_plots.py336
-rwxr-xr-xsrc/scripts/vnet/uri/dummy_app.py110
-rwxr-xr-xsrc/tools/vppapigen/generate_go.py154
-rwxr-xr-xsrc/tools/vppapigen/generate_json.py82
-rwxr-xr-xsrc/tools/vppapigen/test_vppapigen.py120
-rwxr-xr-xsrc/tools/vppapigen/vppapigen.py813
-rw-r--r--src/tools/vppapigen/vppapigen_c.py1850
-rw-r--r--src/tools/vppapigen/vppapigen_crc.py15
-rw-r--r--src/tools/vppapigen/vppapigen_json.py59
-rw-r--r--src/vpp-api/python/setup.py21
-rw-r--r--src/vpp-api/python/vpp_papi/__init__.py3
-rw-r--r--src/vpp-api/python/vpp_papi/macaddress.py17
-rw-r--r--src/vpp-api/python/vpp_papi/tests/test_macaddress.py6
-rw-r--r--src/vpp-api/python/vpp_papi/tests/test_vpp_format.py104
-rw-r--r--src/vpp-api/python/vpp_papi/tests/test_vpp_papi.py10
-rwxr-xr-xsrc/vpp-api/python/vpp_papi/tests/test_vpp_serializer.py775
-rw-r--r--src/vpp-api/python/vpp_papi/vpp_format.py216
-rw-r--r--src/vpp-api/python/vpp_papi/vpp_papi.py350
-rw-r--r--src/vpp-api/python/vpp_papi/vpp_serializer.py259
-rwxr-xr-xsrc/vpp-api/python/vpp_papi/vpp_stats.py308
-rw-r--r--src/vpp-api/python/vpp_papi/vpp_transport_socket.py34
-rwxr-xr-xsrc/vpp-api/vapi/vapi_c_gen.py827
-rwxr-xr-xsrc/vpp-api/vapi/vapi_cpp_gen.py221
-rw-r--r--src/vpp-api/vapi/vapi_json_parser.py269
-rw-r--r--test/Makefile58
-rw-r--r--test/bfd.py261
-rw-r--r--test/config.py363
-rw-r--r--test/debug.py15
-rw-r--r--test/debug_internal.py13
-rw-r--r--test/framework.py880
-rw-r--r--test/hook.py66
-rw-r--r--test/ipfix.py256
-rw-r--r--test/lisp.py139
-rw-r--r--test/log.py36
-rw-r--r--test/remote_test.py143
-rw-r--r--test/requirements-3.txt343
-rw-r--r--test/requirements.txt4
-rw-r--r--test/run_tests.py511
-rw-r--r--test/sanity_run_vpp.py9
-rw-r--r--test/template_bd.py65
-rw-r--r--test/template_classifier.py216
-rw-r--r--test/template_ipsec.py1581
-rw-r--r--test/test_abf.py200
-rw-r--r--test/test_acl_plugin.py999
-rw-r--r--test/test_acl_plugin_conns.py154
-rw-r--r--test/test_acl_plugin_l2l3.py743
-rw-r--r--test/test_acl_plugin_macip.py795
-rw-r--r--test/test_adl.py126
-rw-r--r--test/test_api_client.py9
-rw-r--r--test/test_api_trace.py23
-rw-r--r--test/test_arping.py118
-rw-r--r--test/test_bfd.py2074
-rw-r--r--test/test_bier.py727
-rw-r--r--test/test_bihash.py40
-rw-r--r--test/test_bond.py106
-rw-r--r--test/test_buffers.py6
-rw-r--r--test/test_cdp.py53
-rw-r--r--test/test_classifier.py607
-rw-r--r--test/test_classifier_ip6.py220
-rw-r--r--test/test_classify_l2_acl.py317
-rw-r--r--test/test_cli.py35
-rw-r--r--test/test_cnat.py382
-rw-r--r--test/test_container.py72
-rw-r--r--test/test_counters.py10
-rw-r--r--test/test_crypto.py7
-rw-r--r--test/test_det44.py404
-rw-r--r--test/test_dhcp.py1171
-rw-r--r--test/test_dhcp6.py314
-rw-r--r--test/test_dns.py46
-rw-r--r--test/test_dslite.py214
-rw-r--r--test/test_dvr.py181
-rw-r--r--test/test_endian.py19
-rw-r--r--test/test_fib.py7
-rw-r--r--test/test_flowprobe.py307
-rw-r--r--test/test_geneve.py175
-rw-r--r--test/test_gre.py713
-rw-r--r--test/test_gro.py116
-rw-r--r--test/test_gso.py652
-rw-r--r--test/test_gtpu.py185
-rw-r--r--test/test_http.py20
-rw-r--r--test/test_igmp.py798
-rw-r--r--test/test_ikev2.py1698
-rw-r--r--test/test_interface_crud.py38
-rw-r--r--test/test_ip4.py1788
-rw-r--r--test/test_ip4_irb.py68
-rw-r--r--test/test_ip4_vrf_multi_instance.py150
-rw-r--r--test/test_ip6.py2351
-rw-r--r--test/test_ip6_nd_mirror_proxy.py105
-rw-r--r--test/test_ip6_vrf_multi_instance.py184
-rw-r--r--test/test_ip_ecmp.py89
-rw-r--r--test/test_ip_mcast.py669
-rw-r--r--test/test_ipfix_export.py134
-rw-r--r--test/test_ipip.py866
-rw-r--r--test/test_ipsec_ah.py453
-rw-r--r--test/test_ipsec_api.py92
-rw-r--r--test/test_ipsec_default.py89
-rw-r--r--test/test_ipsec_esp.py1135
-rw-r--r--test/test_ipsec_nat.py334
-rw-r--r--test/test_ipsec_spd_flow_cache_input.py371
-rw-r--r--test/test_ipsec_spd_flow_cache_output.py319
-rw-r--r--test/test_ipsec_tun_if_esp.py2444
-rw-r--r--test/test_l2_fib.py172
-rw-r--r--test/test_l2_flood.py174
-rw-r--r--test/test_l2bd.py101
-rw-r--r--test/test_l2bd_arp_term.py176
-rw-r--r--test/test_l2bd_learnlimit.py34
-rw-r--r--test/test_l2bd_learnlimit_bdenabled.py41
-rw-r--r--test/test_l2bd_learnlimit_enabled.py34
-rw-r--r--test/test_l2bd_multi_instance.py122
-rw-r--r--test/test_l2tp.py20
-rw-r--r--test/test_l2xc.py59
-rw-r--r--test/test_l2xc_multi_instance.py82
-rw-r--r--test/test_l3xc.py77
-rw-r--r--test/test_lacp.py149
-rw-r--r--test/test_lb.py287
-rw-r--r--test/test_lb_api.py31
-rw-r--r--test/test_linux_cp.py228
-rw-r--r--test/test_lisp.py117
-rw-r--r--test/test_mactime.py241
-rw-r--r--test/test_map.py824
-rw-r--r--test/test_map_br.py421
-rw-r--r--test/test_memif.py141
-rw-r--r--test/test_mpcap.py41
-rw-r--r--test/test_mpls.py1837
-rw-r--r--test/test_mss_clamp.py228
-rw-r--r--test/test_mtu.py73
-rw-r--r--test/test_nat44_ed.py2902
-rw-r--r--test/test_nat44_ed_output.py151
-rw-r--r--test/test_nat44_ei.py2521
-rw-r--r--test/test_nat64.py1425
-rw-r--r--test/test_nat66.py137
-rw-r--r--test/test_neighbor.py2215
-rw-r--r--test/test_node_variants.py40
-rw-r--r--test/test_offload.py73
-rw-r--r--test/test_p2p_ethernet.py322
-rw-r--r--test/test_pcap.py107
-rw-r--r--test/test_pg.py42
-rw-r--r--test/test_ping.py45
-rw-r--r--test/test_pipe.py161
-rw-r--r--test/test_pnat.py242
-rw-r--r--test/test_policer.py119
-rw-r--r--test/test_policer_input.py106
-rw-r--r--test/test_pppoe.py312
-rw-r--r--test/test_punt.py572
-rw-r--r--test/test_qos.py342
-rw-r--r--test/test_quic.py234
-rw-r--r--test/test_reassembly.py1509
-rw-r--r--test/test_session.py66
-rw-r--r--test/test_sixrd.py340
-rw-r--r--test/test_span.py210
-rw-r--r--test/test_sparse_vec.py7
-rw-r--r--test/test_srmpls.py166
-rw-r--r--test/test_srv6.py1149
-rw-r--r--test/test_srv6_ad.py356
-rw-r--r--test/test_srv6_ad_flow.py276
-rw-r--r--test/test_srv6_as.py380
-rw-r--r--test/test_srv6_mobile.py141
-rw-r--r--test/test_srv6_un.py116
-rw-r--r--test/test_stats_client.py69
-rw-r--r--test/test_string.py37
-rw-r--r--test/test_svs.py225
-rw-r--r--test/test_syslog.py206
-rw-r--r--test/test_tap.py9
-rw-r--r--test/test_tcp.py52
-rw-r--r--test/test_tls.py72
-rw-r--r--test/test_trace_filter.py177
-rw-r--r--test/test_udp.py424
-rw-r--r--test/test_urpf.py252
-rw-r--r--test/test_util.py14
-rw-r--r--test/test_vapi.py30
-rw-r--r--test/test_vcl.py779
-rw-r--r--test/test_vhost.py46
-rw-r--r--test/test_vlib.py268
-rw-r--r--test/test_vpe_api.py24
-rw-r--r--test/test_vppinfra.py10
-rw-r--r--test/test_vrrp.py626
-rw-r--r--test/test_vtr.py286
-rw-r--r--test/test_vxlan.py236
-rw-r--r--test/test_vxlan6.py146
-rw-r--r--test/test_vxlan_gpe.py185
-rw-r--r--test/test_wireguard.py1155
-rw-r--r--test/util.py188
-rw-r--r--test/vpp_acl.py143
-rw-r--r--test/vpp_bier.py140
-rw-r--r--test/vpp_bond_interface.py52
-rw-r--r--test/vpp_bvi_interface.py5
-rw-r--r--test/vpp_devices.py9
-rw-r--r--test/vpp_dhcp.py75
-rw-r--r--test/vpp_gre_interface.py62
-rw-r--r--test/vpp_igmp.py31
-rw-r--r--test/vpp_ikev2.py172
-rw-r--r--test/vpp_interface.py160
-rw-r--r--test/vpp_ip.py124
-rw-r--r--test/vpp_ip_route.py687
-rw-r--r--test/vpp_ipip_tun_interface.py31
-rw-r--r--test/vpp_ipsec.py226
-rw-r--r--test/vpp_l2.py106
-rw-r--r--test/vpp_lb.py56
-rw-r--r--test/vpp_lo_interface.py2
-rw-r--r--test/vpp_memif.py52
-rw-r--r--test/vpp_mpls_tunnel_interface.py22
-rw-r--r--test/vpp_neighbor.py46
-rw-r--r--test/vpp_object.py27
-rw-r--r--test/vpp_papi_exceptions.py6
-rw-r--r--test/vpp_papi_provider.py1211
-rw-r--r--test/vpp_pg_interface.py256
-rw-r--r--test/vpp_policer.py71
-rw-r--r--test/vpp_pppoe_interface.py28
-rw-r--r--test/vpp_qos.py76
-rw-r--r--test/vpp_srv6.py129
-rw-r--r--test/vpp_sub_interface.py53
-rw-r--r--test/vpp_teib.py26
-rw-r--r--test/vpp_tunnel_interface.py12
-rw-r--r--test/vpp_udp_decap.py13
-rw-r--r--test/vpp_udp_encap.py30
-rw-r--r--test/vpp_vhost_interface.py49
-rw-r--r--test/vpp_vxlan_gpe_tunnel.py68
-rw-r--r--test/vpp_vxlan_tunnel.py80
-rw-r--r--test/vrf.py3
268 files changed, 47066 insertions, 35540 deletions
diff --git a/Makefile b/Makefile
index edadf8a4e7a..609a17418fc 100644
--- a/Makefile
+++ b/Makefile
@@ -232,10 +232,10 @@ help:
@echo " compdb - (re)generate compile_commands.json"
@echo " checkstyle - check coding style"
@echo " checkstyle-commit - check commit message format"
- @echo " checkstyle-test - check test framework coding style"
- @echo " checkstyle-test-diff - check test framework coding style (only changed files)"
+ @echo " checkstyle-python - check python coding style using 'black' formatter"
@echo " checkstyle-api - check api for incompatible changes"
@echo " fixstyle - fix coding style"
+ @echo " fixstyle-python - fix python coding style using 'black' formatter"
@echo " doxygen - DEPRECATED - use 'make docs'"
@echo " bootstrap-doxygen - DEPRECATED"
@echo " wipe-doxygen - DEPRECATED"
@@ -501,13 +501,17 @@ test-wipe-cov:
test-wipe-all:
@make -C test wipe-all
+# Note: All python venv consolidated in test/Makefile, test/requirements*.txt
.PHONY: test-checkstyle
test-checkstyle:
- @make -C test checkstyle
+ $(warning test-checkstyle is deprecated. Running checkstyle-python.")
+ @make -C test checkstyle-python-all
+# Note: All python venv consolidated in test/Makefile, test/requirements*.txt
.PHONY: test-checkstyle-diff
test-checkstyle-diff:
- @make -C test checkstyle-diff
+ $(warning test-checkstyle-diff is deprecated. Running checkstyle-python.")
+ @make -C test checkstyle-python-all
.PHONY: test-refresh-deps
test-refresh-deps:
@@ -664,15 +668,27 @@ checkstyle-commit:
@extras/scripts/check_commit_msg.sh
.PHONY: checkstyle-test
-checkstyle-test: test-checkstyle
+checkstyle-test:
+ $(warning test-checkstyle is deprecated. Running checkstyle-python.")
+ @make -C test checkstyle-python-all
+
+# Note: All python venv consolidated in test/Makefile, test/requirements*.txt
+.PHONY: checkstyle-python
+checkstyle-python:
+ @make -C test checkstyle-python-all
.PHONY: checkstyle-all
-checkstyle-all: checkstyle-commit checkstyle checkstyle-test
+checkstyle-all: checkstyle-commit checkstyle checkstyle-python
.PHONY: fixstyle
fixstyle:
@extras/scripts/checkstyle.sh --fix
+# Note: All python venv consolidated in test/Makefile, test/requirements*.txt
+.PHONY: fixstyle-python
+fixstyle-python:
+ @make -C test fixstyle-python-all
+
.PHONY: checkstyle-api
checkstyle-api:
@extras/scripts/crcchecker.py --check-patchset
diff --git a/docs/_scripts/filter_api.py b/docs/_scripts/filter_api.py
index 484881439b8..e22bc5e50f5 100755
--- a/docs/_scripts/filter_api.py
+++ b/docs/_scripts/filter_api.py
@@ -24,9 +24,10 @@ if len(sys.argv) < 2:
patterns = [
# Search for "define" blocks and treat them as structs
- (re.compile(r"^.*(manual_.[^\s]+\s+)?define\s+(?P<name>[^\s]+)"),
- r"typedef struct vl_api_\g<name>_t"),
-
+ (
+ re.compile(r"^.*(manual_.[^\s]+\s+)?define\s+(?P<name>[^\s]+)"),
+ r"typedef struct vl_api_\g<name>_t",
+ ),
# For every "brief" statement at the start of a comment block, add an
# xref with whatever is on the same line. This gives us an index page
# with all the API methods in one place.
@@ -36,14 +37,13 @@ patterns = [
# r'/** @xrefitem api "" "VPP API" \g<c> \g<b> \g<c>'), # capture inline comment close
# (re.compile(r"/\*\*\s*(?P<b>[\\@]brief)\s+(?P<c>.+)$"),
# r'/** @xrefitem api "" "VPP API" \g<c> \g<b> \g<c>'),
-
# Since structs don't have params, replace @param with @tparam
- ( re.compile("[\\@]param\\b"), "@tparam"),
+ (re.compile("[\\@]param\\b"), "@tparam"),
]
with open(sys.argv[1]) as fd:
for line in fd:
- str = line[:-1] # strip \n
+ str = line[:-1] # strip \n
for p in patterns:
str = p[0].sub(p[1], str)
- sys.stdout.write(str+"\n")
+ sys.stdout.write(str + "\n")
diff --git a/docs/_scripts/filter_c.py b/docs/_scripts/filter_c.py
index 897f9f6d0b3..d3e7ee38762 100755
--- a/docs/_scripts/filter_c.py
+++ b/docs/_scripts/filter_c.py
@@ -23,51 +23,82 @@ if len(sys.argv) < 2:
replace_patterns = [
# Search for VLIB_CLI_COMMAND, extract its parameters and add a docblock for it
- ( re.compile("(?P<m>VLIB_CLI_COMMAND)\s*[(](?P<name>[a-zA-Z0-9_]+)[)]"),
- r"/** @brief (@em constructor) \g<m> (\g<name>) */ vlib_cli_command_t \g<name>"),
- ( re.compile("(?P<m>VLIB_CLI_COMMAND)\s*[(](?P<name>[a-zA-Z0-9_]+),\s*(?P<qual>[^)]*)[)]"),
- r"/** @brief (@em constructor) \g<m> (\g<name>) */ \g<qual> vlib_cli_command_t \g<name>"),
-
+ (
+ re.compile("(?P<m>VLIB_CLI_COMMAND)\s*[(](?P<name>[a-zA-Z0-9_]+)[)]"),
+ r"/** @brief (@em constructor) \g<m> (\g<name>) */ vlib_cli_command_t \g<name>",
+ ),
+ (
+ re.compile(
+ "(?P<m>VLIB_CLI_COMMAND)\s*[(](?P<name>[a-zA-Z0-9_]+),\s*(?P<qual>[^)]*)[)]"
+ ),
+ r"/** @brief (@em constructor) \g<m> (\g<name>) */ \g<qual> vlib_cli_command_t \g<name>",
+ ),
# Search for VLIB_REGISTER_NODE, extract its parameters and add a docblock for it
- ( re.compile("(?P<m>VLIB_REGISTER_NODE)\s*[(](?P<name>[a-zA-Z0-9_]+)[)]"),
- r"/** @brief (@em constructor) \g<m> (\g<name>) */ vlib_node_registration_t \g<name>"),
- ( re.compile("(?P<m>VLIB_REGISTER_NODE)\s*[(](?P<name>[a-zA-Z0-9_]+),\s*(?P<qual>[^)]*)[)]"),
- r"/** @brief (@em constructor) \g<m> (\g<name>) */ \g<qual> vlib_node_registration_t \g<name>"),
-
+ (
+ re.compile("(?P<m>VLIB_REGISTER_NODE)\s*[(](?P<name>[a-zA-Z0-9_]+)[)]"),
+ r"/** @brief (@em constructor) \g<m> (\g<name>) */ vlib_node_registration_t \g<name>",
+ ),
+ (
+ re.compile(
+ "(?P<m>VLIB_REGISTER_NODE)\s*[(](?P<name>[a-zA-Z0-9_]+),\s*(?P<qual>[^)]*)[)]"
+ ),
+ r"/** @brief (@em constructor) \g<m> (\g<name>) */ \g<qual> vlib_node_registration_t \g<name>",
+ ),
# Search for VLIB_INIT_FUNCTION, extract its parameter and add a docblock for it
- ( re.compile("(?P<m>VLIB_INIT_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+)[)]"),
- r"/** @brief (@em constructor) \g<m> (@ref \g<name>) */ vlib_init_function_t * _vlib_init_function_\g<name>"),
- ( re.compile("(?P<m>VLIB_DECLARE_INIT_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+)[)]"),
- r"/** @brief (@em constructor) \g<m> (@ref \g<name>) */ vlib_init_function_t * _vlib_init_function_\g<name>"),
-
+ (
+ re.compile("(?P<m>VLIB_INIT_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+)[)]"),
+ r"/** @brief (@em constructor) \g<m> (@ref \g<name>) */ vlib_init_function_t * _vlib_init_function_\g<name>",
+ ),
+ (
+ re.compile("(?P<m>VLIB_DECLARE_INIT_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+)[)]"),
+ r"/** @brief (@em constructor) \g<m> (@ref \g<name>) */ vlib_init_function_t * _vlib_init_function_\g<name>",
+ ),
# Search for VLIB_LOOP_ENTER_FUNCTION, extract the parameters and add a docblock for it
- ( re.compile("(?P<m>VLIB_MAIN_LOOP_ENTER_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+)(,[^)]*)?[)]"),
- r"/** @brief (@em constructor) \g<m> (@ref \g<name>) */ _vlib_main_loop_enter_\g<name>"),
- ( re.compile("(?P<m>VLIB_MAIN_LOOP_EXIT_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+)(,[^)]*)?[)]"),
- r"/** @brief (@em constructor) \g<m> (@ref \g<name>) */ _vlib_main_loop_exit_\g<name>"),
-
+ (
+ re.compile(
+ "(?P<m>VLIB_MAIN_LOOP_ENTER_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+)(,[^)]*)?[)]"
+ ),
+ r"/** @brief (@em constructor) \g<m> (@ref \g<name>) */ _vlib_main_loop_enter_\g<name>",
+ ),
+ (
+ re.compile(
+ "(?P<m>VLIB_MAIN_LOOP_EXIT_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+)(,[^)]*)?[)]"
+ ),
+ r"/** @brief (@em constructor) \g<m> (@ref \g<name>) */ _vlib_main_loop_exit_\g<name>",
+ ),
# Search for VLIB_CONFIG_FUNCTION, extract the parameters and add a docblock for it
- ( re.compile("(?P<m>VLIB_CONFIG_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+),\s*(?P<n>\"[^\"]+\")(,[^)]*)?[)]"),
- r"/** @brief (@em constructor) \g<m> (\g<name>, \g<n>) */ vlib_config_function_runtime_t _vlib_config_function_\g<name>"),
- ( re.compile("(?P<m>VLIB_EARLY_CONFIG_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+),\s*(?P<n>\"[^\"]+\")(,[^)]*)?[)]"),
- r"/** @brief (@em constructor) \g<m> (\g<name>, \g<n>) */ vlib_config_function_runtime_t _vlib_config_function_\g<name>"),
-
+ (
+ re.compile(
+ '(?P<m>VLIB_CONFIG_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+),\s*(?P<n>"[^"]+")(,[^)]*)?[)]'
+ ),
+ r"/** @brief (@em constructor) \g<m> (\g<name>, \g<n>) */ vlib_config_function_runtime_t _vlib_config_function_\g<name>",
+ ),
+ (
+ re.compile(
+ '(?P<m>VLIB_EARLY_CONFIG_FUNCTION)\s*[(](?P<name>[a-zA-Z0-9_]+),\s*(?P<n>"[^"]+")(,[^)]*)?[)]'
+ ),
+ r"/** @brief (@em constructor) \g<m> (\g<name>, \g<n>) */ vlib_config_function_runtime_t _vlib_config_function_\g<name>",
+ ),
# Search for "format_thing" and "unformat_thing" when used as a function pointer and add parens
- ( re.compile("(?P<pre>(^|,)\s*)(?P<name>(un)?format_[a-zA-Z0-9_]+)(?P<post>\s*(,|$))"),
- r"\g<pre>\g<name>()\g<post>" ),
-
+ (
+ re.compile(
+ "(?P<pre>(^|,)\s*)(?P<name>(un)?format_[a-zA-Z0-9_]+)(?P<post>\s*(,|$))"
+ ),
+ r"\g<pre>\g<name>()\g<post>",
+ ),
# Search for CLIB_PAD_FROM_TO(...); and replace with padding
# #define CLIB_PAD_FROM_TO(from,to) u8 pad_##from[(to) - (from)]
- ( re.compile("(?P<m>CLIB_PAD_FROM_TO)\s*[(](?P<from>[^,]+),\s*(?P<to>[^)]+)[)]"),
- r"/** Padding. */ u8 pad_\g<from>[(\g<to>) - (\g<from>)]" ),
-
+ (
+ re.compile("(?P<m>CLIB_PAD_FROM_TO)\s*[(](?P<from>[^,]+),\s*(?P<to>[^)]+)[)]"),
+ r"/** Padding. */ u8 pad_\g<from>[(\g<to>) - (\g<from>)]",
+ ),
]
filename = sys.argv[1]
cwd = os.getcwd()
-if filename[0:len(cwd)] == cwd:
- filename = filename[len(cwd):]
+if filename[0 : len(cwd)] == cwd:
+ filename = filename[len(cwd) :]
if filename[0] == "/":
filename = filename[1:]
@@ -76,12 +107,12 @@ with open(filename) as fd:
for line in fd:
line_num += 1
- str = line[:-1] # filter \n
+ str = line[:-1] # filter \n
# Look for search/replace patterns
for p in replace_patterns:
str = p[0].sub(p[1], str)
- sys.stdout.write(str+"\n")
+ sys.stdout.write(str + "\n")
# All done
diff --git a/docs/_scripts/filter_h.py b/docs/_scripts/filter_h.py
index 0891fa708e1..31c4c514283 100755
--- a/docs/_scripts/filter_h.py
+++ b/docs/_scripts/filter_h.py
@@ -26,17 +26,19 @@ if len(sys.argv) < 2:
replace_patterns = [
# Search for CLIB_PAD_FROM_TO(...); and replace with padding
# #define CLIB_PAD_FROM_TO(from,to) u8 pad_##from[(to) - (from)]
- (re.compile(r"(?P<m>CLIB_PAD_FROM_TO)\s*[(](?P<from>[^,]+),"
- r"\s*(?P<to>[^)]+)[)]"),
- r"/** Padding. */ u8 pad_\g<from>[(\g<to>) - (\g<from>)]"),
-
+ (
+ re.compile(
+ r"(?P<m>CLIB_PAD_FROM_TO)\s*[(](?P<from>[^,]+)," r"\s*(?P<to>[^)]+)[)]"
+ ),
+ r"/** Padding. */ u8 pad_\g<from>[(\g<to>) - (\g<from>)]",
+ ),
]
filename = sys.argv[1]
cwd = os.getcwd()
-if filename[0:len(cwd)] == cwd:
- filename = filename[len(cwd):]
+if filename[0 : len(cwd)] == cwd:
+ filename = filename[len(cwd) :]
if filename[0] == "/":
filename = filename[1:]
@@ -51,6 +53,6 @@ with open(filename) as fd:
for p in replace_patterns:
str = p[0].sub(p[1], str)
- sys.stdout.write(str+"\n")
+ sys.stdout.write(str + "\n")
# All done
diff --git a/docs/_scripts/includes_renderer.py b/docs/_scripts/includes_renderer.py
index 6bd501d83ff..a2d422b5c18 100644
--- a/docs/_scripts/includes_renderer.py
+++ b/docs/_scripts/includes_renderer.py
@@ -33,15 +33,14 @@ class ContentRenderer:
class PluginRenderer(ContentRenderer):
-
def _render_entry(self, output_file, entry):
description = "<no-description-found>"
# we use glob because a plugin can (ioam for now)
# define the plugin definition in
# a further subdirectory.
- path = os.path.join(self.plugin_dir(), entry.name, '**')
+ path = os.path.join(self.plugin_dir(), entry.name, "**")
for f in glob.iglob(path, recursive=True):
- if not f.endswith('.c'):
+ if not f.endswith(".c"):
continue
with open(f, "r", encoding="utf-8") as src:
for match in self.regex.finditer(src.read()):
@@ -56,7 +55,7 @@ class PluginRenderer(ContentRenderer):
with open(fname, "w") as output_file:
with os.scandir(self.plugin_dir()) as pdir:
for entry in sorted(pdir, key=lambda entry: entry.name):
- if not entry.name.startswith('.') and entry.is_dir():
+ if not entry.name.startswith(".") and entry.is_dir():
self._render_entry(output_file, entry)
diff --git a/docs/_scripts/siphon/generate.py b/docs/_scripts/siphon/generate.py
index 2ae5a1b6f1b..1244c4658e4 100644
--- a/docs/_scripts/siphon/generate.py
+++ b/docs/_scripts/siphon/generate.py
@@ -24,8 +24,10 @@ import re
themselves on this list."""
siphon_patterns = []
+
class Generate(object):
"""Matches a siphon comment block start"""
+
siphon_block_start = re.compile("^\s*/\*\?\s*(.*)$")
"""Matches a siphon comment block stop"""
@@ -36,8 +38,10 @@ class Generate(object):
"""Matches a siphon block directive such as
'%clicmd:group_label Debug CLI%'"""
- siphon_block_directive = re.compile("(%s)\s*([a-zA-Z0-9_:]+)\s+(.*)\s*(%s)" % \
- (siphon_block_delimiter, siphon_block_delimiter))
+ siphon_block_directive = re.compile(
+ "(%s)\s*([a-zA-Z0-9_:]+)\s+(.*)\s*(%s)"
+ % (siphon_block_delimiter, siphon_block_delimiter)
+ )
"""Matches the start of an initializer block"""
siphon_initializer = re.compile("\s*=")
@@ -54,7 +58,6 @@ class Generate(object):
"""Logging handler"""
log = None
-
def __init__(self, output_directory, input_prefix):
super(Generate, self).__init__()
self.log = logging.getLogger("siphon.generate")
@@ -70,14 +73,13 @@ class Generate(object):
self.output = {}
for siphon in self.known_siphons:
self.output[siphon] = {
- "file": "%s/%s.siphon" % (output_directory, siphon),
- "global": {},
- "items": [],
- }
+ "file": "%s/%s.siphon" % (output_directory, siphon),
+ "global": {},
+ "items": [],
+ }
self.input_prefix = input_prefix
-
"""
count open and close braces in str
return (0, index) when braces were found and count becomes 0.
@@ -87,16 +89,17 @@ class Generate(object):
return (count, -1) if not all opening braces are closed, count is the
current depth
"""
+
def count_braces(self, str, count=0, found=False):
for index in range(0, len(str)):
- if str[index] == '{':
- count += 1;
+ if str[index] == "{":
+ count += 1
found = True
- elif str[index] == '}':
+ elif str[index] == "}":
if count == 0:
# means we never found an open brace
return (-1, -1)
- count -= 1;
+ count -= 1
if count == 0 and found:
return (count, index)
@@ -106,8 +109,8 @@ class Generate(object):
def parse(self, filename):
# Strip the current directory off the start of the
# filename for brevity
- if filename[0:len(self.input_prefix)] == self.input_prefix:
- filename = filename[len(self.input_prefix):]
+ if filename[0 : len(self.input_prefix)] == self.input_prefix:
+ filename = filename[len(self.input_prefix) :]
if filename[0] == "/":
filename = filename[1:]
@@ -115,8 +118,8 @@ class Generate(object):
directory = os.path.dirname(filename)
if directory[0:2] == "./":
directory = directory[2:]
- elif directory[0:len(self.input_prefix)] == self.input_prefix:
- directory = directory[len(self.input_prefix):]
+ elif directory[0 : len(self.input_prefix)] == self.input_prefix:
+ directory = directory[len(self.input_prefix) :]
if directory[0] == "/":
directory = directory[1:]
@@ -133,9 +136,10 @@ class Generate(object):
for line in fd:
line_num += 1
- str = line[:-1] # filter \n
+ str = line[:-1] # filter \n
"""See if there is a block directive and if so extract it"""
+
def process_block_directive(str, directives):
m = self.siphon_block_directive.search(str)
if m is not None:
@@ -143,7 +147,7 @@ class Generate(object):
v = m.group(3).strip()
directives[k] = v
# Return only the parts we did not match
- return str[0:m.start(1)] + str[m.end(4):]
+ return str[0 : m.start(1)] + str[m.end(4) :]
return str
@@ -200,27 +204,25 @@ class Generate(object):
# Skip to next line
continue
-
if siphon is None:
# Look for blocks we need to siphon
for p in siphon_patterns:
if p[0].match(str):
- siphon = [ p[1], str + "\n", 0 ]
+ siphon = [p[1], str + "\n", 0]
siphon_line = line_num
# see if we have an initializer
m = self.siphon_initializer.search(str)
if m is not None:
# count the braces on this line
- (count, index) = \
- self.count_braces(str[m.start():])
+ (count, index) = self.count_braces(str[m.start() :])
siphon[2] = count
# TODO - it's possible we have the
# initializer all on the first line
# we should check for it, but also
# account for the possibility that
# the open brace is on the next line
- #if count == 0:
+ # if count == 0:
# # braces balanced
# close_siphon = siphon
# siphon = None
@@ -231,12 +233,11 @@ class Generate(object):
else:
# See if we should end the siphon here - do we have
# balanced braces?
- (count, index) = self.count_braces(str,
- count=siphon[2], found=True)
+ (count, index) = self.count_braces(str, count=siphon[2], found=True)
if count == 0:
# braces balanced - add the substring and
# close the siphon
- siphon[1] += str[:index+1] + ";\n"
+ siphon[1] += str[: index + 1] + ";\n"
close_siphon = siphon
siphon = None
else:
@@ -259,15 +260,15 @@ class Generate(object):
details[key] = directives[key]
# Copy details for this block
- details['file'] = filename
- details['directory'] = directory
- details['line_start'] = siphon_line
- details['line_end'] = line_num
- details['siphon_block'] = siphon_block.strip()
+ details["file"] = filename
+ details["directory"] = directory
+ details["line_start"] = siphon_line
+ details["line_end"] = line_num
+ details["siphon_block"] = siphon_block.strip()
details["block"] = close_siphon[1]
# Store the item
- self.output[siphon_name]['items'].append(details)
+ self.output[siphon_name]["items"].append(details)
# All done
close_siphon = None
@@ -275,7 +276,7 @@ class Generate(object):
# Update globals
for key in directives.keys():
- if ':' not in key:
+ if ":" not in key:
continue
if filename.endswith("/dir.dox"):
@@ -288,19 +289,17 @@ class Generate(object):
if sn not in self.output:
self.output[sn] = {}
- if 'global' not in self.output[sn]:
- self.output[sn]['global'] = {}
- if l not in self.output[sn]['global']:
- self.output[sn]['global'][l] = {}
+ if "global" not in self.output[sn]:
+ self.output[sn]["global"] = {}
+ if l not in self.output[sn]["global"]:
+ self.output[sn]["global"][l] = {}
- self.output[sn]['global'][l][label] = directives[key]
+ self.output[sn]["global"][l][label] = directives[key]
def deliver(self):
# Write out the data
for siphon in self.output.keys():
self.log.info("Saving siphon data %s." % siphon)
s = self.output[siphon]
- with open(s['file'], "a") as fp:
- json.dump(s, fp,
- separators=(',', ': '), indent=4, sort_keys=True)
-
+ with open(s["file"], "a") as fp:
+ json.dump(s, fp, separators=(",", ": "), indent=4, sort_keys=True)
diff --git a/docs/_scripts/siphon/generate_clicmd.py b/docs/_scripts/siphon/generate_clicmd.py
index 6d24aaf4926..2e2f6281a39 100644
--- a/docs/_scripts/siphon/generate_clicmd.py
+++ b/docs/_scripts/siphon/generate_clicmd.py
@@ -17,8 +17,11 @@ import re
from . import generate
# Register our regexp
-generate.siphon_patterns.append((
- re.compile("(?P<m>VLIB_CLI_COMMAND)\s*"
- "[(](?P<name>[a-zA-Z0-9_]+)(,[^)]*)?[)]"),
- "clicmd"
-))
+generate.siphon_patterns.append(
+ (
+ re.compile(
+ "(?P<m>VLIB_CLI_COMMAND)\s*" "[(](?P<name>[a-zA-Z0-9_]+)(,[^)]*)?[)]"
+ ),
+ "clicmd",
+ )
+)
diff --git a/docs/_scripts/siphon/generate_syscfg.py b/docs/_scripts/siphon/generate_syscfg.py
index 52c802e5752..105a59c8262 100644
--- a/docs/_scripts/siphon/generate_syscfg.py
+++ b/docs/_scripts/siphon/generate_syscfg.py
@@ -17,8 +17,12 @@ import re
from . import generate
# Register our regexp
-generate.siphon_patterns.append((
- re.compile("(?P<m>VLIB_CONFIG_FUNCTION)\s*"
- '[(](?P<fn>[a-zA-Z0-9_]+)\s*,\s*"(?P<name>[^"]*)"[)]'),
- "syscfg"
-))
+generate.siphon_patterns.append(
+ (
+ re.compile(
+ "(?P<m>VLIB_CONFIG_FUNCTION)\s*"
+ '[(](?P<fn>[a-zA-Z0-9_]+)\s*,\s*"(?P<name>[^"]*)"[)]'
+ ),
+ "syscfg",
+ )
+)
diff --git a/docs/_scripts/siphon/parsers.py b/docs/_scripts/siphon/parsers.py
index 162205de4ca..1a7d1f59539 100644
--- a/docs/_scripts/siphon/parsers.py
+++ b/docs/_scripts/siphon/parsers.py
@@ -18,9 +18,10 @@ ident = pp.Word(pp.alphas + "_", pp.alphas + pp.nums + "_")
intNum = pp.Word(pp.nums)
hexNum = pp.Literal("0x") + pp.Word(pp.hexnums)
octalNum = pp.Literal("0") + pp.Word("01234567")
-integer = (hexNum | octalNum | intNum) + \
- pp.Optional(pp.Literal("ULL") | pp.Literal("LL") | pp.Literal("L"))
-floatNum = pp.Regex(r'\d+(\.\d*)?([eE]\d+)?') + pp.Optional(pp.Literal("f"))
+integer = (hexNum | octalNum | intNum) + pp.Optional(
+ pp.Literal("ULL") | pp.Literal("LL") | pp.Literal("L")
+)
+floatNum = pp.Regex(r"\d+(\.\d*)?([eE]\d+)?") + pp.Optional(pp.Literal("f"))
char = pp.Literal("'") + pp.Word(pp.printables, exact=1) + pp.Literal("'")
arrayIndex = integer | ident
@@ -36,23 +37,29 @@ semicolon = pp.Literal(";").suppress()
# initializer := { [member = ] (variable | expression | { initializer } ) }
typeName = ident
varName = ident
-typeSpec = pp.Optional("unsigned") + \
- pp.oneOf("int long short float double char u8 i8 void") + \
- pp.Optional(pp.Word("*"), default="")
-typeCast = pp.Combine( "(" + ( typeSpec | typeName ) + ")" ).suppress()
-
-string = pp.Combine(pp.OneOrMore(pp.QuotedString(quoteChar='"',
- escChar='\\', multiline=True)), adjacent=False)
+typeSpec = (
+ pp.Optional("unsigned")
+ + pp.oneOf("int long short float double char u8 i8 void")
+ + pp.Optional(pp.Word("*"), default="")
+)
+typeCast = pp.Combine("(" + (typeSpec | typeName) + ")").suppress()
+
+string = pp.Combine(
+ pp.OneOrMore(pp.QuotedString(quoteChar='"', escChar="\\", multiline=True)),
+ adjacent=False,
+)
literal = pp.Optional(typeCast) + (integer | floatNum | char | string)
-var = pp.Combine(pp.Optional(typeCast) + varName +
- pp.Optional("[" + arrayIndex + "]"))
+var = pp.Combine(pp.Optional(typeCast) + varName + pp.Optional("[" + arrayIndex + "]"))
# This could be more complete, but suffices for our uses
-expr = (literal | var)
+expr = literal | var
"""Parse and render a block of text into a Python dictionary."""
+
+
class Parser(object):
"""Compiled PyParsing BNF"""
+
_parser = None
def __init__(self):
@@ -71,6 +78,8 @@ class Parser(object):
"""Parser for function-like macros - without the closing semi-colon."""
+
+
class ParserFunctionMacro(Parser):
def BNF(self):
# VLIB_CONFIG_FUNCTION (unix_config, "unix")
@@ -91,6 +100,8 @@ class ParserFunctionMacro(Parser):
"""Parser for function-like macros with a closing semi-colon."""
+
+
class ParseFunctionMacroStmt(ParserFunctionMacro):
def BNF(self):
# VLIB_CONFIG_FUNCTION (unix_config, "unix");
@@ -106,6 +117,8 @@ Parser for our struct initializers which are composed from a
function-like macro, equals sign, and then a normal C struct initializer
block.
"""
+
+
class MacroInitializer(ParserFunctionMacro):
def BNF(self):
# VLIB_CLI_COMMAND (show_sr_tunnel_command, static) = {
@@ -115,14 +128,15 @@ class MacroInitializer(ParserFunctionMacro):
# };
cs = pp.Forward()
-
- member = pp.Combine(dot + varName + pp.Optional("[" + arrayIndex + "]"),
- adjacent=False)
- value = (expr | cs)
+ member = pp.Combine(
+ dot + varName + pp.Optional("[" + arrayIndex + "]"), adjacent=False
+ )
+ value = expr | cs
entry = pp.Group(pp.Optional(member + equals, default="") + value)
- entries = (pp.ZeroOrMore(entry + comma) + entry + pp.Optional(comma)) | \
- (pp.ZeroOrMore(entry + comma))
+ entries = (pp.ZeroOrMore(entry + comma) + entry + pp.Optional(comma)) | (
+ pp.ZeroOrMore(entry + comma)
+ )
cs << (lbrace + entries + rbrace)
diff --git a/docs/_scripts/siphon/process.py b/docs/_scripts/siphon/process.py
index e3a70152487..341b7cba299 100644
--- a/docs/_scripts/siphon/process.py
+++ b/docs/_scripts/siphon/process.py
@@ -88,7 +88,8 @@ class Siphon(object):
loader=loader,
trim_blocks=True,
autoescape=False,
- keep_trailing_newline=True)
+ keep_trailing_newline=True,
+ )
# Convenience, get a reference to the internal escape and
# unescape methods in html.parser. These then become
@@ -103,32 +104,38 @@ class Siphon(object):
# Output renderers
"""Returns an object to be used as the sorting key in the item index."""
+
def index_sort_key(self, group):
return group
"""Returns a string to use as the header at the top of the item index."""
+
def index_header(self):
return self.template("index_header")
"""Returns the string fragment to use for each section in the item
index."""
+
def index_section(self, group):
return self.template("index_section", group=group)
"""Returns the string fragment to use for each entry in the item index."""
+
def index_entry(self, meta, item):
return self.template("index_entry", meta=meta, item=item)
"""Returns an object, typically a string, to be used as the sorting key
for items within a section."""
+
def item_sort_key(self, item):
- return item['name']
+ return item["name"]
"""Returns a key for grouping items together."""
+
def group_key(self, directory, file, macro, name):
- _global = self._cmds['_global']
+ _global = self._cmds["_global"]
- if file in _global and 'group_label' in _global[file]:
+ if file in _global and "group_label" in _global[file]:
self._group[file] = (directory, file)
return file
@@ -136,60 +143,59 @@ class Siphon(object):
return directory
"""Returns a key for identifying items within a grouping."""
+
def item_key(self, directory, file, macro, name):
return name
"""Returns a string to use as the header when rendering the item."""
+
def item_header(self, group):
return self.template("item_header", group=group)
"""Returns a string to use as the body when rendering the item."""
+
def item_format(self, meta, item):
return self.template("item_format", meta=meta, item=item)
"""Returns a string to use as the label for the page reference."""
+
def page_label(self, group):
- return "_".join((
- self.name,
- self.sanitize_label(group)
- ))
+ return "_".join((self.name, self.sanitize_label(group)))
"""Returns a title to use for a page."""
+
def page_title(self, group):
- _global = self._cmds['_global']
+ _global = self._cmds["_global"]
(directory, file) = self._group[group]
- if file and file in _global and 'group_label' in _global[file]:
- return _global[file]['group_label']
+ if file and file in _global and "group_label" in _global[file]:
+ return _global[file]["group_label"]
- if directory in _global and 'group_label' in _global[directory]:
- return _global[directory]['group_label']
+ if directory in _global and "group_label" in _global[directory]:
+ return _global[directory]["group_label"]
return directory
"""Returns a string to use as the label for the section reference."""
+
def item_label(self, group, item):
- return "__".join((
- self.name,
- item
- ))
+ return "__".join((self.name, item))
"""Label sanitizer; for creating Doxygen references"""
+
def sanitize_label(self, value):
- return value.replace(" ", "_") \
- .replace("/", "_") \
- .replace(".", "_")
+ return value.replace(" ", "_").replace("/", "_").replace(".", "_")
"""Template processor"""
+
def template(self, name, **kwargs):
tpl = self._tplenv.get_template(name + self._format.extension)
- return tpl.render(
- this=self,
- **kwargs)
+ return tpl.render(this=self, **kwargs)
# Processing methods
"""Parse the input file into a more usable dictionary structure."""
+
def load_json(self, files):
self._cmds = {}
self._group = {}
@@ -198,34 +204,37 @@ class Siphon(object):
line_start = 0
for filename in files:
filename = os.path.relpath(filename)
- self.log.info("Parsing items in file \"%s\"." % filename)
+ self.log.info('Parsing items in file "%s".' % filename)
data = None
with open(filename, "r") as fd:
data = json.load(fd)
- self._cmds['_global'] = data['global']
+ self._cmds["_global"] = data["global"]
# iterate the items loaded and regroup it
for item in data["items"]:
try:
- o = self._parser.parse(item['block'])
+ o = self._parser.parse(item["block"])
except Exception:
- self.log.error("Exception parsing item: %s\n%s"
- % (json.dumps(item, separators=(',', ': '),
- indent=4),
- item['block']))
+ self.log.error(
+ "Exception parsing item: %s\n%s"
+ % (
+ json.dumps(item, separators=(",", ": "), indent=4),
+ item["block"],
+ )
+ )
raise
# Augment the item with metadata
o["meta"] = {}
for key in item:
- if key == 'block':
+ if key == "block":
continue
- o['meta'][key] = item[key]
+ o["meta"][key] = item[key]
# Load some interesting fields
- directory = item['directory']
- file = item['file']
+ directory = item["directory"]
+ file = item["file"]
macro = o["macro"]
name = o["name"]
@@ -240,6 +249,7 @@ class Siphon(object):
"""Iterate over the input data, calling render methods to generate the
output."""
+
def process(self, out=None):
if out is None:
@@ -257,11 +267,12 @@ class Siphon(object):
# Iterate the dictionary and process it
for group in sorted(self._cmds.keys(), key=group_sort_key):
- if group.startswith('_'):
+ if group.startswith("_"):
continue
- self.log.info("Processing items in group \"%s\" (%s)." %
- (group, group_sort_key(group)))
+ self.log.info(
+ 'Processing items in group "%s" (%s).' % (group, group_sort_key(group))
+ )
# Generate the section index entry (write it now)
out.write(self.index_section(group))
@@ -273,15 +284,16 @@ class Siphon(object):
return self.item_sort_key(self._cmds[group][key])
for key in sorted(self._cmds[group].keys(), key=item_sort_key):
- self.log.debug("--- Processing key \"%s\" (%s)." %
- (key, item_sort_key(key)))
+ self.log.debug(
+ '--- Processing key "%s" (%s).' % (key, item_sort_key(key))
+ )
o = self._cmds[group][key]
meta = {
- "directory": o['meta']['directory'],
- "file": o['meta']['file'],
- "macro": o['macro'],
- "name": o['name'],
+ "directory": o["meta"]["directory"],
+ "file": o["meta"]["file"],
+ "macro": o["macro"],
+ "name": o["name"],
"key": key,
"label": self.item_label(group, key),
}
@@ -304,7 +316,7 @@ class Siphon(object):
def do_cliexstart(self, matchobj):
title = matchobj.group(1)
- title = ' '.join(title.splitlines())
+ title = " ".join(title.splitlines())
content = matchobj.group(2)
content = re.sub(r"\n", r"\n ", content)
return "\n\n.. code-block:: console\n\n %s\n %s\n\n" % (title, content)
@@ -316,7 +328,7 @@ class Siphon(object):
def do_cliexcmd(self, matchobj):
content = matchobj.group(1)
- content = ' '.join(content.splitlines())
+ content = " ".join(content.splitlines())
return "\n\n.. code-block:: console\n\n %s\n\n" % content
def process_list(self, matchobj):
@@ -351,7 +363,9 @@ class Siphon(object):
s = re.sub(r"@TODO[^\n]*", "", s)
# ----------- code blocks
s = re.sub(r"@cliexcmd{(.+?)}", self.do_cliexcmd, s, flags=re.DOTALL)
- s = re.sub(r"@cliexstart{(.+?)}(.+?)@cliexend", self.do_cliexstart, s, flags=re.DOTALL)
+ s = re.sub(
+ r"@cliexstart{(.+?)}(.+?)@cliexend", self.do_cliexstart, s, flags=re.DOTALL
+ )
s = re.sub(r"@clistart(.+?)@cliend", self.do_clistart, s, flags=re.DOTALL)
# ----------- lists
s = re.sub(r"^\s*-", r"\n@@@@", s, flags=re.MULTILINE)
@@ -377,6 +391,7 @@ class Siphon(object):
s = re.sub(r"\n[ \f\v\t]*", "\n", s)
return s
+
class Format(object):
"""Output format class"""
@@ -389,6 +404,7 @@ class Format(object):
class FormatMarkdown(Format):
"""Markdown output format"""
+
name = "markdown"
extension = ".md"
@@ -399,6 +415,7 @@ formats["markdown"] = FormatMarkdown
class FormatItemlist(Format):
"""Itemlist output format"""
+
name = "itemlist"
extension = ".itemlist"
diff --git a/docs/_scripts/siphon/process_clicmd.py b/docs/_scripts/siphon/process_clicmd.py
index bf270518ad1..afc24ae6da1 100644
--- a/docs/_scripts/siphon/process_clicmd.py
+++ b/docs/_scripts/siphon/process_clicmd.py
@@ -17,6 +17,7 @@
from . import process, parsers
import os
+
class SiphonCLICMD(process.Siphon):
name = "clicmd"
@@ -32,37 +33,36 @@ class SiphonCLICMD(process.Siphon):
return self.page_label(group) + ".rst"
def index_sort_key(self, group):
- _global = self._cmds['_global']
+ _global = self._cmds["_global"]
if group not in self._group:
return group
(directory, file) = self._group[group]
- if file in _global and 'group_label' in _global[file]:
- return _global[file]['group_label']
+ if file in _global and "group_label" in _global[file]:
+ return _global[file]["group_label"]
- if directory in _global and 'group_label' in _global[directory]:
- return _global[directory]['group_label']
+ if directory in _global and "group_label" in _global[directory]:
+ return _global[directory]["group_label"]
return group
def item_sort_key(self, item):
- return item['value']['path']
+ return item["value"]["path"]
def item_label(self, group, item):
- return "_".join((
- self.name,
- self.sanitize_label(self._cmds[group][item]['value']['path'])
- ))
+ return "_".join(
+ (self.name, self.sanitize_label(self._cmds[group][item]["value"]["path"]))
+ )
def page_title(self, group):
- _global = self._cmds['_global']
+ _global = self._cmds["_global"]
(directory, file) = self._group[group]
- if file and file in _global and 'group_label' in _global[file]:
- return _global[file]['group_label']
+ if file and file in _global and "group_label" in _global[file]:
+ return _global[file]["group_label"]
- if directory in _global and 'group_label' in _global[directory]:
- return _global[directory]['group_label']
+ if directory in _global and "group_label" in _global[directory]:
+ return _global[directory]["group_label"]
file_ext = os.path.basename(directory)
fname, ext = os.path.splitext(file_ext)
diff --git a/docs/conf.py b/docs/conf.py
index 26ccb3f0f7c..550eee8fbe9 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -20,14 +20,16 @@ import subprocess
# -- Project information -----------------------------------------------------
-project = u'The Vector Packet Processor'
-copyright = u'2018-2022, Linux Foundation'
-author = u'FD.io VPP Community'
+project = "The Vector Packet Processor"
+copyright = "2018-2022, Linux Foundation"
+author = "FD.io VPP Community"
# The short X.Y version
version = subprocess.run(["git", "describe"], stdout=subprocess.PIPE, text=True).stdout
# The full version, including alpha/beta/rc tags
-release = subprocess.run(["git", "describe", "--long"], stdout=subprocess.PIPE, text=True).stdout
+release = subprocess.run(
+ ["git", "describe", "--long"], stdout=subprocess.PIPE, text=True
+).stdout
# -- General configuration ---------------------------------------------------
@@ -40,29 +42,27 @@ release = subprocess.run(["git", "describe", "--long"], stdout=subprocess.PIPE,
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
- 'sphinx.ext.autodoc',
- 'sphinx.ext.viewcode',
- 'recommonmark',
- 'sphinxcontrib.spelling']
+ "sphinx.ext.autodoc",
+ "sphinx.ext.viewcode",
+ "recommonmark",
+ "sphinxcontrib.spelling",
+]
-spelling_word_list_filename = 'spelling_wordlist.txt'
+spelling_word_list_filename = "spelling_wordlist.txt"
# do not spell check those files
-spelling_exclude_patterns = ['aboutvpp/releasenotes/*']
+spelling_exclude_patterns = ["aboutvpp/releasenotes/*"]
# Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
+templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
-source_suffix = {
- '.rst': 'restructuredtext',
- '.md': 'markdown'
-}
+source_suffix = {".rst": "restructuredtext", ".md": "markdown"}
# The master toctree document.
-master_doc = 'index'
+master_doc = "index"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@@ -74,10 +74,10 @@ language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
-exclude_patterns = ['Thumbs.db', '.DS_Store', '_scripts', 'venv', '_generated']
+exclude_patterns = ["Thumbs.db", ".DS_Store", "_scripts", "venv", "_generated"]
# The name of the Pygments (syntax highlighting) style to use.
-pygments_style = 'default'
+pygments_style = "default"
# -- Options for HTML output -------------------------------------------------
@@ -88,15 +88,17 @@ pygments_style = 'default'
# import sphinx_theme
-templates_path = ['_templates']
+templates_path = ["_templates"]
html_theme = "sphinx_rtd_theme"
-html_theme_path = ["_themes", ]
+html_theme_path = [
+ "_themes",
+]
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
-html_logo = '_static/fd-io_red_white.png'
+html_logo = "_static/fd-io_red_white.png"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
@@ -107,11 +109,12 @@ html_logo = '_static/fd-io_red_white.png'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
-html_static_path = ['_static']
+html_static_path = ["_static"]
def setup(app):
- app.add_css_file('css/rules.css')
+ app.add_css_file("css/rules.css")
+
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
@@ -127,7 +130,7 @@ def setup(app):
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
-htmlhelp_basename = 'Vector Packet Processor'
+htmlhelp_basename = "Vector Packet Processor"
# -- Options for LaTeX output ------------------------------------------------
@@ -136,15 +139,12 @@ latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
-
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
-
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
-
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
@@ -154,9 +154,13 @@ latex_elements = {
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
- (master_doc, 'Vector Packet Processor.tex',
- u'Vector Packet Processor Documentation',
- u'John DeNisco', 'manual'),
+ (
+ master_doc,
+ "Vector Packet Processor.tex",
+ "Vector Packet Processor Documentation",
+ "John DeNisco",
+ "manual",
+ ),
]
@@ -165,9 +169,13 @@ latex_documents = [
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
- (master_doc, 'Vector Packet Processor',
- u'Vector Packet Processor Documentation',
- [author], 1)
+ (
+ master_doc,
+ "Vector Packet Processor",
+ "Vector Packet Processor Documentation",
+ [author],
+ 1,
+ )
]
@@ -177,10 +185,15 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
- (master_doc, 'Vector Packet Processor',
- u'Vector Packet Processor Documentation',
- author, 'Vector Packet Processor', 'One line description of project.',
- 'Miscellaneous'),
+ (
+ master_doc,
+ "Vector Packet Processor",
+ "Vector Packet Processor Documentation",
+ author,
+ "Vector Packet Processor",
+ "One line description of project.",
+ "Miscellaneous",
+ ),
]
diff --git a/extras/deprecated/perfmon/intel_json_to_c.py b/extras/deprecated/perfmon/intel_json_to_c.py
index 6a625ac2c33..4389c86fc38 100755
--- a/extras/deprecated/perfmon/intel_json_to_c.py
+++ b/extras/deprecated/perfmon/intel_json_to_c.py
@@ -4,48 +4,58 @@ import json, argparse
p = argparse.ArgumentParser()
-p.add_argument('-i', '--input', action="store",
- help="input JSON file name", required = True)
-
-p.add_argument('-o', '--output', action="store",
- help="output C file name", required = True)
-
-p.add_argument('-m', '--model', action="append",
- help="CPU model in format: model[,stepping0]",
- required = True)
+p.add_argument(
+ "-i", "--input", action="store", help="input JSON file name", required=True
+)
+
+p.add_argument(
+ "-o", "--output", action="store", help="output C file name", required=True
+)
+
+p.add_argument(
+ "-m",
+ "--model",
+ action="append",
+ help="CPU model in format: model[,stepping0]",
+ required=True,
+)
r = p.parse_args()
-with open(r.input, 'r') as fp:
+with open(r.input, "r") as fp:
objects = json.load(fp)
-c = open(r.output, 'w')
+c = open(r.output, "w")
-c.write ("""
+c.write(
+ """
#include <perfmon/perfmon_intel.h>
static perfmon_intel_pmc_cpu_model_t cpu_model_table[] = {
-""")
+"""
+)
for v in r.model:
if "," in v:
- (m, s) = v.split(",")
+ (m, s) = v.split(",")
m = int(m, 0)
s = int(s, 0)
- c.write (" {}0x{:02X}, 0x{:02X}, 1{},\n".format("{", m, s, "}"))
+ c.write(" {}0x{:02X}, 0x{:02X}, 1{},\n".format("{", m, s, "}"))
else:
m = int(v, 0)
- c.write (" {}0x{:02X}, 0x00, 0{},\n".format("{", m, "}"))
-c.write ("""
+ c.write(" {}0x{:02X}, 0x00, 0{},\n".format("{", m, "}"))
+c.write(
+ """
};
static perfmon_intel_pmc_event_t event_table[] = {
-""")
+"""
+)
for obj in objects:
MSRIndex = obj["MSRIndex"]
if MSRIndex != "0":
- continue
+ continue
EventCode = obj["EventCode"]
UMask = obj["UMask"]
@@ -53,20 +63,22 @@ for obj in objects:
if "," in EventCode:
continue
- c.write (" {\n")
- c.write (" .event_code = {}{}{},\n".format("{", EventCode, "}"))
- c.write (" .umask = {},\n".format(UMask))
- c.write (" .event_name = \"{}\",\n".format(EventName))
- c.write (" },\n")
+ c.write(" {\n")
+ c.write(" .event_code = {}{}{},\n".format("{", EventCode, "}"))
+ c.write(" .umask = {},\n".format(UMask))
+ c.write(' .event_name = "{}",\n'.format(EventName))
+ c.write(" },\n")
-c.write (""" {
+c.write(
+ """ {
.event_name = 0,
},
};
PERFMON_REGISTER_INTEL_PMC (cpu_model_table, event_table);
-""")
+"""
+)
c.close()
diff --git a/extras/deprecated/plugins/gbp/test_gbp.py b/extras/deprecated/plugins/gbp/test_gbp.py
index c30a729519d..8c53b393f92 100644
--- a/extras/deprecated/plugins/gbp/test_gbp.py
+++ b/extras/deprecated/plugins/gbp/test_gbp.py
@@ -43,16 +43,16 @@ from vpp_l2 import (
from vpp_sub_interface import L2_VTR_OP, VppDot1QSubint
from vpp_ip import DpoProto, get_dpo_proto
from vpp_papi import VppEnum, MACAddress
-from vpp_vxlan_gbp_tunnel import find_vxlan_gbp_tunnel, INDEX_INVALID, \
- VppVxlanGbpTunnel
+from vpp_vxlan_gbp_tunnel import find_vxlan_gbp_tunnel, INDEX_INVALID, VppVxlanGbpTunnel
from vpp_neighbor import VppNeighbor
from vpp_acl import AclRule, VppAcl
NUM_PKTS = 67
-def find_gbp_endpoint(test, sw_if_index=None, ip=None, mac=None,
- tep=None, sclass=None, flags=None):
+def find_gbp_endpoint(
+ test, sw_if_index=None, ip=None, mac=None, tep=None, sclass=None, flags=None
+):
if ip:
vip = ip
if mac:
@@ -64,8 +64,7 @@ def find_gbp_endpoint(test, sw_if_index=None, ip=None, mac=None,
if tep:
src = tep[0]
dst = tep[1]
- if src != str(ep.endpoint.tun.src) or \
- dst != str(ep.endpoint.tun.dst):
+ if src != str(ep.endpoint.tun.src) or dst != str(ep.endpoint.tun.dst):
continue
if sw_if_index:
if ep.endpoint.sw_if_index != sw_if_index:
@@ -128,11 +127,21 @@ class VppGbpEndpoint(VppObject):
def fips(self):
return [self.fip4, self.fip6]
- def __init__(self, test, itf, epg, recirc, ip4, fip4, ip6, fip6,
- flags=0,
- tun_src="0.0.0.0",
- tun_dst="0.0.0.0",
- mac=True):
+ def __init__(
+ self,
+ test,
+ itf,
+ epg,
+ recirc,
+ ip4,
+ fip4,
+ ip6,
+ fip6,
+ flags=0,
+ tun_src="0.0.0.0",
+ tun_dst="0.0.0.0",
+ mac=True,
+ ):
self._test = test
self.itf = itf
self.handle = None
@@ -179,15 +188,15 @@ class VppGbpEndpoint(VppObject):
self._test.vapi.gbp_endpoint_del(handle=self.handle)
def object_id(self):
- return "gbp-endpoint:[%d==%d:%s:%d]" % (self.handle,
- self.itf.sw_if_index,
- self.ip4,
- self.epg.sclass)
+ return "gbp-endpoint:[%d==%d:%s:%d]" % (
+ self.handle,
+ self.itf.sw_if_index,
+ self.ip4,
+ self.epg.sclass,
+ )
def query_vpp_config(self):
- return find_gbp_endpoint(self._test,
- self.itf.sw_if_index,
- self.ip4)
+ return find_gbp_endpoint(self._test, self.itf.sw_if_index, self.ip4)
class VppGbpRecirc(VppObject):
@@ -266,8 +275,10 @@ class VppGbpExtItf(VppObject):
)
def object_id(self):
- return "gbp-ext-itf:[%d]%s" % (self.itf.sw_if_index,
- " [anon]" if self.flags else "")
+ return "gbp-ext-itf:[%d]%s" % (
+ self.itf.sw_if_index,
+ " [anon]" if self.flags else "",
+ )
def query_vpp_config(self):
rs = self._test.vapi.gbp_ext_itf_dump()
@@ -282,19 +293,25 @@ class VppGbpSubnet(VppObject):
GBP Subnet
"""
- def __init__(self, test, rd, address, address_len,
- type, sw_if_index=0xffffffff, sclass=0xffff):
+ def __init__(
+ self,
+ test,
+ rd,
+ address,
+ address_len,
+ type,
+ sw_if_index=0xFFFFFFFF,
+ sclass=0xFFFF,
+ ):
# TODO: replace hardcoded defaults when vpp_papi supports
# defaults in typedefs
self._test = test
self.rd_id = rd.rd_id
a = ip_address(address)
if 4 == a.version:
- self.prefix = IPv4Network("%s/%d" % (address, address_len),
- strict=False)
+ self.prefix = IPv4Network("%s/%d" % (address, address_len), strict=False)
else:
- self.prefix = IPv6Network("%s/%d" % (address, address_len),
- strict=False)
+ self.prefix = IPv6Network("%s/%d" % (address, address_len), strict=False)
self.type = type
self.sw_if_index = sw_if_index
self.sclass = sclass
@@ -316,10 +333,7 @@ class VppGbpSubnet(VppObject):
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
- self._test.vapi.gbp_subnet_add_del(
- is_add=0,
- subnet=self.encode()
- )
+ self._test.vapi.gbp_subnet_add_del(is_add=0, subnet=self.encode())
def object_id(self):
return "gbp-subnet:[%d-%s]" % (self.rd_id, self.prefix)
@@ -327,19 +341,21 @@ class VppGbpSubnet(VppObject):
def query_vpp_config(self):
ss = self._test.vapi.gbp_subnet_dump()
for s in ss:
- if s.subnet.rd_id == self.rd_id and \
- s.subnet.type == self.type and \
- s.subnet.prefix == self.prefix:
+ if (
+ s.subnet.rd_id == self.rd_id
+ and s.subnet.type == self.type
+ and s.subnet.prefix == self.prefix
+ ):
return True
return False
class VppGbpEndpointRetention(object):
- def __init__(self, remote_ep_timeout=0xffffffff):
+ def __init__(self, remote_ep_timeout=0xFFFFFFFF):
self.remote_ep_timeout = remote_ep_timeout
def encode(self):
- return {'remote_ep_timeout': self.remote_ep_timeout}
+ return {"remote_ep_timeout": self.remote_ep_timeout}
class VppGbpEndpointGroup(VppObject):
@@ -347,9 +363,19 @@ class VppGbpEndpointGroup(VppObject):
GBP Endpoint Group
"""
- def __init__(self, test, vnid, sclass, rd, bd, uplink,
- bvi, bvi_ip4, bvi_ip6=None,
- retention=VppGbpEndpointRetention()):
+ def __init__(
+ self,
+ test,
+ vnid,
+ sclass,
+ rd,
+ bd,
+ uplink,
+ bvi,
+ bvi_ip4,
+ bvi_ip6=None,
+ retention=VppGbpEndpointRetention(),
+ ):
self._test = test
self.uplink = uplink
self.bvi = bvi
@@ -360,13 +386,14 @@ class VppGbpEndpointGroup(VppObject):
self.rd = rd
self.sclass = sclass
if 0 == self.sclass:
- self.sclass = 0xffff
+ self.sclass = 0xFFFF
self.retention = retention
def encode(self) -> dict:
return {
"uplink_sw_if_index": self.uplink.sw_if_index
- if self.uplink else INDEX_INVALID,
+ if self.uplink
+ else INDEX_INVALID,
"bd_id": self.bd.bd.bd_id,
"rd_id": self.rd.rd_id,
"vnid": self.vnid,
@@ -397,11 +424,19 @@ class VppGbpBridgeDomain(VppObject):
GBP Bridge Domain
"""
- def __init__(self, test, bd, rd, bvi,
- uu_fwd: typing.Optional[VppVxlanGbpTunnel] = None,
- bm_flood=None, learn=True,
- uu_drop=False, bm_drop=False,
- ucast_arp=False):
+ def __init__(
+ self,
+ test,
+ bd,
+ rd,
+ bvi,
+ uu_fwd: typing.Optional[VppVxlanGbpTunnel] = None,
+ bm_flood=None,
+ learn=True,
+ uu_drop=False,
+ bm_drop=False,
+ ucast_arp=False,
+ ):
self._test = test
self.bvi = bvi
self.uu_fwd = uu_fwd
@@ -426,9 +461,11 @@ class VppGbpBridgeDomain(VppObject):
"flags": self.flags,
"bvi_sw_if_index": self.bvi.sw_if_index,
"uu_fwd_sw_if_index": self.uu_fwd.sw_if_index
- if self.uu_fwd else INDEX_INVALID,
+ if self.uu_fwd
+ else INDEX_INVALID,
"bm_flood_sw_if_index": self.bm_flood.sw_if_index
- if self.bm_flood else INDEX_INVALID,
+ if self.bm_flood
+ else INDEX_INVALID,
"bd_id": self.bd.bd_id,
"rd_id": self.rd.rd_id,
}
@@ -474,10 +511,11 @@ class VppGbpRouteDomain(VppObject):
"ip4_table_id": self.t4.table_id,
"ip6_table_id": self.t6.table_id,
"ip4_uu_sw_if_index": self.ip4_uu.sw_if_index
- if self.ip4_uu else INDEX_INVALID,
+ if self.ip4_uu
+ else INDEX_INVALID,
"ip6_uu_sw_if_index": self.ip6_uu.sw_if_index
- if self.ip6_uu else INDEX_INVALID,
-
+ if self.ip6_uu
+ else INDEX_INVALID,
}
def add_vpp_config(self):
@@ -528,15 +566,16 @@ class VppGbpContractRule:
nhs.append(nh.encode())
while len(nhs) < 8:
nhs.append({})
- return {'action': self.action,
- 'nh_set': {
- 'hash_mode': self.hash_mode,
- 'n_nhs': len(self.nhs),
- 'nhs': nhs}}
+ return {
+ "action": self.action,
+ "nh_set": {"hash_mode": self.hash_mode, "n_nhs": len(self.nhs), "nhs": nhs},
+ }
def __repr__(self):
- return '<VppGbpContractRule action=%s, hash_mode=%s>' % (
- self.action, self.hash_mode)
+ return "<VppGbpContractRule action=%s, hash_mode=%s>" % (
+ self.action,
+ self.hash_mode,
+ )
class VppGbpContract(VppObject):
@@ -544,8 +583,16 @@ class VppGbpContract(VppObject):
GBP Contract
"""
- def __init__(self, test, scope, sclass, dclass, acl_index,
- rules: list, allowed_ethertypes: list):
+ def __init__(
+ self,
+ test,
+ scope,
+ sclass,
+ dclass,
+ acl_index,
+ rules: list,
+ allowed_ethertypes: list,
+ ):
self._test = test
self.scope = scope
self.acl_index = acl_index
@@ -553,7 +600,7 @@ class VppGbpContract(VppObject):
self.dclass = dclass
self.rules = rules
self.allowed_ethertypes = allowed_ethertypes
- while (len(self.allowed_ethertypes) < 16):
+ while len(self.allowed_ethertypes) < 16:
self.allowed_ethertypes.append(0)
def encode(self) -> dict:
@@ -561,21 +608,18 @@ class VppGbpContract(VppObject):
for r in self.rules:
rules.append(r.encode())
return {
- 'acl_index': self.acl_index,
- 'scope': self.scope,
- 'sclass': self.sclass,
- 'dclass': self.dclass,
- 'n_rules': len(rules),
- 'rules': rules,
- 'n_ether_types': len(self.allowed_ethertypes),
- 'allowed_ethertypes': self.allowed_ethertypes,
+ "acl_index": self.acl_index,
+ "scope": self.scope,
+ "sclass": self.sclass,
+ "dclass": self.dclass,
+ "n_rules": len(rules),
+ "rules": rules,
+ "n_ether_types": len(self.allowed_ethertypes),
+ "allowed_ethertypes": self.allowed_ethertypes,
}
def add_vpp_config(self):
- r = self._test.vapi.gbp_contract_add_del(
- is_add=1,
- contract=self.encode()
- )
+ r = self._test.vapi.gbp_contract_add_del(is_add=1, contract=self.encode())
self.stats_index = r.stats_index
self._test.registry.register(self, self._test.logger)
@@ -587,17 +631,21 @@ class VppGbpContract(VppObject):
)
def object_id(self):
- return "gbp-contract:[%d:%d:%d:%d]" % (self.scope,
- self.sclass,
- self.dclass,
- self.acl_index)
+ return "gbp-contract:[%d:%d:%d:%d]" % (
+ self.scope,
+ self.sclass,
+ self.dclass,
+ self.acl_index,
+ )
def query_vpp_config(self):
cs = self._test.vapi.gbp_contract_dump()
for c in cs:
- if c.contract.scope == self.scope \
- and c.contract.sclass == self.sclass \
- and c.contract.dclass == self.dclass:
+ if (
+ c.contract.scope == self.scope
+ and c.contract.sclass == self.sclass
+ and c.contract.dclass == self.dclass
+ ):
return True
return False
@@ -650,7 +698,7 @@ class VppGbpVxlanTunnel(VppInterface):
@tag_fixme_vpp_workers
class TestGBP(VppTestCase):
- """ GBP Test Case """
+ """GBP Test Case"""
@property
def nat_config_flags(self):
@@ -817,7 +865,7 @@ class TestGBP(VppTestCase):
return rx
def test_gbp(self):
- """ Group Based Policy """
+ """Group Based Policy"""
ep_flags = VppEnum.vl_api_gbp_endpoint_flags_t
@@ -862,26 +910,70 @@ class TestGBP(VppTestCase):
# 3 EPGs, 2 of which share a BD.
# 2 NAT EPGs, one for floating-IP subnets, the other for internet
#
- epgs = [VppGbpEndpointGroup(self, 220, 1220, rd0, gbd1,
- self.pg4, self.loop0,
- "10.0.0.128", "2001:10::128"),
- VppGbpEndpointGroup(self, 221, 1221, rd0, gbd1,
- self.pg5, self.loop0,
- "10.0.1.128", "2001:10:1::128"),
- VppGbpEndpointGroup(self, 222, 1222, rd0, gbd2,
- self.pg6, self.loop1,
- "10.0.2.128", "2001:10:2::128"),
- VppGbpEndpointGroup(self, 333, 1333, rd20, gbd20,
- self.pg7, self.loop2,
- "11.0.0.128", "3001::128"),
- VppGbpEndpointGroup(self, 444, 1444, rd20, gbd20,
- self.pg8, self.loop2,
- "11.0.0.129", "3001::129")]
- recircs = [VppGbpRecirc(self, epgs[0], self.loop3),
- VppGbpRecirc(self, epgs[1], self.loop4),
- VppGbpRecirc(self, epgs[2], self.loop5),
- VppGbpRecirc(self, epgs[3], self.loop6, is_ext=True),
- VppGbpRecirc(self, epgs[4], self.loop7, is_ext=True)]
+ epgs = [
+ VppGbpEndpointGroup(
+ self,
+ 220,
+ 1220,
+ rd0,
+ gbd1,
+ self.pg4,
+ self.loop0,
+ "10.0.0.128",
+ "2001:10::128",
+ ),
+ VppGbpEndpointGroup(
+ self,
+ 221,
+ 1221,
+ rd0,
+ gbd1,
+ self.pg5,
+ self.loop0,
+ "10.0.1.128",
+ "2001:10:1::128",
+ ),
+ VppGbpEndpointGroup(
+ self,
+ 222,
+ 1222,
+ rd0,
+ gbd2,
+ self.pg6,
+ self.loop1,
+ "10.0.2.128",
+ "2001:10:2::128",
+ ),
+ VppGbpEndpointGroup(
+ self,
+ 333,
+ 1333,
+ rd20,
+ gbd20,
+ self.pg7,
+ self.loop2,
+ "11.0.0.128",
+ "3001::128",
+ ),
+ VppGbpEndpointGroup(
+ self,
+ 444,
+ 1444,
+ rd20,
+ gbd20,
+ self.pg8,
+ self.loop2,
+ "11.0.0.129",
+ "3001::129",
+ ),
+ ]
+ recircs = [
+ VppGbpRecirc(self, epgs[0], self.loop3),
+ VppGbpRecirc(self, epgs[1], self.loop4),
+ VppGbpRecirc(self, epgs[2], self.loop5),
+ VppGbpRecirc(self, epgs[3], self.loop6, is_ext=True),
+ VppGbpRecirc(self, epgs[4], self.loop7, is_ext=True),
+ ]
epg_nat = epgs[3]
recirc_nat = recircs[3]
@@ -889,22 +981,48 @@ class TestGBP(VppTestCase):
#
# 4 end-points, 2 in the same subnet, 3 in the same BD
#
- eps = [VppGbpEndpoint(self, self.pg0,
- epgs[0], recircs[0],
- "10.0.0.1", "11.0.0.1",
- "2001:10::1", "3001::1"),
- VppGbpEndpoint(self, self.pg1,
- epgs[0], recircs[0],
- "10.0.0.2", "11.0.0.2",
- "2001:10::2", "3001::2"),
- VppGbpEndpoint(self, self.pg2,
- epgs[1], recircs[1],
- "10.0.1.1", "11.0.0.3",
- "2001:10:1::1", "3001::3"),
- VppGbpEndpoint(self, self.pg3,
- epgs[2], recircs[2],
- "10.0.2.1", "11.0.0.4",
- "2001:10:2::1", "3001::4")]
+ eps = [
+ VppGbpEndpoint(
+ self,
+ self.pg0,
+ epgs[0],
+ recircs[0],
+ "10.0.0.1",
+ "11.0.0.1",
+ "2001:10::1",
+ "3001::1",
+ ),
+ VppGbpEndpoint(
+ self,
+ self.pg1,
+ epgs[0],
+ recircs[0],
+ "10.0.0.2",
+ "11.0.0.2",
+ "2001:10::2",
+ "3001::2",
+ ),
+ VppGbpEndpoint(
+ self,
+ self.pg2,
+ epgs[1],
+ recircs[1],
+ "10.0.1.1",
+ "11.0.0.3",
+ "2001:10:1::1",
+ "3001::3",
+ ),
+ VppGbpEndpoint(
+ self,
+ self.pg3,
+ epgs[2],
+ recircs[2],
+ "10.0.2.1",
+ "11.0.0.4",
+ "2001:10:2::1",
+ "3001::4",
+ ),
+ ]
self.vapi.nat44_ed_plugin_enable_disable(enable=1)
self.vapi.nat66_plugin_enable_disable(enable=1)
@@ -915,39 +1033,37 @@ class TestGBP(VppTestCase):
for epg in epgs:
# IP config on the BVI interfaces
if epg != epgs[1] and epg != epgs[4]:
- b4 = VppIpInterfaceBind(self, epg.bvi,
- epg.rd.t4).add_vpp_config()
- b6 = VppIpInterfaceBind(self, epg.bvi,
- epg.rd.t6).add_vpp_config()
+ b4 = VppIpInterfaceBind(self, epg.bvi, epg.rd.t4).add_vpp_config()
+ b6 = VppIpInterfaceBind(self, epg.bvi, epg.rd.t6).add_vpp_config()
epg.bvi.set_mac(self.router_mac)
# The BVIs are NAT inside interfaces
flags = self.nat_config_flags.NAT_IS_INSIDE
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=epg.bvi.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=epg.bvi.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat66_add_del_interface(
- sw_if_index=epg.bvi.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=epg.bvi.sw_if_index, flags=flags, is_add=1
+ )
- if_ip4 = VppIpInterfaceAddress(self, epg.bvi,
- epg.bvi_ip4, 32,
- bind=b4).add_vpp_config()
- if_ip6 = VppIpInterfaceAddress(self, epg.bvi,
- epg.bvi_ip6, 128,
- bind=b6).add_vpp_config()
+ if_ip4 = VppIpInterfaceAddress(
+ self, epg.bvi, epg.bvi_ip4, 32, bind=b4
+ ).add_vpp_config()
+ if_ip6 = VppIpInterfaceAddress(
+ self, epg.bvi, epg.bvi_ip6, 128, bind=b6
+ ).add_vpp_config()
# EPG uplink interfaces in the RD
VppIpInterfaceBind(self, epg.uplink, epg.rd.t4).add_vpp_config()
VppIpInterfaceBind(self, epg.uplink, epg.rd.t6).add_vpp_config()
# add the BD ARP termination entry for BVI IP
- epg.bd_arp_ip4 = VppBridgeDomainArpEntry(self, epg.bd.bd,
- str(self.router_mac),
- epg.bvi_ip4)
- epg.bd_arp_ip6 = VppBridgeDomainArpEntry(self, epg.bd.bd,
- str(self.router_mac),
- epg.bvi_ip6)
+ epg.bd_arp_ip4 = VppBridgeDomainArpEntry(
+ self, epg.bd.bd, str(self.router_mac), epg.bvi_ip4
+ )
+ epg.bd_arp_ip6 = VppBridgeDomainArpEntry(
+ self, epg.bd.bd, str(self.router_mac), epg.bvi_ip6
+ )
epg.bd_arp_ip4.add_vpp_config()
epg.bd_arp_ip6.add_vpp_config()
@@ -956,22 +1072,24 @@ class TestGBP(VppTestCase):
for recirc in recircs:
# EPG's ingress recirculation interface maps to its RD
- VppIpInterfaceBind(self, recirc.recirc,
- recirc.epg.rd.t4).add_vpp_config()
- VppIpInterfaceBind(self, recirc.recirc,
- recirc.epg.rd.t6).add_vpp_config()
+ VppIpInterfaceBind(self, recirc.recirc, recirc.epg.rd.t4).add_vpp_config()
+ VppIpInterfaceBind(self, recirc.recirc, recirc.epg.rd.t6).add_vpp_config()
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=recirc.recirc.sw_if_index, is_add=1)
+ sw_if_index=recirc.recirc.sw_if_index, is_add=1
+ )
self.vapi.nat66_add_del_interface(
- sw_if_index=recirc.recirc.sw_if_index, is_add=1)
+ sw_if_index=recirc.recirc.sw_if_index, is_add=1
+ )
recirc.add_vpp_config()
for recirc in recircs:
- self.assertTrue(find_bridge_domain_port(self,
- recirc.epg.bd.bd.bd_id,
- recirc.recirc.sw_if_index))
+ self.assertTrue(
+ find_bridge_domain_port(
+ self, recirc.epg.bd.bd.bd_id, recirc.recirc.sw_if_index
+ )
+ )
for ep in eps:
self.pg_enable_capture(self.pg_interfaces)
@@ -991,12 +1109,12 @@ class TestGBP(VppTestCase):
external_ip_address=fip,
external_sw_if_index=0xFFFFFFFF,
vrf_id=0,
- flags=flags)
+ flags=flags,
+ )
else:
self.vapi.nat66_add_del_static_mapping(
- local_ip_address=ip,
- external_ip_address=fip,
- vrf_id=0, is_add=1)
+ local_ip_address=ip, external_ip_address=fip, vrf_id=0, is_add=1
+ )
# VPP EP create ...
ep.add_vpp_config()
@@ -1019,36 +1137,41 @@ class TestGBP(VppTestCase):
# add the BD ARP termination entry for floating IP
for fip in ep.fips:
- ba = VppBridgeDomainArpEntry(self, epg_nat.bd.bd, ep.mac,
- fip)
+ ba = VppBridgeDomainArpEntry(self, epg_nat.bd.bd, ep.mac, fip)
ba.add_vpp_config()
# floating IPs route via EPG recirc
r = VppIpRoute(
- self, fip, ip_address(fip).max_prefixlen,
- [VppRoutePath(fip,
- ep.recirc.recirc.sw_if_index,
- type=FibPathType.FIB_PATH_TYPE_DVR,
- proto=get_dpo_proto(fip))],
- table_id=20)
+ self,
+ fip,
+ ip_address(fip).max_prefixlen,
+ [
+ VppRoutePath(
+ fip,
+ ep.recirc.recirc.sw_if_index,
+ type=FibPathType.FIB_PATH_TYPE_DVR,
+ proto=get_dpo_proto(fip),
+ )
+ ],
+ table_id=20,
+ )
r.add_vpp_config()
# L2 FIB entries in the NAT EPG BD to bridge the packets from
# the outside direct to the internal EPG
- lf = VppL2FibEntry(self, epg_nat.bd.bd, ep.mac,
- ep.recirc.recirc, bvi_mac=0)
+ lf = VppL2FibEntry(self, epg_nat.bd.bd, ep.mac, ep.recirc.recirc, bvi_mac=0)
lf.add_vpp_config()
#
# ARP packets for unknown IP are sent to the EPG uplink
#
- pkt_arp = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg0.remote_mac) /
- ARP(op="who-has",
- hwdst="ff:ff:ff:ff:ff:ff",
- hwsrc=self.pg0.remote_mac,
- pdst="10.0.0.88",
- psrc="10.0.0.99"))
+ pkt_arp = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op="who-has",
+ hwdst="ff:ff:ff:ff:ff:ff",
+ hwsrc=self.pg0.remote_mac,
+ pdst="10.0.0.88",
+ psrc="10.0.0.99",
+ )
self.vapi.cli("clear trace")
self.pg0.add_stream(pkt_arp)
@@ -1061,33 +1184,35 @@ class TestGBP(VppTestCase):
#
# ARP/ND packets get a response
#
- pkt_arp = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg0.remote_mac) /
- ARP(op="who-has",
- hwdst="ff:ff:ff:ff:ff:ff",
- hwsrc=self.pg0.remote_mac,
- pdst=epgs[0].bvi_ip4,
- psrc=eps[0].ip4))
+ pkt_arp = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op="who-has",
+ hwdst="ff:ff:ff:ff:ff:ff",
+ hwsrc=self.pg0.remote_mac,
+ pdst=epgs[0].bvi_ip4,
+ psrc=eps[0].ip4,
+ )
self.send_and_expect(self.pg0, [pkt_arp], self.pg0)
nsma = in6_getnsma(inet_pton(AF_INET6, eps[0].ip6))
d = inet_ntop(AF_INET6, nsma)
- pkt_nd = (Ether(dst=in6_getnsmac(nsma),
- src=self.pg0.remote_mac) /
- IPv6(dst=d, src=eps[0].ip6) /
- ICMPv6ND_NS(tgt=epgs[0].bvi_ip6) /
- ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac))
+ pkt_nd = (
+ Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac)
+ / IPv6(dst=d, src=eps[0].ip6)
+ / ICMPv6ND_NS(tgt=epgs[0].bvi_ip6)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac)
+ )
self.send_and_expect(self.pg0, [pkt_nd], self.pg0)
#
# broadcast packets are flooded
#
- pkt_bcast = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg0.remote_mac) /
- IP(src=eps[0].ip4, dst="232.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_bcast = (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac)
+ / IP(src=eps[0].ip4, dst="232.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.vapi.cli("clear trace")
self.pg0.add_stream(pkt_bcast)
@@ -1103,52 +1228,74 @@ class TestGBP(VppTestCase):
#
# packets to non-local L3 destinations dropped
#
- pkt_intra_epg_220_ip4 = (Ether(src=self.pg0.remote_mac,
- dst=str(self.router_mac)) /
- IP(src=eps[0].ip4,
- dst="10.0.0.99") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- pkt_inter_epg_222_ip4 = (Ether(src=self.pg0.remote_mac,
- dst=str(self.router_mac)) /
- IP(src=eps[0].ip4,
- dst="10.0.1.99") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
-
- self.send_and_assert_no_replies(self.pg0,
- pkt_intra_epg_220_ip4 * NUM_PKTS)
-
- pkt_inter_epg_222_ip6 = (Ether(src=self.pg0.remote_mac,
- dst=str(self.router_mac)) /
- IPv6(src=eps[0].ip6,
- dst="2001:10::99") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- self.send_and_assert_no_replies(self.pg0,
- pkt_inter_epg_222_ip6 * NUM_PKTS)
+ pkt_intra_epg_220_ip4 = (
+ Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src=eps[0].ip4, dst="10.0.0.99")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ pkt_inter_epg_222_ip4 = (
+ Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src=eps[0].ip4, dst="10.0.1.99")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+
+ self.send_and_assert_no_replies(self.pg0, pkt_intra_epg_220_ip4 * NUM_PKTS)
+
+ pkt_inter_epg_222_ip6 = (
+ Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IPv6(src=eps[0].ip6, dst="2001:10::99")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ self.send_and_assert_no_replies(self.pg0, pkt_inter_epg_222_ip6 * NUM_PKTS)
#
# Add the subnet routes
#
s41 = VppGbpSubnet(
- self, rd0, "10.0.0.0", 24,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL)
+ self,
+ rd0,
+ "10.0.0.0",
+ 24,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL,
+ )
s42 = VppGbpSubnet(
- self, rd0, "10.0.1.0", 24,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL)
+ self,
+ rd0,
+ "10.0.1.0",
+ 24,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL,
+ )
s43 = VppGbpSubnet(
- self, rd0, "10.0.2.0", 24,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL)
+ self,
+ rd0,
+ "10.0.2.0",
+ 24,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL,
+ )
s61 = VppGbpSubnet(
- self, rd0, "2001:10::1", 64,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL)
+ self,
+ rd0,
+ "2001:10::1",
+ 64,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL,
+ )
s62 = VppGbpSubnet(
- self, rd0, "2001:10:1::1", 64,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL)
+ self,
+ rd0,
+ "2001:10:1::1",
+ 64,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL,
+ )
s63 = VppGbpSubnet(
- self, rd0, "2001:10:2::1", 64,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL)
+ self,
+ rd0,
+ "2001:10:2::1",
+ 64,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_INTERNAL,
+ )
s41.add_vpp_config()
s42.add_vpp_config()
s43.add_vpp_config()
@@ -1156,15 +1303,15 @@ class TestGBP(VppTestCase):
s62.add_vpp_config()
s63.add_vpp_config()
- self.send_and_expect_bridged(eps[0].itf,
- pkt_intra_epg_220_ip4 * NUM_PKTS,
- eps[0].epg.uplink)
- self.send_and_expect_bridged(eps[0].itf,
- pkt_inter_epg_222_ip4 * NUM_PKTS,
- eps[0].epg.uplink)
- self.send_and_expect_bridged6(eps[0].itf,
- pkt_inter_epg_222_ip6 * NUM_PKTS,
- eps[0].epg.uplink)
+ self.send_and_expect_bridged(
+ eps[0].itf, pkt_intra_epg_220_ip4 * NUM_PKTS, eps[0].epg.uplink
+ )
+ self.send_and_expect_bridged(
+ eps[0].itf, pkt_inter_epg_222_ip4 * NUM_PKTS, eps[0].epg.uplink
+ )
+ self.send_and_expect_bridged6(
+ eps[0].itf, pkt_inter_epg_222_ip6 * NUM_PKTS, eps[0].epg.uplink
+ )
self.logger.info(self.vapi.cli("sh ip fib 11.0.0.2"))
self.logger.info(self.vapi.cli("sh gbp endpoint-group"))
@@ -1180,182 +1327,210 @@ class TestGBP(VppTestCase):
#
# Packet destined to unknown unicast is sent on the epg uplink ...
#
- pkt_intra_epg_220_to_uplink = (Ether(src=self.pg0.remote_mac,
- dst="00:00:00:33:44:55") /
- IP(src=eps[0].ip4,
- dst="10.0.0.99") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_intra_epg_220_to_uplink = (
+ Ether(src=self.pg0.remote_mac, dst="00:00:00:33:44:55")
+ / IP(src=eps[0].ip4, dst="10.0.0.99")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- self.send_and_expect_bridged(eps[0].itf,
- pkt_intra_epg_220_to_uplink * NUM_PKTS,
- eps[0].epg.uplink)
+ self.send_and_expect_bridged(
+ eps[0].itf, pkt_intra_epg_220_to_uplink * NUM_PKTS, eps[0].epg.uplink
+ )
# ... and nowhere else
self.pg1.get_capture(0, timeout=0.1)
self.pg1.assert_nothing_captured(remark="Flood onto other VMS")
- pkt_intra_epg_221_to_uplink = (Ether(src=self.pg2.remote_mac,
- dst="00:00:00:33:44:66") /
- IP(src=eps[0].ip4,
- dst="10.0.0.99") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_intra_epg_221_to_uplink = (
+ Ether(src=self.pg2.remote_mac, dst="00:00:00:33:44:66")
+ / IP(src=eps[0].ip4, dst="10.0.0.99")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- self.send_and_expect_bridged(eps[2].itf,
- pkt_intra_epg_221_to_uplink * NUM_PKTS,
- eps[2].epg.uplink)
+ self.send_and_expect_bridged(
+ eps[2].itf, pkt_intra_epg_221_to_uplink * NUM_PKTS, eps[2].epg.uplink
+ )
#
# Packets from the uplink are forwarded in the absence of a contract
#
- pkt_intra_epg_220_from_uplink = (Ether(src="00:00:00:33:44:55",
- dst=self.pg0.remote_mac) /
- IP(src=eps[0].ip4,
- dst="10.0.0.99") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_intra_epg_220_from_uplink = (
+ Ether(src="00:00:00:33:44:55", dst=self.pg0.remote_mac)
+ / IP(src=eps[0].ip4, dst="10.0.0.99")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- self.send_and_expect_bridged(self.pg4,
- pkt_intra_epg_220_from_uplink * NUM_PKTS,
- self.pg0)
+ self.send_and_expect_bridged(
+ self.pg4, pkt_intra_epg_220_from_uplink * NUM_PKTS, self.pg0
+ )
#
# in the absence of policy, endpoints in the same EPG
# can communicate
#
- pkt_intra_epg = (Ether(src=self.pg0.remote_mac,
- dst=self.pg1.remote_mac) /
- IP(src=eps[0].ip4,
- dst=eps[1].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_intra_epg = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg1.remote_mac)
+ / IP(src=eps[0].ip4, dst=eps[1].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- self.send_and_expect_bridged(self.pg0,
- pkt_intra_epg * NUM_PKTS,
- self.pg1)
+ self.send_and_expect_bridged(self.pg0, pkt_intra_epg * NUM_PKTS, self.pg1)
#
# in the absence of policy, endpoints in the different EPG
# cannot communicate
#
- pkt_inter_epg_220_to_221 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg2.remote_mac) /
- IP(src=eps[0].ip4,
- dst=eps[2].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- pkt_inter_epg_221_to_220 = (Ether(src=self.pg2.remote_mac,
- dst=self.pg0.remote_mac) /
- IP(src=eps[2].ip4,
- dst=eps[0].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- pkt_inter_epg_220_to_222 = (Ether(src=self.pg0.remote_mac,
- dst=str(self.router_mac)) /
- IP(src=eps[0].ip4,
- dst=eps[3].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
-
- self.send_and_assert_no_replies(eps[0].itf,
- pkt_inter_epg_220_to_221 * NUM_PKTS)
- self.send_and_assert_no_replies(eps[0].itf,
- pkt_inter_epg_220_to_222 * NUM_PKTS)
+ pkt_inter_epg_220_to_221 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg2.remote_mac)
+ / IP(src=eps[0].ip4, dst=eps[2].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ pkt_inter_epg_221_to_220 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg0.remote_mac)
+ / IP(src=eps[2].ip4, dst=eps[0].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ pkt_inter_epg_220_to_222 = (
+ Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src=eps[0].ip4, dst=eps[3].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+
+ self.send_and_assert_no_replies(eps[0].itf, pkt_inter_epg_220_to_221 * NUM_PKTS)
+ self.send_and_assert_no_replies(eps[0].itf, pkt_inter_epg_220_to_222 * NUM_PKTS)
#
# A uni-directional contract from EPG 220 -> 221
#
rule = AclRule(is_permit=1, proto=17)
- rule2 = AclRule(src_prefix=IPv6Network((0, 0)),
- dst_prefix=IPv6Network((0, 0)), is_permit=1, proto=17)
+ rule2 = AclRule(
+ src_prefix=IPv6Network((0, 0)),
+ dst_prefix=IPv6Network((0, 0)),
+ is_permit=1,
+ proto=17,
+ )
acl = VppAcl(self, rules=[rule, rule2])
acl.add_vpp_config()
c1 = VppGbpContract(
- self, 400, epgs[0].sclass, epgs[1].sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 400,
+ epgs[0].sclass,
+ epgs[1].sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c1.add_vpp_config()
- self.send_and_expect_bridged(eps[0].itf,
- pkt_inter_epg_220_to_221 * NUM_PKTS,
- eps[2].itf)
- self.send_and_assert_no_replies(eps[0].itf,
- pkt_inter_epg_220_to_222 * NUM_PKTS)
+ self.send_and_expect_bridged(
+ eps[0].itf, pkt_inter_epg_220_to_221 * NUM_PKTS, eps[2].itf
+ )
+ self.send_and_assert_no_replies(eps[0].itf, pkt_inter_epg_220_to_222 * NUM_PKTS)
#
# contract for the return direction
#
c2 = VppGbpContract(
- self, 400, epgs[1].sclass, epgs[0].sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 400,
+ epgs[1].sclass,
+ epgs[0].sclass,
+ acl.acl_index,
+ [
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c2.add_vpp_config()
- self.send_and_expect_bridged(eps[0].itf,
- pkt_inter_epg_220_to_221 * NUM_PKTS,
- eps[2].itf)
- self.send_and_expect_bridged(eps[2].itf,
- pkt_inter_epg_221_to_220 * NUM_PKTS,
- eps[0].itf)
+ self.send_and_expect_bridged(
+ eps[0].itf, pkt_inter_epg_220_to_221 * NUM_PKTS, eps[2].itf
+ )
+ self.send_and_expect_bridged(
+ eps[2].itf, pkt_inter_epg_221_to_220 * NUM_PKTS, eps[0].itf
+ )
ds = c2.get_drop_stats()
- self.assertEqual(ds['packets'], 0)
+ self.assertEqual(ds["packets"], 0)
ps = c2.get_permit_stats()
- self.assertEqual(ps['packets'], NUM_PKTS)
+ self.assertEqual(ps["packets"], NUM_PKTS)
#
# the contract does not allow non-IP
#
- pkt_non_ip_inter_epg_220_to_221 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg2.remote_mac) /
- ARP())
- self.send_and_assert_no_replies(eps[0].itf,
- pkt_non_ip_inter_epg_220_to_221 * 17)
+ pkt_non_ip_inter_epg_220_to_221 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg2.remote_mac) / ARP()
+ )
+ self.send_and_assert_no_replies(
+ eps[0].itf, pkt_non_ip_inter_epg_220_to_221 * 17
+ )
#
# check that inter group is still disabled for the groups
# not in the contract.
#
- self.send_and_assert_no_replies(eps[0].itf,
- pkt_inter_epg_220_to_222 * NUM_PKTS)
+ self.send_and_assert_no_replies(eps[0].itf, pkt_inter_epg_220_to_222 * NUM_PKTS)
#
# A uni-directional contract from EPG 220 -> 222 'L3 routed'
#
c3 = VppGbpContract(
- self, 400, epgs[0].sclass, epgs[2].sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 400,
+ epgs[0].sclass,
+ epgs[2].sclass,
+ acl.acl_index,
+ [
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c3.add_vpp_config()
self.logger.info(self.vapi.cli("sh gbp contract"))
- self.send_and_expect_routed(eps[0].itf,
- pkt_inter_epg_220_to_222 * NUM_PKTS,
- eps[3].itf,
- str(self.router_mac))
+ self.send_and_expect_routed(
+ eps[0].itf,
+ pkt_inter_epg_220_to_222 * NUM_PKTS,
+ eps[3].itf,
+ str(self.router_mac),
+ )
#
# remove both contracts, traffic stops in both directions
#
@@ -1364,13 +1539,9 @@ class TestGBP(VppTestCase):
c3.remove_vpp_config()
acl.remove_vpp_config()
- self.send_and_assert_no_replies(eps[2].itf,
- pkt_inter_epg_221_to_220 * NUM_PKTS)
- self.send_and_assert_no_replies(eps[0].itf,
- pkt_inter_epg_220_to_221 * NUM_PKTS)
- self.send_and_expect_bridged(eps[0].itf,
- pkt_intra_epg * NUM_PKTS,
- eps[1].itf)
+ self.send_and_assert_no_replies(eps[2].itf, pkt_inter_epg_221_to_220 * NUM_PKTS)
+ self.send_and_assert_no_replies(eps[0].itf, pkt_inter_epg_220_to_221 * NUM_PKTS)
+ self.send_and_expect_bridged(eps[0].itf, pkt_intra_epg * NUM_PKTS, eps[1].itf)
#
# EPs to the outside world
@@ -1378,36 +1549,60 @@ class TestGBP(VppTestCase):
# in the EP's RD an external subnet via the NAT EPG's recirc
se1 = VppGbpSubnet(
- self, rd0, "0.0.0.0", 0,
+ self,
+ rd0,
+ "0.0.0.0",
+ 0,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_EXTERNAL,
sw_if_index=recirc_nat.recirc.sw_if_index,
- sclass=epg_nat.sclass)
+ sclass=epg_nat.sclass,
+ )
se2 = VppGbpSubnet(
- self, rd0, "11.0.0.0", 8,
+ self,
+ rd0,
+ "11.0.0.0",
+ 8,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_EXTERNAL,
sw_if_index=recirc_nat.recirc.sw_if_index,
- sclass=epg_nat.sclass)
+ sclass=epg_nat.sclass,
+ )
se16 = VppGbpSubnet(
- self, rd0, "::", 0,
+ self,
+ rd0,
+ "::",
+ 0,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_EXTERNAL,
sw_if_index=recirc_nat.recirc.sw_if_index,
- sclass=epg_nat.sclass)
+ sclass=epg_nat.sclass,
+ )
# in the NAT RD an external subnet via the NAT EPG's uplink
se3 = VppGbpSubnet(
- self, rd20, "0.0.0.0", 0,
+ self,
+ rd20,
+ "0.0.0.0",
+ 0,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_EXTERNAL,
sw_if_index=epg_nat.uplink.sw_if_index,
- sclass=epg_nat.sclass)
+ sclass=epg_nat.sclass,
+ )
se36 = VppGbpSubnet(
- self, rd20, "::", 0,
+ self,
+ rd20,
+ "::",
+ 0,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_EXTERNAL,
sw_if_index=epg_nat.uplink.sw_if_index,
- sclass=epg_nat.sclass)
+ sclass=epg_nat.sclass,
+ )
se4 = VppGbpSubnet(
- self, rd20, "11.0.0.0", 8,
+ self,
+ rd20,
+ "11.0.0.0",
+ 8,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_STITCHED_EXTERNAL,
sw_if_index=epg_nat.uplink.sw_if_index,
- sclass=epg_nat.sclass)
+ sclass=epg_nat.sclass,
+ )
se1.add_vpp_config()
se2.add_vpp_config()
se16.add_vpp_config()
@@ -1418,132 +1613,153 @@ class TestGBP(VppTestCase):
self.logger.info(self.vapi.cli("sh ip fib 0.0.0.0/0"))
self.logger.info(self.vapi.cli("sh ip fib 11.0.0.1"))
self.logger.info(self.vapi.cli("sh ip6 fib ::/0"))
- self.logger.info(self.vapi.cli("sh ip6 fib %s" %
- eps[0].fip6))
+ self.logger.info(self.vapi.cli("sh ip6 fib %s" % eps[0].fip6))
#
# From an EP to an outside address: IN2OUT
#
- pkt_inter_epg_220_to_global = (Ether(src=self.pg0.remote_mac,
- dst=str(self.router_mac)) /
- IP(src=eps[0].ip4,
- dst="1.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_inter_epg_220_to_global = (
+ Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src=eps[0].ip4, dst="1.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
# no policy yet
- self.send_and_assert_no_replies(eps[0].itf,
- pkt_inter_epg_220_to_global * NUM_PKTS)
+ self.send_and_assert_no_replies(
+ eps[0].itf, pkt_inter_epg_220_to_global * NUM_PKTS
+ )
rule = AclRule(is_permit=1, proto=17, ports=1234)
- rule2 = AclRule(is_permit=1, proto=17, ports=1234,
- src_prefix=IPv6Network((0, 0)),
- dst_prefix=IPv6Network((0, 0)))
+ rule2 = AclRule(
+ is_permit=1,
+ proto=17,
+ ports=1234,
+ src_prefix=IPv6Network((0, 0)),
+ dst_prefix=IPv6Network((0, 0)),
+ )
acl2 = VppAcl(self, rules=[rule, rule2])
acl2.add_vpp_config()
c4 = VppGbpContract(
- self, 400, epgs[0].sclass, epgs[3].sclass, acl2.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 400,
+ epgs[0].sclass,
+ epgs[3].sclass,
+ acl2.acl_index,
+ [
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c4.add_vpp_config()
- self.send_and_expect_natted(eps[0].itf,
- pkt_inter_epg_220_to_global * NUM_PKTS,
- self.pg7,
- eps[0].fip4)
+ self.send_and_expect_natted(
+ eps[0].itf, pkt_inter_epg_220_to_global * NUM_PKTS, self.pg7, eps[0].fip4
+ )
- pkt_inter_epg_220_to_global = (Ether(src=self.pg0.remote_mac,
- dst=str(self.router_mac)) /
- IPv6(src=eps[0].ip6,
- dst="6001::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_inter_epg_220_to_global = (
+ Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IPv6(src=eps[0].ip6, dst="6001::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- self.send_and_expect_natted6(self.pg0,
- pkt_inter_epg_220_to_global * NUM_PKTS,
- self.pg7,
- eps[0].fip6)
+ self.send_and_expect_natted6(
+ self.pg0, pkt_inter_epg_220_to_global * NUM_PKTS, self.pg7, eps[0].fip6
+ )
#
# From a global address to an EP: OUT2IN
#
- pkt_inter_epg_220_from_global = (Ether(src=str(self.router_mac),
- dst=self.pg0.remote_mac) /
- IP(dst=eps[0].fip4,
- src="1.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_inter_epg_220_from_global = (
+ Ether(src=str(self.router_mac), dst=self.pg0.remote_mac)
+ / IP(dst=eps[0].fip4, src="1.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_assert_no_replies(
- self.pg7, pkt_inter_epg_220_from_global * NUM_PKTS)
+ self.pg7, pkt_inter_epg_220_from_global * NUM_PKTS
+ )
c5 = VppGbpContract(
- self, 400, epgs[3].sclass, epgs[0].sclass, acl2.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 400,
+ epgs[3].sclass,
+ epgs[0].sclass,
+ acl2.acl_index,
+ [
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c5.add_vpp_config()
- self.send_and_expect_unnatted(self.pg7,
- pkt_inter_epg_220_from_global * NUM_PKTS,
- eps[0].itf,
- eps[0].ip4)
+ self.send_and_expect_unnatted(
+ self.pg7, pkt_inter_epg_220_from_global * NUM_PKTS, eps[0].itf, eps[0].ip4
+ )
- pkt_inter_epg_220_from_global = (Ether(src=str(self.router_mac),
- dst=self.pg0.remote_mac) /
- IPv6(dst=eps[0].fip6,
- src="6001::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_inter_epg_220_from_global = (
+ Ether(src=str(self.router_mac), dst=self.pg0.remote_mac)
+ / IPv6(dst=eps[0].fip6, src="6001::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect_unnatted6(
- self.pg7,
- pkt_inter_epg_220_from_global * NUM_PKTS,
- eps[0].itf,
- eps[0].ip6)
+ self.pg7, pkt_inter_epg_220_from_global * NUM_PKTS, eps[0].itf, eps[0].ip6
+ )
#
# From a local VM to another local VM using resp. public addresses:
# IN2OUT2IN
#
- pkt_intra_epg_220_global = (Ether(src=self.pg0.remote_mac,
- dst=str(self.router_mac)) /
- IP(src=eps[0].ip4,
- dst=eps[1].fip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
-
- self.send_and_expect_double_natted(eps[0].itf,
- pkt_intra_epg_220_global * NUM_PKTS,
- eps[1].itf,
- eps[0].fip4,
- eps[1].ip4)
-
- pkt_intra_epg_220_global = (Ether(src=self.pg0.remote_mac,
- dst=str(self.router_mac)) /
- IPv6(src=eps[0].ip6,
- dst=eps[1].fip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_intra_epg_220_global = (
+ Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src=eps[0].ip4, dst=eps[1].fip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+
+ self.send_and_expect_double_natted(
+ eps[0].itf,
+ pkt_intra_epg_220_global * NUM_PKTS,
+ eps[1].itf,
+ eps[0].fip4,
+ eps[1].ip4,
+ )
+
+ pkt_intra_epg_220_global = (
+ Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IPv6(src=eps[0].ip6, dst=eps[1].fip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect_double_natted6(
eps[0].itf,
pkt_intra_epg_220_global * NUM_PKTS,
eps[1].itf,
eps[0].fip6,
- eps[1].ip6)
+ eps[1].ip6,
+ )
#
# cleanup
@@ -1551,36 +1767,37 @@ class TestGBP(VppTestCase):
self.vapi.nat44_ed_plugin_enable_disable(enable=0)
self.vapi.nat66_plugin_enable_disable(enable=0)
- def wait_for_ep_timeout(self, sw_if_index=None, ip=None, mac=None,
- tep=None, n_tries=100, s_time=1):
+ def wait_for_ep_timeout(
+ self, sw_if_index=None, ip=None, mac=None, tep=None, n_tries=100, s_time=1
+ ):
# only learnt EP can timeout
ep_flags = VppEnum.vl_api_gbp_endpoint_flags_t
flags = ep_flags.GBP_API_ENDPOINT_FLAG_LEARNT
- while (n_tries):
- if not find_gbp_endpoint(self, sw_if_index, ip, mac, tep=tep,
- flags=flags):
+ while n_tries:
+ if not find_gbp_endpoint(self, sw_if_index, ip, mac, tep=tep, flags=flags):
return True
n_tries = n_tries - 1
self.sleep(s_time)
- self.assertFalse(find_gbp_endpoint(self, sw_if_index, ip, mac, tep=tep,
- flags=flags))
+ self.assertFalse(
+ find_gbp_endpoint(self, sw_if_index, ip, mac, tep=tep, flags=flags)
+ )
return False
def test_gbp_learn_l2(self):
- """ GBP L2 Endpoint Learning """
+ """GBP L2 Endpoint Learning"""
drop_no_contract = self.statistics.get_err_counter(
- '/err/gbp-policy-port/drop-no-contract')
+ "/err/gbp-policy-port/drop-no-contract"
+ )
allow_intra_class = self.statistics.get_err_counter(
- '/err/gbp-policy-port/allow-intra-sclass')
+ "/err/gbp-policy-port/allow-intra-sclass"
+ )
ep_flags = VppEnum.vl_api_gbp_endpoint_flags_t
- learnt = [{'mac': '00:00:11:11:11:01',
- 'ip': '10.0.0.1',
- 'ip6': '2001:10::2'},
- {'mac': '00:00:11:11:11:02',
- 'ip': '10.0.0.2',
- 'ip6': '2001:10::3'}]
+ learnt = [
+ {"mac": "00:00:11:11:11:01", "ip": "10.0.0.1", "ip6": "2001:10::2"},
+ {"mac": "00:00:11:11:11:02", "ip": "10.0.0.2", "ip6": "2001:10::3"},
+ ]
#
# IP tables
@@ -1610,9 +1827,9 @@ class TestGBP(VppTestCase):
#
# Add a mcast destination VXLAN-GBP tunnel for B&M traffic
#
- tun_bm = VppVxlanGbpTunnel(self, self.pg4.local_ip4,
- "239.1.1.1", 88,
- mcast_itf=self.pg4)
+ tun_bm = VppVxlanGbpTunnel(
+ self, self.pg4.local_ip4, "239.1.1.1", 88, mcast_itf=self.pg4
+ )
tun_bm.add_vpp_config()
#
@@ -1620,8 +1837,7 @@ class TestGBP(VppTestCase):
#
bd1 = VppBridgeDomain(self, 1)
bd1.add_vpp_config()
- gbd1 = VppGbpBridgeDomain(self, bd1, rd1, self.loop0,
- self.pg3, tun_bm)
+ gbd1 = VppGbpBridgeDomain(self, bd1, rd1, self.loop0, self.pg3, tun_bm)
gbd1.add_vpp_config()
self.logger.info(self.vapi.cli("sh bridge 1 detail"))
@@ -1634,17 +1850,31 @@ class TestGBP(VppTestCase):
#
# The Endpoint-group in which we are learning endpoints
#
- epg_220 = VppGbpEndpointGroup(self, 220, 112, rd1, gbd1,
- None, self.loop0,
- "10.0.0.128",
- "2001:10::128",
- VppGbpEndpointRetention(4))
+ epg_220 = VppGbpEndpointGroup(
+ self,
+ 220,
+ 112,
+ rd1,
+ gbd1,
+ None,
+ self.loop0,
+ "10.0.0.128",
+ "2001:10::128",
+ VppGbpEndpointRetention(4),
+ )
epg_220.add_vpp_config()
- epg_330 = VppGbpEndpointGroup(self, 330, 113, rd1, gbd1,
- None, self.loop1,
- "10.0.1.128",
- "2001:11::128",
- VppGbpEndpointRetention(4))
+ epg_330 = VppGbpEndpointGroup(
+ self,
+ 330,
+ 113,
+ rd1,
+ gbd1,
+ None,
+ self.loop1,
+ "10.0.1.128",
+ "2001:11::128",
+ VppGbpEndpointRetention(4),
+ )
epg_330.add_vpp_config()
#
@@ -1652,51 +1882,61 @@ class TestGBP(VppTestCase):
# learning enabled
#
vx_tun_l2_1 = VppGbpVxlanTunnel(
- self, 99, bd1.bd_id,
+ self,
+ 99,
+ bd1.bd_id,
VppEnum.vl_api_gbp_vxlan_tunnel_mode_t.GBP_VXLAN_TUNNEL_MODE_L2,
- self.pg2.local_ip4)
+ self.pg2.local_ip4,
+ )
vx_tun_l2_1.add_vpp_config()
#
# A static endpoint that the learnt endpoints are trying to
# talk to
#
- ep = VppGbpEndpoint(self, self.pg0,
- epg_220, None,
- "10.0.0.127", "11.0.0.127",
- "2001:10::1", "3001::1")
+ ep = VppGbpEndpoint(
+ self,
+ self.pg0,
+ epg_220,
+ None,
+ "10.0.0.127",
+ "11.0.0.127",
+ "2001:10::1",
+ "3001::1",
+ )
ep.add_vpp_config()
self.assertTrue(find_route(self, ep.ip4, 32, table_id=1))
# a packet with an sclass from an unknown EPG
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[0].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=99, gpid=88, flags=0x88) /
- Ether(src=learnt[0]["mac"], dst=ep.mac) /
- IP(src=learnt[0]["ip"], dst=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[0].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=99, gpid=88, flags=0x88)
+ / Ether(src=learnt[0]["mac"], dst=ep.mac)
+ / IP(src=learnt[0]["ip"], dst=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_assert_no_replies(self.pg2, p)
self.logger.info(self.vapi.cli("sh error"))
self.assert_error_counter_equal(
- '/err/gbp-policy-port/drop-no-contract',
- drop_no_contract + 1)
+ "/err/gbp-policy-port/drop-no-contract", drop_no_contract + 1
+ )
#
# we should not have learnt a new tunnel endpoint, since
# the EPG was not learnt.
#
- self.assertEqual(INDEX_INVALID,
- find_vxlan_gbp_tunnel(self,
- self.pg2.local_ip4,
- self.pg2.remote_hosts[0].ip4,
- 99))
+ self.assertEqual(
+ INDEX_INVALID,
+ find_vxlan_gbp_tunnel(
+ self, self.pg2.local_ip4, self.pg2.remote_hosts[0].ip4, 99
+ ),
+ )
# ep is not learnt, because the EPG is unknown
self.assertEqual(len(self.vapi.gbp_endpoint_dump()), 1)
@@ -1707,41 +1947,39 @@ class TestGBP(VppTestCase):
for ii, l in enumerate(learnt):
# a packet with an sclass from a known EPG
# arriving on an unknown TEP
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=99, gpid=112, flags=0x88) /
- Ether(src=l['mac'], dst=ep.mac) /
- IP(src=l['ip'], dst=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=99, gpid=112, flags=0x88)
+ / Ether(src=l["mac"], dst=ep.mac)
+ / IP(src=l["ip"], dst=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, [p], self.pg0)
# the new TEP
tep1_sw_if_index = find_vxlan_gbp_tunnel(
- self,
- self.pg2.local_ip4,
- self.pg2.remote_hosts[1].ip4,
- 99)
+ self, self.pg2.local_ip4, self.pg2.remote_hosts[1].ip4, 99
+ )
self.assertNotEqual(INDEX_INVALID, tep1_sw_if_index)
#
# the EP is learnt via the learnt TEP
# both from its MAC and its IP
#
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l2_1.sw_if_index,
- mac=l['mac']))
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l2_1.sw_if_index,
- ip=l['ip']))
+ self.assertTrue(
+ find_gbp_endpoint(self, vx_tun_l2_1.sw_if_index, mac=l["mac"])
+ )
+ self.assertTrue(
+ find_gbp_endpoint(self, vx_tun_l2_1.sw_if_index, ip=l["ip"])
+ )
self.assert_error_counter_equal(
- '/err/gbp-policy-port/allow-intra-sclass',
- allow_intra_class + 2)
+ "/err/gbp-policy-port/allow-intra-sclass", allow_intra_class + 2
+ )
self.logger.info(self.vapi.cli("show gbp endpoint"))
self.logger.info(self.vapi.cli("show gbp vxlan"))
@@ -1752,8 +1990,7 @@ class TestGBP(VppTestCase):
# age out
#
for l in learnt:
- self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index,
- mac=l['mac'])
+ self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index, mac=l["mac"])
#
# Learn new EPs from GARP packets received on the BD's mcast tunnel
@@ -1762,44 +1999,45 @@ class TestGBP(VppTestCase):
# add some junk in the reserved field of the vxlan-header
# next to the VNI. we should accept since reserved bits are
# ignored on rx.
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst="239.1.1.1") /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=88, reserved2=0x80, gpid=112, flags=0x88) /
- Ether(src=l['mac'], dst="ff:ff:ff:ff:ff:ff") /
- ARP(op="who-has",
- psrc=l['ip'], pdst=l['ip'],
- hwsrc=l['mac'], hwdst="ff:ff:ff:ff:ff:ff"))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst="239.1.1.1")
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=88, reserved2=0x80, gpid=112, flags=0x88)
+ / Ether(src=l["mac"], dst="ff:ff:ff:ff:ff:ff")
+ / ARP(
+ op="who-has",
+ psrc=l["ip"],
+ pdst=l["ip"],
+ hwsrc=l["mac"],
+ hwdst="ff:ff:ff:ff:ff:ff",
+ )
+ )
rx = self.send_and_expect(self.pg4, [p], self.pg0)
# the new TEP
tep1_sw_if_index = find_vxlan_gbp_tunnel(
- self,
- self.pg2.local_ip4,
- self.pg2.remote_hosts[1].ip4,
- 99)
+ self, self.pg2.local_ip4, self.pg2.remote_hosts[1].ip4, 99
+ )
self.assertNotEqual(INDEX_INVALID, tep1_sw_if_index)
#
# the EP is learnt via the learnt TEP
# both from its MAC and its IP
#
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l2_1.sw_if_index,
- mac=l['mac']))
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l2_1.sw_if_index,
- ip=l['ip']))
+ self.assertTrue(
+ find_gbp_endpoint(self, vx_tun_l2_1.sw_if_index, mac=l["mac"])
+ )
+ self.assertTrue(
+ find_gbp_endpoint(self, vx_tun_l2_1.sw_if_index, ip=l["ip"])
+ )
#
# wait for the learnt endpoints to age out
#
for l in learnt:
- self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index,
- mac=l['mac'])
+ self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index, mac=l["mac"])
#
# Learn new EPs from L2 packets
@@ -1807,32 +2045,30 @@ class TestGBP(VppTestCase):
for ii, l in enumerate(learnt):
# a packet with an sclass from a known EPG
# arriving on an unknown TEP
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=99, gpid=112, flags=0x88) /
- Ether(src=l['mac'], dst=ep.mac) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=99, gpid=112, flags=0x88)
+ / Ether(src=l["mac"], dst=ep.mac)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, [p], self.pg0)
# the new TEP
tep1_sw_if_index = find_vxlan_gbp_tunnel(
- self,
- self.pg2.local_ip4,
- self.pg2.remote_hosts[1].ip4,
- 99)
+ self, self.pg2.local_ip4, self.pg2.remote_hosts[1].ip4, 99
+ )
self.assertNotEqual(INDEX_INVALID, tep1_sw_if_index)
#
# the EP is learnt via the learnt TEP
# both from its MAC and its IP
#
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l2_1.sw_if_index,
- mac=l['mac']))
+ self.assertTrue(
+ find_gbp_endpoint(self, vx_tun_l2_1.sw_if_index, mac=l["mac"])
+ )
self.logger.info(self.vapi.cli("show gbp endpoint"))
self.logger.info(self.vapi.cli("show gbp vxlan"))
@@ -1842,31 +2078,30 @@ class TestGBP(VppTestCase):
# wait for the learnt endpoints to age out
#
for l in learnt:
- self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index,
- mac=l['mac'])
+ self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index, mac=l["mac"])
#
# repeat. the do not learn bit is set so the EPs are not learnt
#
for l in learnt:
# a packet with an sclass from a known EPG
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=99, gpid=112, flags=0x88, gpflags="D") /
- Ether(src=l['mac'], dst=ep.mac) /
- IP(src=l['ip'], dst=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=99, gpid=112, flags=0x88, gpflags="D")
+ / Ether(src=l["mac"], dst=ep.mac)
+ / IP(src=l["ip"], dst=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, p * NUM_PKTS, self.pg0)
for l in learnt:
- self.assertFalse(find_gbp_endpoint(self,
- vx_tun_l2_1.sw_if_index,
- mac=l['mac']))
+ self.assertFalse(
+ find_gbp_endpoint(self, vx_tun_l2_1.sw_if_index, mac=l["mac"])
+ )
#
# repeat
@@ -1875,32 +2110,34 @@ class TestGBP(VppTestCase):
# a packet with an sclass from a known EPG
# set a reserved bit in addition to the G and I
# reserved bits should not be checked on rx.
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=99, gpid=112, flags=0xc8) /
- Ether(src=l['mac'], dst=ep.mac) /
- IP(src=l['ip'], dst=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=99, gpid=112, flags=0xC8)
+ / Ether(src=l["mac"], dst=ep.mac)
+ / IP(src=l["ip"], dst=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, p * NUM_PKTS, self.pg0)
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l2_1.sw_if_index,
- mac=l['mac']))
+ self.assertTrue(
+ find_gbp_endpoint(self, vx_tun_l2_1.sw_if_index, mac=l["mac"])
+ )
#
# Static EP replies to dynamics
#
self.logger.info(self.vapi.cli("sh l2fib bd_id 1"))
for l in learnt:
- p = (Ether(src=ep.mac, dst=l['mac']) /
- IP(dst=l['ip'], src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=l["mac"])
+ / IP(dst=l["ip"], src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * 17, self.pg2)
@@ -1917,8 +2154,7 @@ class TestGBP(VppTestCase):
self.assertFalse(rx[VXLAN].gpflags.D)
for l in learnt:
- self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index,
- mac=l['mac'])
+ self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index, mac=l["mac"])
#
# repeat in the other EPG
@@ -1927,31 +2163,33 @@ class TestGBP(VppTestCase):
#
for l in learnt:
# a packet with an sclass from a known EPG
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=99, gpid=113, flags=0x88, gpflags='A') /
- Ether(src=l['mac'], dst=ep.mac) /
- IP(src=l['ip'], dst=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=99, gpid=113, flags=0x88, gpflags="A")
+ / Ether(src=l["mac"], dst=ep.mac)
+ / IP(src=l["ip"], dst=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, p * NUM_PKTS, self.pg0)
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l2_1.sw_if_index,
- mac=l['mac']))
+ self.assertTrue(
+ find_gbp_endpoint(self, vx_tun_l2_1.sw_if_index, mac=l["mac"])
+ )
#
# static EP cannot reach the learnt EPs since there is no contract
# only test 1 EP as the others could timeout
#
- p = (Ether(src=ep.mac, dst=l['mac']) /
- IP(dst=learnt[0]['ip'], src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=l["mac"])
+ / IP(dst=learnt[0]["ip"], src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_assert_no_replies(self.pg0, [p])
@@ -1960,50 +2198,65 @@ class TestGBP(VppTestCase):
#
for l in learnt:
# a packet with an sclass from a known EPG
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=99, gpid=113, flags=0x88, gpflags='A') /
- Ether(src=l['mac'], dst=ep.mac) /
- IP(src=l['ip'], dst=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=99, gpid=113, flags=0x88, gpflags="A")
+ / Ether(src=l["mac"], dst=ep.mac)
+ / IP(src=l["ip"], dst=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, p * NUM_PKTS, self.pg0)
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l2_1.sw_if_index,
- mac=l['mac']))
+ self.assertTrue(
+ find_gbp_endpoint(self, vx_tun_l2_1.sw_if_index, mac=l["mac"])
+ )
#
# Add the contract so they can talk
#
rule = AclRule(is_permit=1, proto=17)
- rule2 = AclRule(src_prefix=IPv6Network((0, 0)),
- dst_prefix=IPv6Network((0, 0)), is_permit=1, proto=17)
+ rule2 = AclRule(
+ src_prefix=IPv6Network((0, 0)),
+ dst_prefix=IPv6Network((0, 0)),
+ is_permit=1,
+ proto=17,
+ )
acl = VppAcl(self, rules=[rule, rule2])
acl.add_vpp_config()
c1 = VppGbpContract(
- self, 401, epg_220.sclass, epg_330.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
- VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ self,
+ 401,
+ epg_220.sclass,
+ epg_330.sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c1.add_vpp_config()
for l in learnt:
- p = (Ether(src=ep.mac, dst=l['mac']) /
- IP(dst=l['ip'], src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=l["mac"])
+ / IP(dst=l["ip"], src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect(self.pg0, [p], self.pg2)
@@ -2012,18 +2265,22 @@ class TestGBP(VppTestCase):
#
self.logger.info(self.vapi.cli("sh gbp bridge"))
self.logger.info(self.vapi.cli("sh bridge-domain 1 detail"))
- p_uu = (Ether(src=ep.mac, dst="00:11:11:11:11:11") /
- IP(dst="10.0.0.133", src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_uu = (
+ Ether(src=ep.mac, dst="00:11:11:11:11:11")
+ / IP(dst="10.0.0.133", src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(ep.itf, [p_uu], gbd1.uu_fwd)
self.logger.info(self.vapi.cli("sh bridge 1 detail"))
- p_bm = (Ether(src=ep.mac, dst="ff:ff:ff:ff:ff:ff") /
- IP(dst="10.0.0.133", src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_bm = (
+ Ether(src=ep.mac, dst="ff:ff:ff:ff:ff:ff")
+ / IP(dst="10.0.0.133", src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect_only(ep.itf, [p_bm], tun_bm.mcast_itf)
for rx in rxs:
@@ -2039,52 +2296,66 @@ class TestGBP(VppTestCase):
self.assertFalse(rx[VXLAN].gpflags.D)
rule = AclRule(is_permit=1, proto=17)
- rule2 = AclRule(src_prefix=IPv6Network((0, 0)),
- dst_prefix=IPv6Network((0, 0)), is_permit=1, proto=17)
+ rule2 = AclRule(
+ src_prefix=IPv6Network((0, 0)),
+ dst_prefix=IPv6Network((0, 0)),
+ is_permit=1,
+ proto=17,
+ )
acl = VppAcl(self, rules=[rule, rule2])
acl.add_vpp_config()
c2 = VppGbpContract(
- self, 401, epg_330.sclass, epg_220.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 401,
+ epg_330.sclass,
+ epg_220.sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c2.add_vpp_config()
for l in learnt:
- self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index,
- mac=l['mac'])
+ self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index, mac=l["mac"])
#
# Check v6 Endpoints learning
#
for l in learnt:
# a packet with an sclass from a known EPG
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=99, gpid=113, flags=0x88) /
- Ether(src=l['mac'], dst=ep.mac) /
- IPv6(src=l['ip6'], dst=ep.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=99, gpid=113, flags=0x88)
+ / Ether(src=l["mac"], dst=ep.mac)
+ / IPv6(src=l["ip6"], dst=ep.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, p * NUM_PKTS, self.pg0)
rx = self.send_and_expect(self.pg2, p * NUM_PKTS, self.pg0)
- self.assertTrue(find_gbp_endpoint(
- self,
- vx_tun_l2_1.sw_if_index,
- ip=l['ip6'],
- tep=[self.pg2.local_ip4,
- self.pg2.remote_hosts[1].ip4]))
+ self.assertTrue(
+ find_gbp_endpoint(
+ self,
+ vx_tun_l2_1.sw_if_index,
+ ip=l["ip6"],
+ tep=[self.pg2.local_ip4, self.pg2.remote_hosts[1].ip4],
+ )
+ )
self.logger.info(self.vapi.cli("sh int"))
self.logger.info(self.vapi.cli("sh vxlan-gbp tunnel"))
@@ -2097,36 +2368,40 @@ class TestGBP(VppTestCase):
#
for l in learnt:
# a packet with an sclass from a known EPG
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[2].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=99, gpid=113, flags=0x88) /
- Ether(src=l['mac'], dst=ep.mac) /
- IPv6(src=l['ip6'], dst=ep.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[2].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=99, gpid=113, flags=0x88)
+ / Ether(src=l["mac"], dst=ep.mac)
+ / IPv6(src=l["ip6"], dst=ep.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, p * 1, self.pg0)
rx = self.send_and_expect(self.pg2, p * NUM_PKTS, self.pg0)
- self.assertTrue(find_gbp_endpoint(
- self,
- vx_tun_l2_1.sw_if_index,
- sclass=113,
- mac=l['mac'],
- tep=[self.pg2.local_ip4,
- self.pg2.remote_hosts[2].ip4]))
+ self.assertTrue(
+ find_gbp_endpoint(
+ self,
+ vx_tun_l2_1.sw_if_index,
+ sclass=113,
+ mac=l["mac"],
+ tep=[self.pg2.local_ip4, self.pg2.remote_hosts[2].ip4],
+ )
+ )
#
# v6 remote EP reachability
#
for l in learnt:
- p = (Ether(src=ep.mac, dst=l['mac']) /
- IPv6(dst=l['ip6'], src=ep.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=l["mac"])
+ / IPv6(dst=l["ip6"], src=ep.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg2)
@@ -2141,46 +2416,51 @@ class TestGBP(VppTestCase):
self.assertTrue(rx[VXLAN].flags.Instance)
self.assertTrue(rx[VXLAN].gpflags.A)
self.assertFalse(rx[VXLAN].gpflags.D)
- self.assertEqual(rx[IPv6].dst, l['ip6'])
+ self.assertEqual(rx[IPv6].dst, l["ip6"])
#
# EP changes sclass
#
for l in learnt:
# a packet with an sclass from a known EPG
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[2].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=99, gpid=112, flags=0x88) /
- Ether(src=l['mac'], dst=ep.mac) /
- IPv6(src=l['ip6'], dst=ep.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[2].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=99, gpid=112, flags=0x88)
+ / Ether(src=l["mac"], dst=ep.mac)
+ / IPv6(src=l["ip6"], dst=ep.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, p * 1, self.pg0)
rx = self.send_and_expect(self.pg2, p * NUM_PKTS, self.pg0)
- self.assertTrue(find_gbp_endpoint(
- self,
- vx_tun_l2_1.sw_if_index,
- mac=l['mac'],
- sclass=112,
- tep=[self.pg2.local_ip4,
- self.pg2.remote_hosts[2].ip4]))
+ self.assertTrue(
+ find_gbp_endpoint(
+ self,
+ vx_tun_l2_1.sw_if_index,
+ mac=l["mac"],
+ sclass=112,
+ tep=[self.pg2.local_ip4, self.pg2.remote_hosts[2].ip4],
+ )
+ )
#
# check reachability and contract intra-epg
#
allow_intra_class = self.statistics.get_err_counter(
- '/err/gbp-policy-mac/allow-intra-sclass')
+ "/err/gbp-policy-mac/allow-intra-sclass"
+ )
for l in learnt:
- p = (Ether(src=ep.mac, dst=l['mac']) /
- IPv6(dst=l['ip6'], src=ep.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=l["mac"])
+ / IPv6(dst=l["ip6"], src=ep.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg2)
@@ -2194,26 +2474,25 @@ class TestGBP(VppTestCase):
self.assertTrue(rx[VXLAN].flags.Instance)
self.assertTrue(rx[VXLAN].gpflags.A)
self.assertFalse(rx[VXLAN].gpflags.D)
- self.assertEqual(rx[IPv6].dst, l['ip6'])
+ self.assertEqual(rx[IPv6].dst, l["ip6"])
allow_intra_class += NUM_PKTS
self.assert_error_counter_equal(
- '/err/gbp-policy-mac/allow-intra-sclass',
- allow_intra_class)
+ "/err/gbp-policy-mac/allow-intra-sclass", allow_intra_class
+ )
#
# clean up
#
for l in learnt:
- self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index,
- mac=l['mac'])
+ self.wait_for_ep_timeout(vx_tun_l2_1.sw_if_index, mac=l["mac"])
self.pg2.unconfig_ip4()
self.pg3.unconfig_ip4()
self.pg4.unconfig_ip4()
def test_gbp_contract(self):
- """ GBP Contracts """
+ """GBP Contracts"""
#
# Route Domains
@@ -2245,34 +2524,86 @@ class TestGBP(VppTestCase):
#
# 3 EPGs, 2 of which share a BD.
#
- epgs = [VppGbpEndpointGroup(self, 220, 1220, rd0, gbd1,
- None, self.loop0,
- "10.0.0.128", "2001:10::128"),
- VppGbpEndpointGroup(self, 221, 1221, rd0, gbd1,
- None, self.loop0,
- "10.0.1.128", "2001:10:1::128"),
- VppGbpEndpointGroup(self, 222, 1222, rd0, gbd2,
- None, self.loop1,
- "10.0.2.128", "2001:10:2::128")]
+ epgs = [
+ VppGbpEndpointGroup(
+ self,
+ 220,
+ 1220,
+ rd0,
+ gbd1,
+ None,
+ self.loop0,
+ "10.0.0.128",
+ "2001:10::128",
+ ),
+ VppGbpEndpointGroup(
+ self,
+ 221,
+ 1221,
+ rd0,
+ gbd1,
+ None,
+ self.loop0,
+ "10.0.1.128",
+ "2001:10:1::128",
+ ),
+ VppGbpEndpointGroup(
+ self,
+ 222,
+ 1222,
+ rd0,
+ gbd2,
+ None,
+ self.loop1,
+ "10.0.2.128",
+ "2001:10:2::128",
+ ),
+ ]
#
# 4 end-points, 2 in the same subnet, 3 in the same BD
#
- eps = [VppGbpEndpoint(self, self.pg0,
- epgs[0], None,
- "10.0.0.1", "11.0.0.1",
- "2001:10::1", "3001::1"),
- VppGbpEndpoint(self, self.pg1,
- epgs[0], None,
- "10.0.0.2", "11.0.0.2",
- "2001:10::2", "3001::2"),
- VppGbpEndpoint(self, self.pg2,
- epgs[1], None,
- "10.0.1.1", "11.0.0.3",
- "2001:10:1::1", "3001::3"),
- VppGbpEndpoint(self, self.pg3,
- epgs[2], None,
- "10.0.2.1", "11.0.0.4",
- "2001:10:2::1", "3001::4")]
+ eps = [
+ VppGbpEndpoint(
+ self,
+ self.pg0,
+ epgs[0],
+ None,
+ "10.0.0.1",
+ "11.0.0.1",
+ "2001:10::1",
+ "3001::1",
+ ),
+ VppGbpEndpoint(
+ self,
+ self.pg1,
+ epgs[0],
+ None,
+ "10.0.0.2",
+ "11.0.0.2",
+ "2001:10::2",
+ "3001::2",
+ ),
+ VppGbpEndpoint(
+ self,
+ self.pg2,
+ epgs[1],
+ None,
+ "10.0.1.1",
+ "11.0.0.3",
+ "2001:10:1::1",
+ "3001::3",
+ ),
+ VppGbpEndpoint(
+ self,
+ self.pg3,
+ epgs[2],
+ None,
+ "10.0.2.1",
+ "11.0.0.4",
+ "2001:10:2::1",
+ "3001::4",
+ ),
+ ]
#
# Config related to each of the EPGs
@@ -2280,23 +2611,21 @@ class TestGBP(VppTestCase):
for epg in epgs:
# IP config on the BVI interfaces
if epg != epgs[1]:
- b4 = VppIpInterfaceBind(self, epg.bvi,
- epg.rd.t4).add_vpp_config()
- b6 = VppIpInterfaceBind(self, epg.bvi,
- epg.rd.t6).add_vpp_config()
+ b4 = VppIpInterfaceBind(self, epg.bvi, epg.rd.t4).add_vpp_config()
+ b6 = VppIpInterfaceBind(self, epg.bvi, epg.rd.t6).add_vpp_config()
epg.bvi.set_mac(self.router_mac)
- if_ip4 = VppIpInterfaceAddress(self, epg.bvi,
- epg.bvi_ip4, 32,
- bind=b4).add_vpp_config()
- if_ip6 = VppIpInterfaceAddress(self, epg.bvi,
- epg.bvi_ip6, 128,
- bind=b6).add_vpp_config()
+ if_ip4 = VppIpInterfaceAddress(
+ self, epg.bvi, epg.bvi_ip4, 32, bind=b4
+ ).add_vpp_config()
+ if_ip6 = VppIpInterfaceAddress(
+ self, epg.bvi, epg.bvi_ip6, 128, bind=b6
+ ).add_vpp_config()
# add the BD ARP termination entry for BVI IP
- epg.bd_arp_ip4 = VppBridgeDomainArpEntry(self, epg.bd.bd,
- str(self.router_mac),
- epg.bvi_ip4)
+ epg.bd_arp_ip4 = VppBridgeDomainArpEntry(
+ self, epg.bd.bd, str(self.router_mac), epg.bvi_ip4
+ )
epg.bd_arp_ip4.add_vpp_config()
# EPG in VPP
@@ -2315,37 +2644,33 @@ class TestGBP(VppTestCase):
#
# Intra epg allowed without contract
#
- pkt_intra_epg_220_to_220 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg1.remote_mac) /
- IP(src=eps[0].ip4,
- dst=eps[1].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_intra_epg_220_to_220 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg1.remote_mac)
+ / IP(src=eps[0].ip4, dst=eps[1].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- self.send_and_expect_bridged(self.pg0,
- pkt_intra_epg_220_to_220 * 65,
- self.pg1)
+ self.send_and_expect_bridged(self.pg0, pkt_intra_epg_220_to_220 * 65, self.pg1)
- pkt_intra_epg_220_to_220 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg1.remote_mac) /
- IPv6(src=eps[0].ip6,
- dst=eps[1].ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_intra_epg_220_to_220 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg1.remote_mac)
+ / IPv6(src=eps[0].ip6, dst=eps[1].ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- self.send_and_expect_bridged6(self.pg0,
- pkt_intra_epg_220_to_220 * 65,
- self.pg1)
+ self.send_and_expect_bridged6(self.pg0, pkt_intra_epg_220_to_220 * 65, self.pg1)
#
# Inter epg denied without contract
#
- pkt_inter_epg_220_to_221 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg2.remote_mac) /
- IP(src=eps[0].ip4,
- dst=eps[2].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_inter_epg_220_to_221 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg2.remote_mac)
+ / IP(src=eps[0].ip4, dst=eps[2].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_assert_no_replies(self.pg0, pkt_inter_epg_220_to_221)
@@ -2353,58 +2678,71 @@ class TestGBP(VppTestCase):
# A uni-directional contract from EPG 220 -> 221
#
rule = AclRule(is_permit=1, proto=17)
- rule2 = AclRule(src_prefix=IPv6Network((0, 0)),
- dst_prefix=IPv6Network((0, 0)), is_permit=1, proto=17)
+ rule2 = AclRule(
+ src_prefix=IPv6Network((0, 0)),
+ dst_prefix=IPv6Network((0, 0)),
+ is_permit=1,
+ proto=17,
+ )
rule3 = AclRule(is_permit=1, proto=1)
acl = VppAcl(self, rules=[rule, rule2, rule3])
acl.add_vpp_config()
c1 = VppGbpContract(
- self, 400, epgs[0].sclass, epgs[1].sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
- VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
- VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ self,
+ 400,
+ epgs[0].sclass,
+ epgs[1].sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c1.add_vpp_config()
- self.send_and_expect_bridged(eps[0].itf,
- pkt_inter_epg_220_to_221 * 65,
- eps[2].itf)
+ self.send_and_expect_bridged(
+ eps[0].itf, pkt_inter_epg_220_to_221 * 65, eps[2].itf
+ )
- pkt_inter_epg_220_to_222 = (Ether(src=self.pg0.remote_mac,
- dst=str(self.router_mac)) /
- IP(src=eps[0].ip4,
- dst=eps[3].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- self.send_and_assert_no_replies(eps[0].itf,
- pkt_inter_epg_220_to_222 * 65)
+ pkt_inter_epg_220_to_222 = (
+ Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src=eps[0].ip4, dst=eps[3].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ self.send_and_assert_no_replies(eps[0].itf, pkt_inter_epg_220_to_222 * 65)
#
# ping router IP in different BD
#
- pkt_router_ping_220_to_221 = (Ether(src=self.pg0.remote_mac,
- dst=str(self.router_mac)) /
- IP(src=eps[0].ip4,
- dst=epgs[1].bvi_ip4) /
- ICMP(type='echo-request'))
+ pkt_router_ping_220_to_221 = (
+ Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src=eps[0].ip4, dst=epgs[1].bvi_ip4)
+ / ICMP(type="echo-request")
+ )
self.send_and_expect(self.pg0, [pkt_router_ping_220_to_221], self.pg0)
- pkt_router_ping_220_to_221 = (Ether(src=self.pg0.remote_mac,
- dst=str(self.router_mac)) /
- IPv6(src=eps[0].ip6,
- dst=epgs[1].bvi_ip6) /
- ICMPv6EchoRequest())
+ pkt_router_ping_220_to_221 = (
+ Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IPv6(src=eps[0].ip6, dst=epgs[1].bvi_ip6)
+ / ICMPv6EchoRequest()
+ )
self.send_and_expect(self.pg0, [pkt_router_ping_220_to_221], self.pg0)
@@ -2412,70 +2750,84 @@ class TestGBP(VppTestCase):
# contract for the return direction
#
c2 = VppGbpContract(
- self, 400, epgs[1].sclass, epgs[0].sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
- VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ self,
+ 400,
+ epgs[1].sclass,
+ epgs[0].sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c2.add_vpp_config()
- self.send_and_expect_bridged(eps[0].itf,
- pkt_inter_epg_220_to_221 * 65,
- eps[2].itf)
- pkt_inter_epg_221_to_220 = (Ether(src=self.pg2.remote_mac,
- dst=self.pg0.remote_mac) /
- IP(src=eps[2].ip4,
- dst=eps[0].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- self.send_and_expect_bridged(eps[2].itf,
- pkt_inter_epg_221_to_220 * 65,
- eps[0].itf)
- pkt_inter_epg_221_to_220 = (Ether(src=self.pg2.remote_mac,
- dst=str(self.router_mac)) /
- IP(src=eps[2].ip4,
- dst=eps[0].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- self.send_and_expect_routed(eps[2].itf,
- pkt_inter_epg_221_to_220 * 65,
- eps[0].itf,
- str(self.router_mac))
- pkt_inter_epg_221_to_220 = (Ether(src=self.pg2.remote_mac,
- dst=str(self.router_mac)) /
- IPv6(src=eps[2].ip6,
- dst=eps[0].ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- self.send_and_expect_routed6(eps[2].itf,
- pkt_inter_epg_221_to_220 * 65,
- eps[0].itf,
- str(self.router_mac))
+ self.send_and_expect_bridged(
+ eps[0].itf, pkt_inter_epg_220_to_221 * 65, eps[2].itf
+ )
+ pkt_inter_epg_221_to_220 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg0.remote_mac)
+ / IP(src=eps[2].ip4, dst=eps[0].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ self.send_and_expect_bridged(
+ eps[2].itf, pkt_inter_epg_221_to_220 * 65, eps[0].itf
+ )
+ pkt_inter_epg_221_to_220 = (
+ Ether(src=self.pg2.remote_mac, dst=str(self.router_mac))
+ / IP(src=eps[2].ip4, dst=eps[0].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ self.send_and_expect_routed(
+ eps[2].itf, pkt_inter_epg_221_to_220 * 65, eps[0].itf, str(self.router_mac)
+ )
+ pkt_inter_epg_221_to_220 = (
+ Ether(src=self.pg2.remote_mac, dst=str(self.router_mac))
+ / IPv6(src=eps[2].ip6, dst=eps[0].ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ self.send_and_expect_routed6(
+ eps[2].itf, pkt_inter_epg_221_to_220 * 65, eps[0].itf, str(self.router_mac)
+ )
#
# contract between 220 and 222 uni-direction
#
c3 = VppGbpContract(
- self, 400, epgs[0].sclass, epgs[2].sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
- VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ self,
+ 400,
+ epgs[0].sclass,
+ epgs[2].sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c3.add_vpp_config()
- self.send_and_expect(eps[0].itf,
- pkt_inter_epg_220_to_222 * 65,
- eps[3].itf)
+ self.send_and_expect(eps[0].itf, pkt_inter_epg_220_to_222 * 65, eps[3].itf)
c3.remove_vpp_config()
c1.remove_vpp_config()
@@ -2483,7 +2835,7 @@ class TestGBP(VppTestCase):
acl.remove_vpp_config()
def test_gbp_bd_drop_flags(self):
- """ GBP BD drop flags """
+ """GBP BD drop flags"""
#
# IP tables
@@ -2502,32 +2854,46 @@ class TestGBP(VppTestCase):
bd1 = VppBridgeDomain(self, 1)
bd1.add_vpp_config()
- gbd1 = VppGbpBridgeDomain(self, bd1, rd1, self.loop0,
- None, None,
- uu_drop=True, bm_drop=True)
+ gbd1 = VppGbpBridgeDomain(
+ self, bd1, rd1, self.loop0, None, None, uu_drop=True, bm_drop=True
+ )
gbd1.add_vpp_config()
self.logger.info(self.vapi.cli("sh bridge 1 detail"))
self.logger.info(self.vapi.cli("sh gbp bridge"))
# ... and has a /32 applied
- ip_addr = VppIpInterfaceAddress(self, gbd1.bvi,
- "10.0.0.128", 32).add_vpp_config()
+ ip_addr = VppIpInterfaceAddress(
+ self, gbd1.bvi, "10.0.0.128", 32
+ ).add_vpp_config()
#
# The Endpoint-group
#
- epg_220 = VppGbpEndpointGroup(self, 220, 112, rd1, gbd1,
- None, self.loop0,
- "10.0.0.128",
- "2001:10::128",
- VppGbpEndpointRetention(3))
+ epg_220 = VppGbpEndpointGroup(
+ self,
+ 220,
+ 112,
+ rd1,
+ gbd1,
+ None,
+ self.loop0,
+ "10.0.0.128",
+ "2001:10::128",
+ VppGbpEndpointRetention(3),
+ )
epg_220.add_vpp_config()
- ep = VppGbpEndpoint(self, self.pg0,
- epg_220, None,
- "10.0.0.127", "11.0.0.127",
- "2001:10::1", "3001::1")
+ ep = VppGbpEndpoint(
+ self,
+ self.pg0,
+ epg_220,
+ None,
+ "10.0.0.127",
+ "11.0.0.127",
+ "2001:10::1",
+ "3001::1",
+ )
ep.add_vpp_config()
#
@@ -2536,16 +2902,20 @@ class TestGBP(VppTestCase):
#
self.logger.info(self.vapi.cli("sh bridge 1 detail"))
self.logger.info(self.vapi.cli("sh gbp bridge"))
- p_uu = (Ether(src=ep.mac, dst="00:11:11:11:11:11") /
- IP(dst="10.0.0.133", src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_uu = (
+ Ether(src=ep.mac, dst="00:11:11:11:11:11")
+ / IP(dst="10.0.0.133", src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_assert_no_replies(ep.itf, [p_uu])
- p_bm = (Ether(src=ep.mac, dst="ff:ff:ff:ff:ff:ff") /
- IP(dst="10.0.0.133", src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_bm = (
+ Ether(src=ep.mac, dst="ff:ff:ff:ff:ff:ff")
+ / IP(dst="10.0.0.133", src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_assert_no_replies(ep.itf, [p_bm])
self.pg3.unconfig_ip4()
@@ -2553,7 +2923,7 @@ class TestGBP(VppTestCase):
self.logger.info(self.vapi.cli("sh int"))
def test_gbp_bd_arp_flags(self):
- """ GBP BD arp flags """
+ """GBP BD arp flags"""
#
# IP tables
@@ -2575,9 +2945,9 @@ class TestGBP(VppTestCase):
#
# Add a mcast destination VXLAN-GBP tunnel for B&M traffic
#
- tun_uu = VppVxlanGbpTunnel(self, self.pg4.local_ip4,
- "239.1.1.1", 88,
- mcast_itf=self.pg4)
+ tun_uu = VppVxlanGbpTunnel(
+ self, self.pg4.local_ip4, "239.1.1.1", 88, mcast_itf=self.pg4
+ )
tun_uu.add_vpp_config()
#
@@ -2586,29 +2956,43 @@ class TestGBP(VppTestCase):
bd1 = VppBridgeDomain(self, 1)
bd1.add_vpp_config()
- gbd1 = VppGbpBridgeDomain(self, bd1, rd1, self.loop0,
- tun_uu, None,
- ucast_arp=True)
+ gbd1 = VppGbpBridgeDomain(
+ self, bd1, rd1, self.loop0, tun_uu, None, ucast_arp=True
+ )
gbd1.add_vpp_config()
# ... and has a /32 applied
- ip_addr = VppIpInterfaceAddress(self, gbd1.bvi,
- "10.0.0.128", 32).add_vpp_config()
+ ip_addr = VppIpInterfaceAddress(
+ self, gbd1.bvi, "10.0.0.128", 32
+ ).add_vpp_config()
#
# The Endpoint-group
#
- epg_220 = VppGbpEndpointGroup(self, 220, 112, rd1, gbd1,
- None, self.loop0,
- "10.0.0.128",
- "2001:10::128",
- VppGbpEndpointRetention(2))
+ epg_220 = VppGbpEndpointGroup(
+ self,
+ 220,
+ 112,
+ rd1,
+ gbd1,
+ None,
+ self.loop0,
+ "10.0.0.128",
+ "2001:10::128",
+ VppGbpEndpointRetention(2),
+ )
epg_220.add_vpp_config()
- ep = VppGbpEndpoint(self, self.pg0,
- epg_220, None,
- "10.0.0.127", "11.0.0.127",
- "2001:10::1", "3001::1")
+ ep = VppGbpEndpoint(
+ self,
+ self.pg0,
+ epg_220,
+ None,
+ "10.0.0.127",
+ "11.0.0.127",
+ "2001:10::1",
+ "3001::1",
+ )
ep.add_vpp_config()
#
@@ -2616,25 +3000,25 @@ class TestGBP(VppTestCase):
#
self.logger.info(self.vapi.cli("sh bridge 1 detail"))
self.logger.info(self.vapi.cli("sh gbp bridge"))
- p_arp = (Ether(src=ep.mac, dst="ff:ff:ff:ff:ff:ff") /
- ARP(op="who-has",
- psrc=ep.ip4, pdst="10.0.0.99",
- hwsrc=ep.mac,
- hwdst="ff:ff:ff:ff:ff:ff"))
+ p_arp = Ether(src=ep.mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op="who-has",
+ psrc=ep.ip4,
+ pdst="10.0.0.99",
+ hwsrc=ep.mac,
+ hwdst="ff:ff:ff:ff:ff:ff",
+ )
self.send_and_expect(ep.itf, [p_arp], self.pg4)
self.pg4.unconfig_ip4()
def test_gbp_learn_vlan_l2(self):
- """ GBP L2 Endpoint w/ VLANs"""
+ """GBP L2 Endpoint w/ VLANs"""
ep_flags = VppEnum.vl_api_gbp_endpoint_flags_t
- learnt = [{'mac': '00:00:11:11:11:01',
- 'ip': '10.0.0.1',
- 'ip6': '2001:10::2'},
- {'mac': '00:00:11:11:11:02',
- 'ip': '10.0.0.2',
- 'ip6': '2001:10::3'}]
+ learnt = [
+ {"mac": "00:00:11:11:11:01", "ip": "10.0.0.1", "ip6": "2001:10::2"},
+ {"mac": "00:00:11:11:11:02", "ip": "10.0.0.2", "ip6": "2001:10::3"},
+ ]
#
# IP tables
@@ -2663,11 +3047,12 @@ class TestGBP(VppTestCase):
vlan_11 = VppDot1QSubint(self, self.pg0, 11)
vlan_11.admin_up()
self.vapi.l2_interface_vlan_tag_rewrite(
- sw_if_index=vlan_11.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1,
- push_dot1q=11)
+ sw_if_index=vlan_11.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1, push_dot1q=11
+ )
- bd_uu_fwd = VppVxlanGbpTunnel(self, self.pg3.local_ip4,
- self.pg3.remote_ip4, 116)
+ bd_uu_fwd = VppVxlanGbpTunnel(
+ self, self.pg3.local_ip4, self.pg3.remote_ip4, 116
+ )
bd_uu_fwd.add_vpp_config()
#
@@ -2677,25 +3062,32 @@ class TestGBP(VppTestCase):
#
bd1 = VppBridgeDomain(self, 1)
bd1.add_vpp_config()
- gbd1 = VppGbpBridgeDomain(self, bd1, rd1, self.loop0, bd_uu_fwd,
- learn=False)
+ gbd1 = VppGbpBridgeDomain(self, bd1, rd1, self.loop0, bd_uu_fwd, learn=False)
gbd1.add_vpp_config()
self.logger.info(self.vapi.cli("sh bridge 1 detail"))
self.logger.info(self.vapi.cli("sh gbp bridge"))
# ... and has a /32 applied
- ip_addr = VppIpInterfaceAddress(self, gbd1.bvi,
- "10.0.0.128", 32).add_vpp_config()
+ ip_addr = VppIpInterfaceAddress(
+ self, gbd1.bvi, "10.0.0.128", 32
+ ).add_vpp_config()
#
# The Endpoint-group in which we are learning endpoints
#
- epg_220 = VppGbpEndpointGroup(self, 220, 441, rd1, gbd1,
- None, self.loop0,
- "10.0.0.128",
- "2001:10::128",
- VppGbpEndpointRetention(4))
+ epg_220 = VppGbpEndpointGroup(
+ self,
+ 220,
+ 441,
+ rd1,
+ gbd1,
+ None,
+ self.loop0,
+ "10.0.0.128",
+ "2001:10::128",
+ VppGbpEndpointRetention(4),
+ )
epg_220.add_vpp_config()
#
@@ -2703,19 +3095,28 @@ class TestGBP(VppTestCase):
# learning enabled
#
vx_tun_l2_1 = VppGbpVxlanTunnel(
- self, 99, bd1.bd_id,
+ self,
+ 99,
+ bd1.bd_id,
VppEnum.vl_api_gbp_vxlan_tunnel_mode_t.GBP_VXLAN_TUNNEL_MODE_L2,
- self.pg2.local_ip4)
+ self.pg2.local_ip4,
+ )
vx_tun_l2_1.add_vpp_config()
#
# A static endpoint that the learnt endpoints are trying to
# talk to
#
- ep = VppGbpEndpoint(self, vlan_11,
- epg_220, None,
- "10.0.0.127", "11.0.0.127",
- "2001:10::1", "3001::1")
+ ep = VppGbpEndpoint(
+ self,
+ vlan_11,
+ epg_220,
+ None,
+ "10.0.0.127",
+ "11.0.0.127",
+ "2001:10::1",
+ "3001::1",
+ )
ep.add_vpp_config()
self.assertTrue(find_route(self, ep.ip4, 32, table_id=1))
@@ -2726,16 +3127,16 @@ class TestGBP(VppTestCase):
for ii, l in enumerate(learnt):
# a packet with an sclass from a known EPG
# arriving on an unknown TEP
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=99, gpid=441, flags=0x88) /
- Ether(src=l['mac'], dst=ep.mac) /
- IP(src=l['ip'], dst=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=99, gpid=441, flags=0x88)
+ / Ether(src=l["mac"], dst=ep.mac)
+ / IP(src=l["ip"], dst=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg2, [p], self.pg0)
@@ -2749,15 +3150,15 @@ class TestGBP(VppTestCase):
# the EP is not learnt since the BD setting prevents it
# also no TEP too
#
- self.assertFalse(find_gbp_endpoint(self,
- vx_tun_l2_1.sw_if_index,
- mac=l['mac']))
- self.assertEqual(INDEX_INVALID,
- find_vxlan_gbp_tunnel(
- self,
- self.pg2.local_ip4,
- self.pg2.remote_hosts[1].ip4,
- 99))
+ self.assertFalse(
+ find_gbp_endpoint(self, vx_tun_l2_1.sw_if_index, mac=l["mac"])
+ )
+ self.assertEqual(
+ INDEX_INVALID,
+ find_vxlan_gbp_tunnel(
+ self, self.pg2.local_ip4, self.pg2.remote_hosts[1].ip4, 99
+ ),
+ )
self.assertEqual(len(self.vapi.gbp_endpoint_dump()), 1)
@@ -2766,11 +3167,13 @@ class TestGBP(VppTestCase):
# we didn't learn the remotes so they are sent to the UU-fwd
#
for l in learnt:
- p = (Ether(src=ep.mac, dst=l['mac']) /
- Dot1Q(vlan=11) /
- IP(dst=l['ip'], src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=l["mac"])
+ / Dot1Q(vlan=11)
+ / IP(dst=l["ip"], src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * 17, self.pg3)
@@ -2790,7 +3193,7 @@ class TestGBP(VppTestCase):
self.pg3.unconfig_ip4()
def test_gbp_learn_l3(self):
- """ GBP L3 Endpoint Learning """
+ """GBP L3 Endpoint Learning"""
self.vapi.cli("set logging class gbp level debug")
@@ -2798,12 +3201,10 @@ class TestGBP(VppTestCase):
routed_dst_mac = "00:0c:0c:0c:0c:0c"
routed_src_mac = "00:22:bd:f8:19:ff"
- learnt = [{'mac': '00:00:11:11:11:02',
- 'ip': '10.0.1.2',
- 'ip6': '2001:10::2'},
- {'mac': '00:00:11:11:11:03',
- 'ip': '10.0.1.3',
- 'ip6': '2001:10::3'}]
+ learnt = [
+ {"mac": "00:00:11:11:11:02", "ip": "10.0.1.2", "ip6": "2001:10::2"},
+ {"mac": "00:00:11:11:11:03", "ip": "10.0.1.3", "ip6": "2001:10::3"},
+ ]
#
# IP tables
@@ -2813,10 +3214,12 @@ class TestGBP(VppTestCase):
t6 = VppIpTable(self, 1, True)
t6.add_vpp_config()
- tun_ip4_uu = VppVxlanGbpTunnel(self, self.pg4.local_ip4,
- self.pg4.remote_ip4, 114)
- tun_ip6_uu = VppVxlanGbpTunnel(self, self.pg4.local_ip4,
- self.pg4.remote_ip4, 116)
+ tun_ip4_uu = VppVxlanGbpTunnel(
+ self, self.pg4.local_ip4, self.pg4.remote_ip4, 114
+ )
+ tun_ip6_uu = VppVxlanGbpTunnel(
+ self, self.pg4.local_ip4, self.pg4.remote_ip4, 116
+ )
tun_ip4_uu.add_vpp_config()
tun_ip6_uu.add_vpp_config()
@@ -2859,40 +3262,56 @@ class TestGBP(VppTestCase):
self.logger.info(self.vapi.cli("sh gbp route"))
# ... and has a /32 and /128 applied
- ip4_addr = VppIpInterfaceAddress(self, gbd1.bvi,
- "10.0.0.128", 32,
- bind=b4).add_vpp_config()
- ip6_addr = VppIpInterfaceAddress(self, gbd1.bvi,
- "2001:10::128", 128,
- bind=b6).add_vpp_config()
+ ip4_addr = VppIpInterfaceAddress(
+ self, gbd1.bvi, "10.0.0.128", 32, bind=b4
+ ).add_vpp_config()
+ ip6_addr = VppIpInterfaceAddress(
+ self, gbd1.bvi, "2001:10::128", 128, bind=b6
+ ).add_vpp_config()
#
# The Endpoint-group in which we are learning endpoints
#
- epg_220 = VppGbpEndpointGroup(self, 220, 441, rd1, gbd1,
- None, self.loop0,
- "10.0.0.128",
- "2001:10::128",
- VppGbpEndpointRetention(4))
+ epg_220 = VppGbpEndpointGroup(
+ self,
+ 220,
+ 441,
+ rd1,
+ gbd1,
+ None,
+ self.loop0,
+ "10.0.0.128",
+ "2001:10::128",
+ VppGbpEndpointRetention(4),
+ )
epg_220.add_vpp_config()
#
# The VXLAN GBP tunnel is in L3 mode with learning enabled
#
vx_tun_l3 = VppGbpVxlanTunnel(
- self, 101, rd1.rd_id,
+ self,
+ 101,
+ rd1.rd_id,
VppEnum.vl_api_gbp_vxlan_tunnel_mode_t.GBP_VXLAN_TUNNEL_MODE_L3,
- self.pg2.local_ip4)
+ self.pg2.local_ip4,
+ )
vx_tun_l3.add_vpp_config()
#
# A static endpoint that the learnt endpoints are trying to
# talk to
#
- ep = VppGbpEndpoint(self, self.pg0,
- epg_220, None,
- "10.0.0.127", "11.0.0.127",
- "2001:10::1", "3001::1")
+ ep = VppGbpEndpoint(
+ self,
+ self.pg0,
+ epg_220,
+ None,
+ "10.0.0.127",
+ "11.0.0.127",
+ "2001:10::1",
+ "3001::1",
+ )
ep.add_vpp_config()
#
@@ -2901,40 +3320,38 @@ class TestGBP(VppTestCase):
for ii, l in enumerate(learnt):
# a packet with an sclass from a known EPG
# arriving on an unknown TEP
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=101, gpid=441, flags=0x88) /
- Ether(src=l['mac'], dst="00:00:00:11:11:11") /
- IP(src=l['ip'], dst=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=101, gpid=441, flags=0x88)
+ / Ether(src=l["mac"], dst="00:00:00:11:11:11")
+ / IP(src=l["ip"], dst=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, [p], self.pg0)
# the new TEP
tep1_sw_if_index = find_vxlan_gbp_tunnel(
- self,
- self.pg2.local_ip4,
- self.pg2.remote_hosts[1].ip4,
- vx_tun_l3.vni)
+ self, self.pg2.local_ip4, self.pg2.remote_hosts[1].ip4, vx_tun_l3.vni
+ )
self.assertNotEqual(INDEX_INVALID, tep1_sw_if_index)
# endpoint learnt via the parent GBP-vxlan interface
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l3._sw_if_index,
- ip=l['ip']))
+ self.assertTrue(find_gbp_endpoint(self, vx_tun_l3._sw_if_index, ip=l["ip"]))
#
# Static IPv4 EP replies to learnt
#
for l in learnt:
- p = (Ether(src=ep.mac, dst=self.loop0.local_mac) /
- IP(dst=l['ip'], src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=self.loop0.local_mac)
+ / IP(dst=l["ip"], src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg2)
@@ -2955,12 +3372,10 @@ class TestGBP(VppTestCase):
self.assertEqual(inner[Ether].src, routed_src_mac)
self.assertEqual(inner[Ether].dst, routed_dst_mac)
self.assertEqual(inner[IP].src, ep.ip4)
- self.assertEqual(inner[IP].dst, l['ip'])
+ self.assertEqual(inner[IP].dst, l["ip"])
for l in learnt:
- self.assertFalse(find_gbp_endpoint(self,
- tep1_sw_if_index,
- ip=l['ip']))
+ self.assertFalse(find_gbp_endpoint(self, tep1_sw_if_index, ip=l["ip"]))
#
# learn some remote IPv6 EPs
@@ -2968,25 +3383,23 @@ class TestGBP(VppTestCase):
for ii, l in enumerate(learnt):
# a packet with an sclass from a known EPG
# arriving on an unknown TEP
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=101, gpid=441, flags=0x88) /
- Ether(src=l['mac'], dst="00:00:00:11:11:11") /
- IPv6(src=l['ip6'], dst=ep.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=101, gpid=441, flags=0x88)
+ / Ether(src=l["mac"], dst="00:00:00:11:11:11")
+ / IPv6(src=l["ip6"], dst=ep.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, [p], self.pg0)
# the new TEP
tep1_sw_if_index = find_vxlan_gbp_tunnel(
- self,
- self.pg2.local_ip4,
- self.pg2.remote_hosts[1].ip4,
- vx_tun_l3.vni)
+ self, self.pg2.local_ip4, self.pg2.remote_hosts[1].ip4, vx_tun_l3.vni
+ )
self.assertNotEqual(INDEX_INVALID, tep1_sw_if_index)
self.logger.info(self.vapi.cli("show gbp bridge"))
@@ -2995,19 +3408,21 @@ class TestGBP(VppTestCase):
self.logger.info(self.vapi.cli("show int addr"))
# endpoint learnt via the TEP
- self.assertTrue(find_gbp_endpoint(self, ip=l['ip6']))
+ self.assertTrue(find_gbp_endpoint(self, ip=l["ip6"]))
self.logger.info(self.vapi.cli("show gbp endpoint"))
- self.logger.info(self.vapi.cli("show ip fib index 1 %s" % l['ip']))
+ self.logger.info(self.vapi.cli("show ip fib index 1 %s" % l["ip"]))
#
# Static EP replies to learnt
#
for l in learnt:
- p = (Ether(src=ep.mac, dst=self.loop0.local_mac) /
- IPv6(dst=l['ip6'], src=ep.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=self.loop0.local_mac)
+ / IPv6(dst=l["ip6"], src=ep.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg2)
@@ -3028,19 +3443,21 @@ class TestGBP(VppTestCase):
self.assertEqual(inner[Ether].src, routed_src_mac)
self.assertEqual(inner[Ether].dst, routed_dst_mac)
self.assertEqual(inner[IPv6].src, ep.ip6)
- self.assertEqual(inner[IPv6].dst, l['ip6'])
+ self.assertEqual(inner[IPv6].dst, l["ip6"])
self.logger.info(self.vapi.cli("sh gbp endpoint"))
for l in learnt:
- self.wait_for_ep_timeout(ip=l['ip'])
+ self.wait_for_ep_timeout(ip=l["ip"])
#
# Static sends to unknown EP with no route
#
- p = (Ether(src=ep.mac, dst=self.loop0.local_mac) /
- IP(dst="10.0.0.99", src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=self.loop0.local_mac)
+ / IP(dst="10.0.0.99", src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_assert_no_replies(self.pg0, [p])
@@ -3048,34 +3465,44 @@ class TestGBP(VppTestCase):
# Add a route to static EP's v4 and v6 subnet
#
se_10_24 = VppGbpSubnet(
- self, rd1, "10.0.0.0", 24,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_TRANSPORT)
+ self,
+ rd1,
+ "10.0.0.0",
+ 24,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_TRANSPORT,
+ )
se_10_24.add_vpp_config()
#
# static pings router
#
- p = (Ether(src=ep.mac, dst=self.loop0.local_mac) /
- IP(dst=epg_220.bvi_ip4, src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=self.loop0.local_mac)
+ / IP(dst=epg_220.bvi_ip4, src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg0)
- p = (Ether(src=ep.mac, dst=self.loop0.local_mac) /
- IPv6(dst=epg_220.bvi_ip6, src=ep.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=self.loop0.local_mac)
+ / IPv6(dst=epg_220.bvi_ip6, src=ep.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg0)
#
# packets to address in the subnet are sent on the uu-fwd
#
- p = (Ether(src=ep.mac, dst=self.loop0.local_mac) /
- IP(dst="10.0.0.99", src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=self.loop0.local_mac)
+ / IP(dst="10.0.0.99", src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, [p], self.pg4)
for rx in rxs:
@@ -3097,43 +3524,45 @@ class TestGBP(VppTestCase):
for ii, l in enumerate(learnt):
# a packet with an sclass from a known EPG
# arriving on an unknown TEP
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[2].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=101, gpid=441, flags=0x88) /
- Ether(src=l['mac'], dst="00:00:00:11:11:11") /
- IP(src=l['ip'], dst=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[2].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=101, gpid=441, flags=0x88)
+ / Ether(src=l["mac"], dst="00:00:00:11:11:11")
+ / IP(src=l["ip"], dst=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, [p], self.pg0)
# the new TEP
tep1_sw_if_index = find_vxlan_gbp_tunnel(
- self,
- self.pg2.local_ip4,
- self.pg2.remote_hosts[2].ip4,
- vx_tun_l3.vni)
+ self, self.pg2.local_ip4, self.pg2.remote_hosts[2].ip4, vx_tun_l3.vni
+ )
self.assertNotEqual(INDEX_INVALID, tep1_sw_if_index)
# endpoint learnt via the parent GBP-vxlan interface
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l3._sw_if_index,
- ip=l['ip']))
+ self.assertTrue(find_gbp_endpoint(self, vx_tun_l3._sw_if_index, ip=l["ip"]))
#
# Add a remote endpoint from the API
#
- rep_88 = VppGbpEndpoint(self, vx_tun_l3,
- epg_220, None,
- "10.0.0.88", "11.0.0.88",
- "2001:10::88", "3001::88",
- ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
- self.pg2.local_ip4,
- self.pg2.remote_hosts[2].ip4,
- mac=None)
+ rep_88 = VppGbpEndpoint(
+ self,
+ vx_tun_l3,
+ epg_220,
+ None,
+ "10.0.0.88",
+ "11.0.0.88",
+ "2001:10::88",
+ "3001::88",
+ ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
+ self.pg2.local_ip4,
+ self.pg2.remote_hosts[2].ip4,
+ mac=None,
+ )
rep_88.add_vpp_config()
#
@@ -3141,14 +3570,20 @@ class TestGBP(VppTestCase):
# this is a lower priority, hence the packet is sent to the DP leanrt
# TEP
#
- rep_2 = VppGbpEndpoint(self, vx_tun_l3,
- epg_220, None,
- learnt[0]['ip'], "11.0.0.101",
- learnt[0]['ip6'], "3001::101",
- ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
- self.pg2.local_ip4,
- self.pg2.remote_hosts[1].ip4,
- mac=None)
+ rep_2 = VppGbpEndpoint(
+ self,
+ vx_tun_l3,
+ epg_220,
+ None,
+ learnt[0]["ip"],
+ "11.0.0.101",
+ learnt[0]["ip6"],
+ "3001::101",
+ ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
+ self.pg2.local_ip4,
+ self.pg2.remote_hosts[1].ip4,
+ mac=None,
+ )
rep_2.add_vpp_config()
#
@@ -3156,18 +3591,24 @@ class TestGBP(VppTestCase):
# packets should be send on the v4/v6 uu=fwd interface resp.
#
se_10_1_24 = VppGbpSubnet(
- self, rd1, "10.0.1.0", 24,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_TRANSPORT)
+ self,
+ rd1,
+ "10.0.1.0",
+ 24,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_TRANSPORT,
+ )
se_10_1_24.add_vpp_config()
self.logger.info(self.vapi.cli("show gbp endpoint"))
- ips = ["10.0.0.88", learnt[0]['ip']]
+ ips = ["10.0.0.88", learnt[0]["ip"]]
for ip in ips:
- p = (Ether(src=ep.mac, dst=self.loop0.local_mac) /
- IP(dst=ip, src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=self.loop0.local_mac)
+ / IP(dst=ip, src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg2)
@@ -3199,18 +3640,22 @@ class TestGBP(VppTestCase):
self.assertTrue(find_gbp_endpoint(self, ip=rep_2.ip4))
- p = (Ether(src=ep.mac, dst=self.loop0.local_mac) /
- IP(src=ep.ip4, dst=rep_2.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=self.loop0.local_mac)
+ / IP(src=ep.ip4, dst=rep_2.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, [p], self.pg2)
self.assertFalse(find_gbp_endpoint(self, ip=rep_88.ip4))
- p = (Ether(src=ep.mac, dst=self.loop0.local_mac) /
- IP(src=ep.ip4, dst=rep_88.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=self.loop0.local_mac)
+ / IP(src=ep.ip4, dst=rep_88.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, [p], self.pg4)
#
@@ -3225,38 +3670,49 @@ class TestGBP(VppTestCase):
# Same as above, learn a remote EP via CP and DP
# this time remove the DP one first. expect the CP data to remain
#
- rep_3 = VppGbpEndpoint(self, vx_tun_l3,
- epg_220, None,
- "10.0.1.4", "11.0.0.103",
- "2001::10:3", "3001::103",
- ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
- self.pg2.local_ip4,
- self.pg2.remote_hosts[1].ip4,
- mac=None)
+ rep_3 = VppGbpEndpoint(
+ self,
+ vx_tun_l3,
+ epg_220,
+ None,
+ "10.0.1.4",
+ "11.0.0.103",
+ "2001::10:3",
+ "3001::103",
+ ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
+ self.pg2.local_ip4,
+ self.pg2.remote_hosts[1].ip4,
+ mac=None,
+ )
rep_3.add_vpp_config()
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[2].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=101, gpid=441, flags=0x88) /
- Ether(src=l['mac'], dst="00:00:00:11:11:11") /
- IP(src="10.0.1.4", dst=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[2].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=101, gpid=441, flags=0x88)
+ / Ether(src=l["mac"], dst="00:00:00:11:11:11")
+ / IP(src="10.0.1.4", dst=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg2, p * NUM_PKTS, self.pg0)
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l3._sw_if_index,
- ip=rep_3.ip4,
- tep=[self.pg2.local_ip4,
- self.pg2.remote_hosts[2].ip4]))
+ self.assertTrue(
+ find_gbp_endpoint(
+ self,
+ vx_tun_l3._sw_if_index,
+ ip=rep_3.ip4,
+ tep=[self.pg2.local_ip4, self.pg2.remote_hosts[2].ip4],
+ )
+ )
- p = (Ether(src=ep.mac, dst=self.loop0.local_mac) /
- IP(dst="10.0.1.4", src=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=ep.mac, dst=self.loop0.local_mac)
+ / IP(dst="10.0.1.4", src=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg2)
# host 2 is the DP learned TEP
@@ -3264,9 +3720,9 @@ class TestGBP(VppTestCase):
self.assertEqual(rx[IP].src, self.pg2.local_ip4)
self.assertEqual(rx[IP].dst, self.pg2.remote_hosts[2].ip4)
- self.wait_for_ep_timeout(ip=rep_3.ip4,
- tep=[self.pg2.local_ip4,
- self.pg2.remote_hosts[2].ip4])
+ self.wait_for_ep_timeout(
+ ip=rep_3.ip4, tep=[self.pg2.local_ip4, self.pg2.remote_hosts[2].ip4]
+ )
rxs = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg2)
@@ -3278,23 +3734,21 @@ class TestGBP(VppTestCase):
#
# shutdown with learnt endpoint present
#
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_hosts[1].ip4,
- dst=self.pg2.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=101, gpid=441, flags=0x88) /
- Ether(src=l['mac'], dst="00:00:00:11:11:11") /
- IP(src=learnt[1]['ip'], dst=ep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_hosts[1].ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=101, gpid=441, flags=0x88)
+ / Ether(src=l["mac"], dst="00:00:00:11:11:11")
+ / IP(src=learnt[1]["ip"], dst=ep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg2, [p], self.pg0)
# endpoint learnt via the parent GBP-vxlan interface
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l3._sw_if_index,
- ip=l['ip']))
+ self.assertTrue(find_gbp_endpoint(self, vx_tun_l3._sw_if_index, ip=l["ip"]))
#
# TODO
@@ -3305,7 +3759,7 @@ class TestGBP(VppTestCase):
self.pg4.unconfig_ip4()
def test_gbp_redirect(self):
- """ GBP Endpoint Redirect """
+ """GBP Endpoint Redirect"""
self.vapi.cli("set logging class gbp level debug")
@@ -3313,12 +3767,10 @@ class TestGBP(VppTestCase):
routed_dst_mac = "00:0c:0c:0c:0c:0c"
routed_src_mac = "00:22:bd:f8:19:ff"
- learnt = [{'mac': '00:00:11:11:11:02',
- 'ip': '10.0.1.2',
- 'ip6': '2001:10::2'},
- {'mac': '00:00:11:11:11:03',
- 'ip': '10.0.1.3',
- 'ip6': '2001:10::3'}]
+ learnt = [
+ {"mac": "00:00:11:11:11:02", "ip": "10.0.1.2", "ip6": "2001:10::2"},
+ {"mac": "00:00:11:11:11:03", "ip": "10.0.1.3", "ip6": "2001:10::3"},
+ ]
#
# IP tables
@@ -3359,139 +3811,226 @@ class TestGBP(VppTestCase):
gbd2.add_vpp_config()
# ... and has a /32 and /128 applied
- ip4_addr = VppIpInterfaceAddress(self, gbd1.bvi,
- "10.0.0.128", 32,
- bind=b_ip4).add_vpp_config()
- ip6_addr = VppIpInterfaceAddress(self, gbd1.bvi,
- "2001:10::128", 128,
- bind=b_ip6).add_vpp_config()
- ip4_addr = VppIpInterfaceAddress(self, gbd2.bvi,
- "10.0.1.128", 32).add_vpp_config()
- ip6_addr = VppIpInterfaceAddress(self, gbd2.bvi,
- "2001:11::128", 128).add_vpp_config()
+ ip4_addr = VppIpInterfaceAddress(
+ self, gbd1.bvi, "10.0.0.128", 32, bind=b_ip4
+ ).add_vpp_config()
+ ip6_addr = VppIpInterfaceAddress(
+ self, gbd1.bvi, "2001:10::128", 128, bind=b_ip6
+ ).add_vpp_config()
+ ip4_addr = VppIpInterfaceAddress(
+ self, gbd2.bvi, "10.0.1.128", 32
+ ).add_vpp_config()
+ ip6_addr = VppIpInterfaceAddress(
+ self, gbd2.bvi, "2001:11::128", 128
+ ).add_vpp_config()
#
# The Endpoint-groups in which we are learning endpoints
#
- epg_220 = VppGbpEndpointGroup(self, 220, 440, rd1, gbd1,
- None, gbd1.bvi,
- "10.0.0.128",
- "2001:10::128",
- VppGbpEndpointRetention(60))
+ epg_220 = VppGbpEndpointGroup(
+ self,
+ 220,
+ 440,
+ rd1,
+ gbd1,
+ None,
+ gbd1.bvi,
+ "10.0.0.128",
+ "2001:10::128",
+ VppGbpEndpointRetention(60),
+ )
epg_220.add_vpp_config()
- epg_221 = VppGbpEndpointGroup(self, 221, 441, rd1, gbd2,
- None, gbd2.bvi,
- "10.0.1.128",
- "2001:11::128",
- VppGbpEndpointRetention(60))
+ epg_221 = VppGbpEndpointGroup(
+ self,
+ 221,
+ 441,
+ rd1,
+ gbd2,
+ None,
+ gbd2.bvi,
+ "10.0.1.128",
+ "2001:11::128",
+ VppGbpEndpointRetention(60),
+ )
epg_221.add_vpp_config()
- epg_222 = VppGbpEndpointGroup(self, 222, 442, rd1, gbd1,
- None, gbd1.bvi,
- "10.0.2.128",
- "2001:12::128",
- VppGbpEndpointRetention(60))
+ epg_222 = VppGbpEndpointGroup(
+ self,
+ 222,
+ 442,
+ rd1,
+ gbd1,
+ None,
+ gbd1.bvi,
+ "10.0.2.128",
+ "2001:12::128",
+ VppGbpEndpointRetention(60),
+ )
epg_222.add_vpp_config()
#
# a GBP bridge domains for the SEPs
#
- bd_uu1 = VppVxlanGbpTunnel(self, self.pg7.local_ip4,
- self.pg7.remote_ip4, 116)
+ bd_uu1 = VppVxlanGbpTunnel(self, self.pg7.local_ip4, self.pg7.remote_ip4, 116)
bd_uu1.add_vpp_config()
- bd_uu2 = VppVxlanGbpTunnel(self, self.pg7.local_ip4,
- self.pg7.remote_ip4, 117)
+ bd_uu2 = VppVxlanGbpTunnel(self, self.pg7.local_ip4, self.pg7.remote_ip4, 117)
bd_uu2.add_vpp_config()
bd3 = VppBridgeDomain(self, 3)
bd3.add_vpp_config()
- gbd3 = VppGbpBridgeDomain(self, bd3, rd1, self.loop2,
- bd_uu1, learn=False)
+ gbd3 = VppGbpBridgeDomain(self, bd3, rd1, self.loop2, bd_uu1, learn=False)
gbd3.add_vpp_config()
bd4 = VppBridgeDomain(self, 4)
bd4.add_vpp_config()
- gbd4 = VppGbpBridgeDomain(self, bd4, rd1, self.loop3,
- bd_uu2, learn=False)
+ gbd4 = VppGbpBridgeDomain(self, bd4, rd1, self.loop3, bd_uu2, learn=False)
gbd4.add_vpp_config()
#
# EPGs in which the service endpoints exist
#
- epg_320 = VppGbpEndpointGroup(self, 320, 550, rd1, gbd3,
- None, gbd1.bvi,
- "12.0.0.128",
- "4001:10::128",
- VppGbpEndpointRetention(60))
+ epg_320 = VppGbpEndpointGroup(
+ self,
+ 320,
+ 550,
+ rd1,
+ gbd3,
+ None,
+ gbd1.bvi,
+ "12.0.0.128",
+ "4001:10::128",
+ VppGbpEndpointRetention(60),
+ )
epg_320.add_vpp_config()
- epg_321 = VppGbpEndpointGroup(self, 321, 551, rd1, gbd4,
- None, gbd2.bvi,
- "12.0.1.128",
- "4001:11::128",
- VppGbpEndpointRetention(60))
+ epg_321 = VppGbpEndpointGroup(
+ self,
+ 321,
+ 551,
+ rd1,
+ gbd4,
+ None,
+ gbd2.bvi,
+ "12.0.1.128",
+ "4001:11::128",
+ VppGbpEndpointRetention(60),
+ )
epg_321.add_vpp_config()
#
# three local endpoints
#
- ep1 = VppGbpEndpoint(self, self.pg0,
- epg_220, None,
- "10.0.0.1", "11.0.0.1",
- "2001:10::1", "3001:10::1")
+ ep1 = VppGbpEndpoint(
+ self,
+ self.pg0,
+ epg_220,
+ None,
+ "10.0.0.1",
+ "11.0.0.1",
+ "2001:10::1",
+ "3001:10::1",
+ )
ep1.add_vpp_config()
- ep2 = VppGbpEndpoint(self, self.pg1,
- epg_221, None,
- "10.0.1.1", "11.0.1.1",
- "2001:11::1", "3001:11::1")
+ ep2 = VppGbpEndpoint(
+ self,
+ self.pg1,
+ epg_221,
+ None,
+ "10.0.1.1",
+ "11.0.1.1",
+ "2001:11::1",
+ "3001:11::1",
+ )
ep2.add_vpp_config()
- ep3 = VppGbpEndpoint(self, self.pg2,
- epg_222, None,
- "10.0.2.2", "11.0.2.2",
- "2001:12::1", "3001:12::1")
+ ep3 = VppGbpEndpoint(
+ self,
+ self.pg2,
+ epg_222,
+ None,
+ "10.0.2.2",
+ "11.0.2.2",
+ "2001:12::1",
+ "3001:12::1",
+ )
ep3.add_vpp_config()
#
# service endpoints
#
- sep1 = VppGbpEndpoint(self, self.pg3,
- epg_320, None,
- "12.0.0.1", "13.0.0.1",
- "4001:10::1", "5001:10::1")
+ sep1 = VppGbpEndpoint(
+ self,
+ self.pg3,
+ epg_320,
+ None,
+ "12.0.0.1",
+ "13.0.0.1",
+ "4001:10::1",
+ "5001:10::1",
+ )
sep1.add_vpp_config()
- sep2 = VppGbpEndpoint(self, self.pg4,
- epg_320, None,
- "12.0.0.2", "13.0.0.2",
- "4001:10::2", "5001:10::2")
+ sep2 = VppGbpEndpoint(
+ self,
+ self.pg4,
+ epg_320,
+ None,
+ "12.0.0.2",
+ "13.0.0.2",
+ "4001:10::2",
+ "5001:10::2",
+ )
sep2.add_vpp_config()
- sep3 = VppGbpEndpoint(self, self.pg5,
- epg_321, None,
- "12.0.1.1", "13.0.1.1",
- "4001:11::1", "5001:11::1")
+ sep3 = VppGbpEndpoint(
+ self,
+ self.pg5,
+ epg_321,
+ None,
+ "12.0.1.1",
+ "13.0.1.1",
+ "4001:11::1",
+ "5001:11::1",
+ )
sep3.add_vpp_config()
# this EP is not installed immediately
- sep4 = VppGbpEndpoint(self, self.pg6,
- epg_321, None,
- "12.0.1.2", "13.0.1.2",
- "4001:11::2", "5001:11::2")
+ sep4 = VppGbpEndpoint(
+ self,
+ self.pg6,
+ epg_321,
+ None,
+ "12.0.1.2",
+ "13.0.1.2",
+ "4001:11::2",
+ "5001:11::2",
+ )
#
# an L2 switch packet between local EPs in different EPGs
# different dest ports on each so the are LB hashed differently
#
- p4 = [(Ether(src=ep1.mac, dst=ep3.mac) /
- IP(src=ep1.ip4, dst=ep3.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(src=ep3.mac, dst=ep1.mac) /
- IP(src=ep3.ip4, dst=ep1.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
- p6 = [(Ether(src=ep1.mac, dst=ep3.mac) /
- IPv6(src=ep1.ip6, dst=ep3.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(src=ep3.mac, dst=ep1.mac) /
- IPv6(src=ep3.ip6, dst=ep1.ip6) /
- UDP(sport=1234, dport=1230) /
- Raw(b'\xa5' * 100))]
+ p4 = [
+ (
+ Ether(src=ep1.mac, dst=ep3.mac)
+ / IP(src=ep1.ip4, dst=ep3.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(src=ep3.mac, dst=ep1.mac)
+ / IP(src=ep3.ip4, dst=ep1.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
+ p6 = [
+ (
+ Ether(src=ep1.mac, dst=ep3.mac)
+ / IPv6(src=ep1.ip6, dst=ep3.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(src=ep3.mac, dst=ep1.mac)
+ / IPv6(src=ep3.ip6, dst=ep1.ip6)
+ / UDP(sport=1234, dport=1230)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
# should be dropped since no contract yet
self.send_and_assert_no_replies(self.pg0, [p4[0]])
@@ -3502,8 +4041,12 @@ class TestGBP(VppTestCase):
# one of the next-hops is via an EP that is not known
#
rule4 = AclRule(is_permit=1, proto=17)
- rule6 = AclRule(src_prefix=IPv6Network((0, 0)),
- dst_prefix=IPv6Network((0, 0)), is_permit=1, proto=17)
+ rule6 = AclRule(
+ src_prefix=IPv6Network((0, 0)),
+ dst_prefix=IPv6Network((0, 0)),
+ is_permit=1,
+ proto=17,
+ )
acl = VppAcl(self, rules=[rule4, rule6])
acl.add_vpp_config()
@@ -3511,41 +4054,75 @@ class TestGBP(VppTestCase):
# test the src-ip hash mode
#
c1 = VppGbpContract(
- self, 402, epg_220.sclass, epg_222.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip4, sep1.epg.rd),
- VppGbpContractNextHop(sep2.vmac, sep2.epg.bd,
- sep2.ip4, sep2.epg.rd)]),
+ self,
+ 402,
+ epg_220.sclass,
+ epg_222.sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip4, sep1.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep2.vmac, sep2.epg.bd, sep2.ip4, sep2.epg.rd
+ ),
+ ],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [VppGbpContractNextHop(sep3.vmac, sep3.epg.bd,
- sep3.ip6, sep3.epg.rd),
- VppGbpContractNextHop(sep4.vmac, sep4.epg.bd,
- sep4.ip6, sep4.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6])
+ [
+ VppGbpContractNextHop(
+ sep3.vmac, sep3.epg.bd, sep3.ip6, sep3.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep4.vmac, sep4.epg.bd, sep4.ip6, sep4.epg.rd
+ ),
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c1.add_vpp_config()
c2 = VppGbpContract(
- self, 402, epg_222.sclass, epg_220.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip4, sep1.epg.rd),
- VppGbpContractNextHop(sep2.vmac, sep2.epg.bd,
- sep2.ip4, sep2.epg.rd)]),
+ self,
+ 402,
+ epg_222.sclass,
+ epg_220.sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip4, sep1.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep2.vmac, sep2.epg.bd, sep2.ip4, sep2.epg.rd
+ ),
+ ],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [VppGbpContractNextHop(sep3.vmac, sep3.epg.bd,
- sep3.ip6, sep3.epg.rd),
- VppGbpContractNextHop(sep4.vmac, sep4.epg.bd,
- sep4.ip6, sep4.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6])
+ [
+ VppGbpContractNextHop(
+ sep3.vmac, sep3.epg.bd, sep3.ip6, sep3.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep4.vmac, sep4.epg.bd, sep4.ip6, sep4.epg.rd
+ ),
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c2.add_vpp_config()
#
@@ -3643,41 +4220,75 @@ class TestGBP(VppTestCase):
# test the symmetric hash mode
#
c1 = VppGbpContract(
- self, 402, epg_220.sclass, epg_222.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip4, sep1.epg.rd),
- VppGbpContractNextHop(sep2.vmac, sep2.epg.bd,
- sep2.ip4, sep2.epg.rd)]),
+ self,
+ 402,
+ epg_220.sclass,
+ epg_222.sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip4, sep1.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep2.vmac, sep2.epg.bd, sep2.ip4, sep2.epg.rd
+ ),
+ ],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
- [VppGbpContractNextHop(sep3.vmac, sep3.epg.bd,
- sep3.ip6, sep3.epg.rd),
- VppGbpContractNextHop(sep4.vmac, sep4.epg.bd,
- sep4.ip6, sep4.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6])
+ [
+ VppGbpContractNextHop(
+ sep3.vmac, sep3.epg.bd, sep3.ip6, sep3.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep4.vmac, sep4.epg.bd, sep4.ip6, sep4.epg.rd
+ ),
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c1.add_vpp_config()
c2 = VppGbpContract(
- self, 402, epg_222.sclass, epg_220.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip4, sep1.epg.rd),
- VppGbpContractNextHop(sep2.vmac, sep2.epg.bd,
- sep2.ip4, sep2.epg.rd)]),
+ self,
+ 402,
+ epg_222.sclass,
+ epg_220.sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip4, sep1.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep2.vmac, sep2.epg.bd, sep2.ip4, sep2.epg.rd
+ ),
+ ],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
- [VppGbpContractNextHop(sep3.vmac, sep3.epg.bd,
- sep3.ip6, sep3.epg.rd),
- VppGbpContractNextHop(sep4.vmac, sep4.epg.bd,
- sep4.ip6, sep4.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6])
+ [
+ VppGbpContractNextHop(
+ sep3.vmac, sep3.epg.bd, sep3.ip6, sep3.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep4.vmac, sep4.epg.bd, sep4.ip6, sep4.epg.rd
+ ),
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c2.add_vpp_config()
#
@@ -3709,40 +4320,69 @@ class TestGBP(VppTestCase):
# an L3 switch packet between local EPs in different EPGs
# different dest ports on each so the are LB hashed differently
#
- p4 = [(Ether(src=ep1.mac, dst=str(self.router_mac)) /
- IP(src=ep1.ip4, dst=ep2.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(src=ep2.mac, dst=str(self.router_mac)) /
- IP(src=ep2.ip4, dst=ep1.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
- p6 = [(Ether(src=ep1.mac, dst=str(self.router_mac)) /
- IPv6(src=ep1.ip6, dst=ep2.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(src=ep2.mac, dst=str(self.router_mac)) /
- IPv6(src=ep2.ip6, dst=ep1.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
+ p4 = [
+ (
+ Ether(src=ep1.mac, dst=str(self.router_mac))
+ / IP(src=ep1.ip4, dst=ep2.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(src=ep2.mac, dst=str(self.router_mac))
+ / IP(src=ep2.ip4, dst=ep1.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
+ p6 = [
+ (
+ Ether(src=ep1.mac, dst=str(self.router_mac))
+ / IPv6(src=ep1.ip6, dst=ep2.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(src=ep2.mac, dst=str(self.router_mac))
+ / IPv6(src=ep2.ip6, dst=ep1.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
c3 = VppGbpContract(
- self, 402, epg_220.sclass, epg_221.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip4, sep1.epg.rd),
- VppGbpContractNextHop(sep2.vmac, sep2.epg.bd,
- sep2.ip4, sep2.epg.rd)]),
+ self,
+ 402,
+ epg_220.sclass,
+ epg_221.sclass,
+ acl.acl_index,
+ [
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
- [VppGbpContractNextHop(sep3.vmac, sep3.epg.bd,
- sep3.ip6, sep3.epg.rd),
- VppGbpContractNextHop(sep4.vmac, sep4.epg.bd,
- sep4.ip6, sep4.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6])
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip4, sep1.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep2.vmac, sep2.epg.bd, sep2.ip4, sep2.epg.rd
+ ),
+ ],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
+ [
+ VppGbpContractNextHop(
+ sep3.vmac, sep3.epg.bd, sep3.ip6, sep3.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep4.vmac, sep4.epg.bd, sep4.ip6, sep4.epg.rd
+ ),
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c3.add_vpp_config()
rxs = self.send_and_expect(self.pg0, p4[0] * 17, sep1.itf)
@@ -3758,40 +4398,60 @@ class TestGBP(VppTestCase):
# packets coming from unknown remote EPs will be leant & redirected
#
vx_tun_l3 = VppGbpVxlanTunnel(
- self, 444, rd1.rd_id,
+ self,
+ 444,
+ rd1.rd_id,
VppEnum.vl_api_gbp_vxlan_tunnel_mode_t.GBP_VXLAN_TUNNEL_MODE_L3,
- self.pg2.local_ip4)
+ self.pg2.local_ip4,
+ )
vx_tun_l3.add_vpp_config()
c4 = VppGbpContract(
- self, 402, epg_221.sclass, epg_220.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip4, sep1.epg.rd),
- VppGbpContractNextHop(sep2.vmac, sep2.epg.bd,
- sep2.ip4, sep2.epg.rd)]),
+ self,
+ 402,
+ epg_221.sclass,
+ epg_220.sclass,
+ acl.acl_index,
+ [
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [VppGbpContractNextHop(sep3.vmac, sep3.epg.bd,
- sep3.ip6, sep3.epg.rd),
- VppGbpContractNextHop(sep4.vmac, sep4.epg.bd,
- sep4.ip6, sep4.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6])
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip4, sep1.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep2.vmac, sep2.epg.bd, sep2.ip4, sep2.epg.rd
+ ),
+ ],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [
+ VppGbpContractNextHop(
+ sep3.vmac, sep3.epg.bd, sep3.ip6, sep3.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep4.vmac, sep4.epg.bd, sep4.ip6, sep4.epg.rd
+ ),
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c4.add_vpp_config()
- p = (Ether(src=self.pg7.remote_mac,
- dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4,
- dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=444, gpid=441, flags=0x88) /
- Ether(src="00:22:22:22:22:33", dst=str(self.router_mac)) /
- IP(src="10.0.0.88", dst=ep1.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=444, gpid=441, flags=0x88)
+ / Ether(src="00:22:22:22:22:33", dst=str(self.router_mac))
+ / IP(src="10.0.0.88", dst=ep1.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
# unknown remote EP to local EP redirected
rxs = self.send_and_expect(self.pg7, [p], sep1.itf)
@@ -3803,20 +4463,18 @@ class TestGBP(VppTestCase):
self.assertEqual(rx[IP].dst, ep1.ip4)
# endpoint learnt via the parent GBP-vxlan interface
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l3._sw_if_index,
- ip="10.0.0.88"))
-
- p = (Ether(src=self.pg7.remote_mac,
- dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4,
- dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=444, gpid=441, flags=0x88) /
- Ether(src="00:22:22:22:22:33", dst=str(self.router_mac)) /
- IPv6(src="2001:10::88", dst=ep1.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ self.assertTrue(find_gbp_endpoint(self, vx_tun_l3._sw_if_index, ip="10.0.0.88"))
+
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=444, gpid=441, flags=0x88)
+ / Ether(src="00:22:22:22:22:33", dst=str(self.router_mac))
+ / IPv6(src="2001:10::88", dst=ep1.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
# unknown remote EP to local EP redirected (ipv6)
rxs = self.send_and_expect(self.pg7, [p], sep3.itf)
@@ -3828,21 +4486,29 @@ class TestGBP(VppTestCase):
self.assertEqual(rx[IPv6].dst, ep1.ip6)
# endpoint learnt via the parent GBP-vxlan interface
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l3._sw_if_index,
- ip="2001:10::88"))
+ self.assertTrue(
+ find_gbp_endpoint(self, vx_tun_l3._sw_if_index, ip="2001:10::88")
+ )
#
# L3 switch from local to remote EP
#
- p4 = [(Ether(src=ep1.mac, dst=str(self.router_mac)) /
- IP(src=ep1.ip4, dst="10.0.0.88") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
- p6 = [(Ether(src=ep1.mac, dst=str(self.router_mac)) /
- IPv6(src=ep1.ip6, dst="2001:10::88") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
+ p4 = [
+ (
+ Ether(src=ep1.mac, dst=str(self.router_mac))
+ / IP(src=ep1.ip4, dst="10.0.0.88")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ ]
+ p6 = [
+ (
+ Ether(src=ep1.mac, dst=str(self.router_mac))
+ / IPv6(src=ep1.ip6, dst="2001:10::88")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ ]
rxs = self.send_and_expect(self.pg0, p4[0] * 17, sep1.itf)
@@ -3864,22 +4530,39 @@ class TestGBP(VppTestCase):
# test the dst-ip hash mode
#
c5 = VppGbpContract(
- self, 402, epg_220.sclass, epg_221.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip4, sep1.epg.rd),
- VppGbpContractNextHop(sep2.vmac, sep2.epg.bd,
- sep2.ip4, sep2.epg.rd)]),
+ self,
+ 402,
+ epg_220.sclass,
+ epg_221.sclass,
+ acl.acl_index,
+ [
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
- [VppGbpContractNextHop(sep3.vmac, sep3.epg.bd,
- sep3.ip6, sep3.epg.rd),
- VppGbpContractNextHop(sep4.vmac, sep4.epg.bd,
- sep4.ip6, sep4.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6])
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip4, sep1.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep2.vmac, sep2.epg.bd, sep2.ip4, sep2.epg.rd
+ ),
+ ],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
+ [
+ VppGbpContractNextHop(
+ sep3.vmac, sep3.epg.bd, sep3.ip6, sep3.epg.rd
+ ),
+ VppGbpContractNextHop(
+ sep4.vmac, sep4.epg.bd, sep4.ip6, sep4.epg.rd
+ ),
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c5.add_vpp_config()
rxs = self.send_and_expect(self.pg0, p4[0] * 17, sep1.itf)
@@ -3904,20 +4587,29 @@ class TestGBP(VppTestCase):
# gbp vxlan tunnel for the remote SEP
vx_tun_l3_sep = VppGbpVxlanTunnel(
- self, 555, rd1.rd_id,
+ self,
+ 555,
+ rd1.rd_id,
VppEnum.vl_api_gbp_vxlan_tunnel_mode_t.GBP_VXLAN_TUNNEL_MODE_L3,
- self.pg2.local_ip4)
+ self.pg2.local_ip4,
+ )
vx_tun_l3_sep.add_vpp_config()
# remote SEP
- sep5 = VppGbpEndpoint(self, vx_tun_l3_sep,
- epg_320, None,
- "12.0.0.10", "13.0.0.10",
- "4001:10::10", "5001:10::10",
- ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
- self.pg7.local_ip4,
- self.pg7.remote_ip4,
- mac=None)
+ sep5 = VppGbpEndpoint(
+ self,
+ vx_tun_l3_sep,
+ epg_320,
+ None,
+ "12.0.0.10",
+ "13.0.0.10",
+ "4001:10::10",
+ "5001:10::10",
+ ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
+ self.pg7.local_ip4,
+ self.pg7.remote_ip4,
+ mac=None,
+ )
sep5.add_vpp_config()
#
@@ -3934,101 +4626,187 @@ class TestGBP(VppTestCase):
gebd = VppGbpBridgeDomain(self, ebd, rd1, self.loop4, None, None)
gebd.add_vpp_config()
# the external epg
- eepg = VppGbpEndpointGroup(self, 888, 765, rd1, gebd,
- None, gebd.bvi,
- "10.1.0.128",
- "2001:10:1::128",
- VppGbpEndpointRetention(60))
- eepg.add_vpp_config()
- # add subnets to BVI
- VppIpInterfaceAddress(
+ eepg = VppGbpEndpointGroup(
self,
+ 888,
+ 765,
+ rd1,
+ gebd,
+ None,
gebd.bvi,
"10.1.0.128",
- 24, bind=b_lo4_ip4).add_vpp_config()
+ "2001:10:1::128",
+ VppGbpEndpointRetention(60),
+ )
+ eepg.add_vpp_config()
+ # add subnets to BVI
+ VppIpInterfaceAddress(
+ self, gebd.bvi, "10.1.0.128", 24, bind=b_lo4_ip4
+ ).add_vpp_config()
VppIpInterfaceAddress(
+ self, gebd.bvi, "2001:10:1::128", 64, bind=b_lo4_ip6
+ ).add_vpp_config()
+ # ... which are L3-out subnets
+ VppGbpSubnet(
self,
- gebd.bvi,
+ rd1,
+ "10.1.0.0",
+ 24,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
+ sclass=765,
+ ).add_vpp_config()
+ VppGbpSubnet(
+ self,
+ rd1,
"2001:10:1::128",
- 64, bind=b_lo4_ip6).add_vpp_config()
- # ... which are L3-out subnets
- VppGbpSubnet(self, rd1, "10.1.0.0", 24,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=765).add_vpp_config()
- VppGbpSubnet(self, rd1, "2001:10:1::128", 64,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=765).add_vpp_config()
+ 64,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
+ sclass=765,
+ ).add_vpp_config()
# external endpoints
VppL2Vtr(self, self.vlan_100, L2_VTR_OP.L2_POP_1).add_vpp_config()
- eep1 = VppGbpEndpoint(self, self.vlan_100, eepg, None, "10.1.0.1",
- "11.1.0.1", "2001:10:1::1", "3001:10:1::1",
- ep_flags.GBP_API_ENDPOINT_FLAG_EXTERNAL)
+ eep1 = VppGbpEndpoint(
+ self,
+ self.vlan_100,
+ eepg,
+ None,
+ "10.1.0.1",
+ "11.1.0.1",
+ "2001:10:1::1",
+ "3001:10:1::1",
+ ep_flags.GBP_API_ENDPOINT_FLAG_EXTERNAL,
+ )
eep1.add_vpp_config()
VppL2Vtr(self, self.vlan_101, L2_VTR_OP.L2_POP_1).add_vpp_config()
- eep2 = VppGbpEndpoint(self, self.vlan_101, eepg, None, "10.1.0.2",
- "11.1.0.2", "2001:10:1::2", "3001:10:1::2",
- ep_flags.GBP_API_ENDPOINT_FLAG_EXTERNAL)
+ eep2 = VppGbpEndpoint(
+ self,
+ self.vlan_101,
+ eepg,
+ None,
+ "10.1.0.2",
+ "11.1.0.2",
+ "2001:10:1::2",
+ "3001:10:1::2",
+ ep_flags.GBP_API_ENDPOINT_FLAG_EXTERNAL,
+ )
eep2.add_vpp_config()
# external subnets reachable though eep1 and eep2 respectively
- VppIpRoute(self, "10.220.0.0", 24,
- [VppRoutePath(eep1.ip4, eep1.epg.bvi.sw_if_index)],
- table_id=t4.table_id).add_vpp_config()
- VppGbpSubnet(self, rd1, "10.220.0.0", 24,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4220).add_vpp_config()
- VppIpRoute(self, "10:220::", 64,
- [VppRoutePath(eep1.ip6, eep1.epg.bvi.sw_if_index)],
- table_id=t6.table_id).add_vpp_config()
- VppGbpSubnet(self, rd1, "10:220::", 64,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4220).add_vpp_config()
- VppIpRoute(self, "10.221.0.0", 24,
- [VppRoutePath(eep2.ip4, eep2.epg.bvi.sw_if_index)],
- table_id=t4.table_id).add_vpp_config()
- VppGbpSubnet(self, rd1, "10.221.0.0", 24,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4221).add_vpp_config()
- VppIpRoute(self, "10:221::", 64,
- [VppRoutePath(eep2.ip6, eep2.epg.bvi.sw_if_index)],
- table_id=t6.table_id).add_vpp_config()
- VppGbpSubnet(self, rd1, "10:221::", 64,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4221).add_vpp_config()
+ VppIpRoute(
+ self,
+ "10.220.0.0",
+ 24,
+ [VppRoutePath(eep1.ip4, eep1.epg.bvi.sw_if_index)],
+ table_id=t4.table_id,
+ ).add_vpp_config()
+ VppGbpSubnet(
+ self,
+ rd1,
+ "10.220.0.0",
+ 24,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
+ sclass=4220,
+ ).add_vpp_config()
+ VppIpRoute(
+ self,
+ "10:220::",
+ 64,
+ [VppRoutePath(eep1.ip6, eep1.epg.bvi.sw_if_index)],
+ table_id=t6.table_id,
+ ).add_vpp_config()
+ VppGbpSubnet(
+ self,
+ rd1,
+ "10:220::",
+ 64,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
+ sclass=4220,
+ ).add_vpp_config()
+ VppIpRoute(
+ self,
+ "10.221.0.0",
+ 24,
+ [VppRoutePath(eep2.ip4, eep2.epg.bvi.sw_if_index)],
+ table_id=t4.table_id,
+ ).add_vpp_config()
+ VppGbpSubnet(
+ self,
+ rd1,
+ "10.221.0.0",
+ 24,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
+ sclass=4221,
+ ).add_vpp_config()
+ VppIpRoute(
+ self,
+ "10:221::",
+ 64,
+ [VppRoutePath(eep2.ip6, eep2.epg.bvi.sw_if_index)],
+ table_id=t6.table_id,
+ ).add_vpp_config()
+ VppGbpSubnet(
+ self,
+ rd1,
+ "10:221::",
+ 64,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
+ sclass=4221,
+ ).add_vpp_config()
#
# l3out redirect to remote (known, then unknown) SEP
#
# packets from 1 external subnet to the other
- p = [(Ether(src=eep1.mac, dst=self.router_mac) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.17", dst="10.221.0.65") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(src=eep1.mac, dst=self.router_mac) /
- Dot1Q(vlan=100) /
- IPv6(src="10:220::17", dst="10:221::65") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
+ p = [
+ (
+ Ether(src=eep1.mac, dst=self.router_mac)
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.17", dst="10.221.0.65")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(src=eep1.mac, dst=self.router_mac)
+ / Dot1Q(vlan=100)
+ / IPv6(src="10:220::17", dst="10:221::65")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
# packets should be dropped in absence of contract
self.send_and_assert_no_replies(self.pg0, p)
# contract redirecting to sep5
VppGbpContract(
- self, 402, 4220, 4221, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
- [VppGbpContractNextHop(sep5.vmac, sep5.epg.bd,
- sep5.ip4, sep5.epg.rd)]),
+ self,
+ 402,
+ 4220,
+ 4221,
+ acl.acl_index,
+ [
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
- [VppGbpContractNextHop(sep5.vmac, sep5.epg.bd,
- sep5.ip6, sep5.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6]).add_vpp_config()
+ [
+ VppGbpContractNextHop(
+ sep5.vmac, sep5.epg.bd, sep5.ip4, sep5.epg.rd
+ )
+ ],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
+ [
+ VppGbpContractNextHop(
+ sep5.vmac, sep5.epg.bd, sep5.ip6, sep5.epg.rd
+ )
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ ).add_vpp_config()
rxs = self.send_and_expect(self.pg0, p, self.pg7)
@@ -4081,18 +4859,33 @@ class TestGBP(VppTestCase):
# change the contract between l3out to redirect to local SEPs
# instead of remote SEP
VppGbpContract(
- self, 402, 4220, 4221, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip4, sep1.epg.rd)]),
+ self,
+ 402,
+ 4220,
+ 4221,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip4, sep1.epg.rd
+ )
+ ],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip6, sep1.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6]).add_vpp_config()
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip6, sep1.epg.rd
+ )
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ ).add_vpp_config()
rxs = self.send_and_expect(self.pg0, p, sep1.itf)
for rx, tx in zip(rxs, p):
@@ -4112,34 +4905,57 @@ class TestGBP(VppTestCase):
# contract to redirect to learnt SEP
VppGbpContract(
- self, 402, epg_221.sclass, epg_222.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
- [VppGbpContractNextHop(sep5.vmac, sep5.epg.bd,
- sep5.ip4, sep5.epg.rd)]),
+ self,
+ 402,
+ epg_221.sclass,
+ epg_222.sclass,
+ acl.acl_index,
+ [
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
- [VppGbpContractNextHop(sep5.vmac, sep5.epg.bd,
- sep5.ip6, sep5.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6]).add_vpp_config()
+ [
+ VppGbpContractNextHop(
+ sep5.vmac, sep5.epg.bd, sep5.ip4, sep5.epg.rd
+ )
+ ],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_DST_IP,
+ [
+ VppGbpContractNextHop(
+ sep5.vmac, sep5.epg.bd, sep5.ip6, sep5.epg.rd
+ )
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ ).add_vpp_config()
# packets from unknown EP 221 to known EP in EPG 222
# should be redirected to known remote SEP
- base = (Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=444, gpid=441, flags=0x88) /
- Ether(src="00:22:22:22:22:44", dst=str(self.router_mac)))
- p = [(base /
- IP(src="10.0.1.100", dst=ep3.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (base /
- IPv6(src="2001:10::100", dst=ep3.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
+ base = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=444, gpid=441, flags=0x88)
+ / Ether(src="00:22:22:22:22:44", dst=str(self.router_mac))
+ )
+ p = [
+ (
+ base
+ / IP(src="10.0.1.100", dst=ep3.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ base
+ / IPv6(src="2001:10::100", dst=ep3.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
# unknown remote EP to local EP redirected to known remote SEP
rxs = self.send_and_expect(self.pg7, p, self.pg7)
@@ -4163,12 +4979,12 @@ class TestGBP(VppTestCase):
self.assertEqual(rxip.dst, txip.dst)
# endpoint learnt via the parent GBP-vxlan interface
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l3._sw_if_index,
- ip="10.0.1.100"))
- self.assertTrue(find_gbp_endpoint(self,
- vx_tun_l3._sw_if_index,
- ip="2001:10::100"))
+ self.assertTrue(
+ find_gbp_endpoint(self, vx_tun_l3._sw_if_index, ip="10.0.1.100")
+ )
+ self.assertTrue(
+ find_gbp_endpoint(self, vx_tun_l3._sw_if_index, ip="2001:10::100")
+ )
# remote SEP: it is now an unknown remote SEP and should go
# to spine proxy
@@ -4202,7 +5018,7 @@ class TestGBP(VppTestCase):
self.pg7.unconfig_ip4()
def test_gbp_redirect_extended(self):
- """ GBP Endpoint Redirect Extended """
+ """GBP Endpoint Redirect Extended"""
self.vapi.cli("set logging class gbp level debug")
@@ -4210,12 +5026,10 @@ class TestGBP(VppTestCase):
routed_dst_mac = "00:0c:0c:0c:0c:0c"
routed_src_mac = "00:22:bd:f8:19:ff"
- learnt = [{'mac': '00:00:11:11:11:02',
- 'ip': '10.0.1.2',
- 'ip6': '2001:10::2'},
- {'mac': '00:00:11:11:11:03',
- 'ip': '10.0.1.3',
- 'ip6': '2001:10::3'}]
+ learnt = [
+ {"mac": "00:00:11:11:11:02", "ip": "10.0.1.2", "ip6": "2001:10::2"},
+ {"mac": "00:00:11:11:11:03", "ip": "10.0.1.3", "ip6": "2001:10::3"},
+ ]
#
# IP tables
@@ -4232,8 +5046,10 @@ class TestGBP(VppTestCase):
self.pg7.local_ip4,
self.pg7.remote_ip4,
114,
- mode=(VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.
- VXLAN_GBP_API_TUNNEL_MODE_L3))
+ mode=(
+ VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.VXLAN_GBP_API_TUNNEL_MODE_L3
+ ),
+ )
rd_uu4.add_vpp_config()
VppIpInterfaceBind(self, rd_uu4, t4).add_vpp_config()
@@ -4242,8 +5058,10 @@ class TestGBP(VppTestCase):
self.pg7.local_ip4,
self.pg7.remote_ip4,
115,
- mode=(VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.
- VXLAN_GBP_API_TUNNEL_MODE_L3))
+ mode=(
+ VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.VXLAN_GBP_API_TUNNEL_MODE_L3
+ ),
+ )
rd_uu6.add_vpp_config()
VppIpInterfaceBind(self, rd_uu6, t4).add_vpp_config()
@@ -4284,54 +5102,66 @@ class TestGBP(VppTestCase):
gbd2.add_vpp_config()
# ... and has a /32 and /128 applied
- ip4_addr1 = VppIpInterfaceAddress(self, gbd1.bvi,
- "10.0.0.128", 32,
- bind=b_lo0_ip4).add_vpp_config()
- ip6_addr1 = VppIpInterfaceAddress(self, gbd1.bvi,
- "2001:10::128", 128,
- bind=b_lo0_ip6).add_vpp_config()
- ip4_addr2 = VppIpInterfaceAddress(self, gbd2.bvi,
- "10.0.1.128", 32,
- bind=b_lo1_ip4).add_vpp_config()
- ip6_addr2 = VppIpInterfaceAddress(self, gbd2.bvi,
- "2001:11::128", 128,
- bind=b_lo1_ip6).add_vpp_config()
+ ip4_addr1 = VppIpInterfaceAddress(
+ self, gbd1.bvi, "10.0.0.128", 32, bind=b_lo0_ip4
+ ).add_vpp_config()
+ ip6_addr1 = VppIpInterfaceAddress(
+ self, gbd1.bvi, "2001:10::128", 128, bind=b_lo0_ip6
+ ).add_vpp_config()
+ ip4_addr2 = VppIpInterfaceAddress(
+ self, gbd2.bvi, "10.0.1.128", 32, bind=b_lo1_ip4
+ ).add_vpp_config()
+ ip6_addr2 = VppIpInterfaceAddress(
+ self, gbd2.bvi, "2001:11::128", 128, bind=b_lo1_ip6
+ ).add_vpp_config()
#
# The Endpoint-groups
#
- epg_220 = VppGbpEndpointGroup(self, 220, 440, rd1, gbd1,
- None, gbd1.bvi,
- "10.0.0.128",
- "2001:10::128",
- VppGbpEndpointRetention(60))
+ epg_220 = VppGbpEndpointGroup(
+ self,
+ 220,
+ 440,
+ rd1,
+ gbd1,
+ None,
+ gbd1.bvi,
+ "10.0.0.128",
+ "2001:10::128",
+ VppGbpEndpointRetention(60),
+ )
epg_220.add_vpp_config()
- epg_221 = VppGbpEndpointGroup(self, 221, 441, rd1, gbd2,
- None, gbd2.bvi,
- "10.0.1.128",
- "2001:11::128",
- VppGbpEndpointRetention(60))
+ epg_221 = VppGbpEndpointGroup(
+ self,
+ 221,
+ 441,
+ rd1,
+ gbd2,
+ None,
+ gbd2.bvi,
+ "10.0.1.128",
+ "2001:11::128",
+ VppGbpEndpointRetention(60),
+ )
epg_221.add_vpp_config()
#
# a GBP bridge domains for the SEPs
#
- bd_uu3 = VppVxlanGbpTunnel(self, self.pg7.local_ip4,
- self.pg7.remote_ip4, 116)
+ bd_uu3 = VppVxlanGbpTunnel(self, self.pg7.local_ip4, self.pg7.remote_ip4, 116)
bd_uu3.add_vpp_config()
bd3 = VppBridgeDomain(self, 3)
bd3.add_vpp_config()
- gbd3 = VppGbpBridgeDomain(self, bd3, rd1, self.loop2,
- bd_uu3, learn=False)
+ gbd3 = VppGbpBridgeDomain(self, bd3, rd1, self.loop2, bd_uu3, learn=False)
gbd3.add_vpp_config()
- ip4_addr3 = VppIpInterfaceAddress(self, gbd3.bvi,
- "12.0.0.128", 32,
- bind=b_lo2_ip4).add_vpp_config()
- ip6_addr3 = VppIpInterfaceAddress(self, gbd3.bvi,
- "4001:10::128", 128,
- bind=b_lo2_ip6).add_vpp_config()
+ ip4_addr3 = VppIpInterfaceAddress(
+ self, gbd3.bvi, "12.0.0.128", 32, bind=b_lo2_ip4
+ ).add_vpp_config()
+ ip6_addr3 = VppIpInterfaceAddress(
+ self, gbd3.bvi, "4001:10::128", 128, bind=b_lo2_ip6
+ ).add_vpp_config()
#
# self.logger.info(self.vapi.cli("show gbp bridge"))
@@ -4343,38 +5173,69 @@ class TestGBP(VppTestCase):
#
# EPGs in which the service endpoints exist
#
- epg_320 = VppGbpEndpointGroup(self, 320, 550, rd1, gbd3,
- None, gbd3.bvi,
- "12.0.0.128",
- "4001:10::128",
- VppGbpEndpointRetention(60))
+ epg_320 = VppGbpEndpointGroup(
+ self,
+ 320,
+ 550,
+ rd1,
+ gbd3,
+ None,
+ gbd3.bvi,
+ "12.0.0.128",
+ "4001:10::128",
+ VppGbpEndpointRetention(60),
+ )
epg_320.add_vpp_config()
#
# endpoints
#
- ep1 = VppGbpEndpoint(self, self.pg0,
- epg_220, None,
- "10.0.0.1", "11.0.0.1",
- "2001:10::1", "3001:10::1")
+ ep1 = VppGbpEndpoint(
+ self,
+ self.pg0,
+ epg_220,
+ None,
+ "10.0.0.1",
+ "11.0.0.1",
+ "2001:10::1",
+ "3001:10::1",
+ )
ep1.add_vpp_config()
- ep2 = VppGbpEndpoint(self, self.pg1,
- epg_221, None,
- "10.0.1.1", "11.0.1.1",
- "2001:11::1", "3001:11::1")
+ ep2 = VppGbpEndpoint(
+ self,
+ self.pg1,
+ epg_221,
+ None,
+ "10.0.1.1",
+ "11.0.1.1",
+ "2001:11::1",
+ "3001:11::1",
+ )
ep2.add_vpp_config()
#
# service endpoints
#
- sep1 = VppGbpEndpoint(self, self.pg3,
- epg_320, None,
- "12.0.0.1", "13.0.0.1",
- "4001:10::1", "5001:10::1")
- sep2 = VppGbpEndpoint(self, self.pg4,
- epg_320, None,
- "12.0.0.2", "13.0.0.2",
- "4001:10::2", "5001:10::2")
+ sep1 = VppGbpEndpoint(
+ self,
+ self.pg3,
+ epg_320,
+ None,
+ "12.0.0.1",
+ "13.0.0.1",
+ "4001:10::1",
+ "5001:10::1",
+ )
+ sep2 = VppGbpEndpoint(
+ self,
+ self.pg4,
+ epg_320,
+ None,
+ "12.0.0.2",
+ "13.0.0.2",
+ "4001:10::2",
+ "5001:10::2",
+ )
# sep1 and sep2 are not added to config yet
# they are unknown for now
@@ -4382,34 +5243,54 @@ class TestGBP(VppTestCase):
#
# add routes to EPG subnets
#
- VppGbpSubnet(self, rd1, "10.0.0.0", 24,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_TRANSPORT
- ).add_vpp_config()
- VppGbpSubnet(self, rd1, "10.0.1.0", 24,
- VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_TRANSPORT
- ).add_vpp_config()
+ VppGbpSubnet(
+ self,
+ rd1,
+ "10.0.0.0",
+ 24,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_TRANSPORT,
+ ).add_vpp_config()
+ VppGbpSubnet(
+ self,
+ rd1,
+ "10.0.1.0",
+ 24,
+ VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_TRANSPORT,
+ ).add_vpp_config()
#
# Local host to known local host in different BD
# with SFC contract (source and destination are in
# one node and service endpoint in another node)
#
- p4 = [(Ether(src=ep1.mac, dst=str(self.router_mac)) /
- IP(src=ep1.ip4, dst=ep2.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(src=ep2.mac, dst=str(self.router_mac)) /
- IP(src=ep2.ip4, dst=ep1.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
- p6 = [(Ether(src=ep1.mac, dst=str(self.router_mac)) /
- IPv6(src=ep1.ip6, dst=ep2.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(src=ep2.mac, dst=str(self.router_mac)) /
- IPv6(src=ep2.ip6, dst=ep1.ip6) /
- UDP(sport=1234, dport=1230) /
- Raw(b'\xa5' * 100))]
+ p4 = [
+ (
+ Ether(src=ep1.mac, dst=str(self.router_mac))
+ / IP(src=ep1.ip4, dst=ep2.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(src=ep2.mac, dst=str(self.router_mac))
+ / IP(src=ep2.ip4, dst=ep1.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
+ p6 = [
+ (
+ Ether(src=ep1.mac, dst=str(self.router_mac))
+ / IPv6(src=ep1.ip6, dst=ep2.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(src=ep2.mac, dst=str(self.router_mac))
+ / IPv6(src=ep2.ip6, dst=ep1.ip6)
+ / UDP(sport=1234, dport=1230)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
# should be dropped since no contract yet
self.send_and_assert_no_replies(self.pg0, [p4[0]])
@@ -4420,8 +5301,12 @@ class TestGBP(VppTestCase):
# one of the next-hops is via an EP that is not known
#
rule4 = AclRule(is_permit=1, proto=17)
- rule6 = AclRule(src_prefix=IPv6Network((0, 0)),
- dst_prefix=IPv6Network((0, 0)), is_permit=1, proto=17)
+ rule6 = AclRule(
+ src_prefix=IPv6Network((0, 0)),
+ dst_prefix=IPv6Network((0, 0)),
+ is_permit=1,
+ proto=17,
+ )
acl = VppAcl(self, rules=[rule4, rule6])
acl.add_vpp_config()
@@ -4429,33 +5314,63 @@ class TestGBP(VppTestCase):
# test the src-ip hash mode
#
c1 = VppGbpContract(
- self, 402, epg_220.sclass, epg_221.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip4, sep1.epg.rd)]),
- VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip6, sep1.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6])
+ self,
+ 402,
+ epg_220.sclass,
+ epg_221.sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip4, sep1.epg.rd
+ )
+ ],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip6, sep1.epg.rd
+ )
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c1.add_vpp_config()
c2 = VppGbpContract(
- self, 402, epg_221.sclass, epg_220.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip4, sep1.epg.rd)]),
- VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
- [VppGbpContractNextHop(sep1.vmac, sep1.epg.bd,
- sep1.ip6, sep1.epg.rd)])],
- [ETH_P_IP, ETH_P_IPV6])
+ self,
+ 402,
+ epg_221.sclass,
+ epg_220.sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip4, sep1.epg.rd
+ )
+ ],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_REDIRECT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
+ [
+ VppGbpContractNextHop(
+ sep1.vmac, sep1.epg.bd, sep1.ip6, sep1.epg.rd
+ )
+ ],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c2.add_vpp_config()
# ep1 <--> ep2 redirected through sep1
@@ -4564,16 +5479,16 @@ class TestGBP(VppTestCase):
self.assertEqual(rx[IPv6].dst, ep1.ip6)
# packet coming from the l2 spine-proxy to sep1
- p = (Ether(src=self.pg7.remote_mac,
- dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4,
- dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=116, gpid=440, gpflags=0x08, flags=0x88) /
- Ether(src=str(self.router_mac), dst=sep1.mac) /
- IP(src=ep1.ip4, dst=ep2.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=116, gpid=440, gpflags=0x08, flags=0x88)
+ / Ether(src=str(self.router_mac), dst=sep1.mac)
+ / IP(src=ep1.ip4, dst=ep2.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg7, [p] * 17, sep1.itf)
@@ -4585,14 +5500,23 @@ class TestGBP(VppTestCase):
# contract for SEP to communicate with dst EP
c3 = VppGbpContract(
- self, 402, epg_320.sclass, epg_221.sclass, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC),
- VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC)],
- [ETH_P_IP, ETH_P_IPV6])
+ self,
+ 402,
+ epg_320.sclass,
+ epg_221.sclass,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SYMMETRIC,
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c3.add_vpp_config()
# temporarily remove ep2, so that ep2 is remote & unknown
@@ -4602,10 +5526,12 @@ class TestGBP(VppTestCase):
# as ep2 is now unknown (see above), it must go through
# the rd UU (packet is routed)
- p1 = (Ether(src=sep1.mac, dst=self.router_mac) /
- IP(src=ep1.ip4, dst=ep2.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p1 = (
+ Ether(src=sep1.mac, dst=self.router_mac)
+ / IP(src=ep1.ip4, dst=ep2.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg3, [p1] * 17, self.pg7)
@@ -4634,16 +5560,16 @@ class TestGBP(VppTestCase):
ep2.add_vpp_config()
# packet coming back from the remote sep through rd UU
- p2 = (Ether(src=self.pg7.remote_mac,
- dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4,
- dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=114, gpid=441, gpflags=0x09, flags=0x88) /
- Ether(src=str(self.router_mac), dst=self.router_mac) /
- IP(src=ep1.ip4, dst=ep2.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p2 = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=114, gpid=441, gpflags=0x09, flags=0x88)
+ / Ether(src=str(self.router_mac), dst=self.router_mac)
+ / IP(src=ep1.ip4, dst=ep2.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg7, [p2], self.pg1)
@@ -4666,7 +5592,7 @@ class TestGBP(VppTestCase):
self.pg7.unconfig_ip4()
def test_gbp_l3_out(self):
- """ GBP L3 Out """
+ """GBP L3 Out"""
ep_flags = VppEnum.vl_api_gbp_endpoint_flags_t
self.vapi.cli("set logging class gbp level debug")
@@ -4703,9 +5629,9 @@ class TestGBP(VppTestCase):
#
# a multicast vxlan-gbp tunnel for broadcast in the BD
#
- tun_bm = VppVxlanGbpTunnel(self, self.pg7.local_ip4,
- "239.1.1.1", 88,
- mcast_itf=self.pg7)
+ tun_bm = VppVxlanGbpTunnel(
+ self, self.pg7.local_ip4, "239.1.1.1", 88, mcast_itf=self.pg7
+ )
tun_bm.add_vpp_config()
#
@@ -4719,24 +5645,37 @@ class TestGBP(VppTestCase):
#
# The Endpoint-groups in which the external endpoints exist
#
- epg_220 = VppGbpEndpointGroup(self, 220, 113, rd1, gbd1,
- None, gbd1.bvi,
- "10.0.0.128",
- "2001:10::128",
- VppGbpEndpointRetention(4))
+ epg_220 = VppGbpEndpointGroup(
+ self,
+ 220,
+ 113,
+ rd1,
+ gbd1,
+ None,
+ gbd1.bvi,
+ "10.0.0.128",
+ "2001:10::128",
+ VppGbpEndpointRetention(4),
+ )
epg_220.add_vpp_config()
# the BVIs have the subnets applied ...
- ip4_addr = VppIpInterfaceAddress(self, gbd1.bvi, "10.0.0.128",
- 24, bind=b_ip4).add_vpp_config()
- ip6_addr = VppIpInterfaceAddress(self, gbd1.bvi, "2001:10::128",
- 64, bind=b_ip6).add_vpp_config()
+ ip4_addr = VppIpInterfaceAddress(
+ self, gbd1.bvi, "10.0.0.128", 24, bind=b_ip4
+ ).add_vpp_config()
+ ip6_addr = VppIpInterfaceAddress(
+ self, gbd1.bvi, "2001:10::128", 64, bind=b_ip6
+ ).add_vpp_config()
# ... which are L3-out subnets
l3o_1 = VppGbpSubnet(
- self, rd1, "10.0.0.0", 24,
+ self,
+ rd1,
+ "10.0.0.0",
+ 24,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=113)
+ sclass=113,
+ )
l3o_1.add_vpp_config()
#
@@ -4753,90 +5692,139 @@ class TestGBP(VppTestCase):
# an unicast vxlan-gbp for inter-RD traffic
#
vx_tun_l3 = VppGbpVxlanTunnel(
- self, 444, rd1.rd_id,
+ self,
+ 444,
+ rd1.rd_id,
VppEnum.vl_api_gbp_vxlan_tunnel_mode_t.GBP_VXLAN_TUNNEL_MODE_L3,
- self.pg2.local_ip4)
+ self.pg2.local_ip4,
+ )
vx_tun_l3.add_vpp_config()
#
# External Endpoints
#
- eep1 = VppGbpEndpoint(self, self.vlan_100,
- epg_220, None,
- "10.0.0.1", "11.0.0.1",
- "2001:10::1", "3001::1",
- ep_flags.GBP_API_ENDPOINT_FLAG_EXTERNAL)
+ eep1 = VppGbpEndpoint(
+ self,
+ self.vlan_100,
+ epg_220,
+ None,
+ "10.0.0.1",
+ "11.0.0.1",
+ "2001:10::1",
+ "3001::1",
+ ep_flags.GBP_API_ENDPOINT_FLAG_EXTERNAL,
+ )
eep1.add_vpp_config()
- eep2 = VppGbpEndpoint(self, self.vlan_101,
- epg_220, None,
- "10.0.0.2", "11.0.0.2",
- "2001:10::2", "3001::2",
- ep_flags.GBP_API_ENDPOINT_FLAG_EXTERNAL)
+ eep2 = VppGbpEndpoint(
+ self,
+ self.vlan_101,
+ epg_220,
+ None,
+ "10.0.0.2",
+ "11.0.0.2",
+ "2001:10::2",
+ "3001::2",
+ ep_flags.GBP_API_ENDPOINT_FLAG_EXTERNAL,
+ )
eep2.add_vpp_config()
- eep3 = VppGbpEndpoint(self, self.vlan_102,
- epg_220, None,
- "10.0.0.3", "11.0.0.3",
- "2001:10::3", "3001::3",
- ep_flags.GBP_API_ENDPOINT_FLAG_EXTERNAL)
+ eep3 = VppGbpEndpoint(
+ self,
+ self.vlan_102,
+ epg_220,
+ None,
+ "10.0.0.3",
+ "11.0.0.3",
+ "2001:10::3",
+ "3001::3",
+ ep_flags.GBP_API_ENDPOINT_FLAG_EXTERNAL,
+ )
eep3.add_vpp_config()
#
# A remote external endpoint
#
- rep = VppGbpEndpoint(self, vx_tun_l3,
- epg_220, None,
- "10.0.0.101", "11.0.0.101",
- "2001:10::101", "3001::101",
- ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
- self.pg7.local_ip4,
- self.pg7.remote_ip4,
- mac=None)
+ rep = VppGbpEndpoint(
+ self,
+ vx_tun_l3,
+ epg_220,
+ None,
+ "10.0.0.101",
+ "11.0.0.101",
+ "2001:10::101",
+ "3001::101",
+ ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
+ self.pg7.local_ip4,
+ self.pg7.remote_ip4,
+ mac=None,
+ )
rep.add_vpp_config()
#
# EP1 impersonating EP3 is dropped
#
- p = (Ether(src=eep1.mac, dst="ff:ff:ff:ff:ff:ff") /
- Dot1Q(vlan=100) /
- ARP(op="who-has",
- psrc="10.0.0.3", pdst="10.0.0.128",
- hwsrc=eep1.mac, hwdst="ff:ff:ff:ff:ff:ff"))
+ p = (
+ Ether(src=eep1.mac, dst="ff:ff:ff:ff:ff:ff")
+ / Dot1Q(vlan=100)
+ / ARP(
+ op="who-has",
+ psrc="10.0.0.3",
+ pdst="10.0.0.128",
+ hwsrc=eep1.mac,
+ hwdst="ff:ff:ff:ff:ff:ff",
+ )
+ )
self.send_and_assert_no_replies(self.pg0, p)
#
# ARP packet from External EPs are accepted and replied to
#
- p_arp = (Ether(src=eep1.mac, dst="ff:ff:ff:ff:ff:ff") /
- Dot1Q(vlan=100) /
- ARP(op="who-has",
- psrc=eep1.ip4, pdst="10.0.0.128",
- hwsrc=eep1.mac, hwdst="ff:ff:ff:ff:ff:ff"))
+ p_arp = (
+ Ether(src=eep1.mac, dst="ff:ff:ff:ff:ff:ff")
+ / Dot1Q(vlan=100)
+ / ARP(
+ op="who-has",
+ psrc=eep1.ip4,
+ pdst="10.0.0.128",
+ hwsrc=eep1.mac,
+ hwdst="ff:ff:ff:ff:ff:ff",
+ )
+ )
rxs = self.send_and_expect(self.pg0, p_arp * 1, self.pg0)
#
# ARP packet from host in remote subnet are accepted and replied to
#
- p_arp = (Ether(src=eep3.mac, dst="ff:ff:ff:ff:ff:ff") /
- Dot1Q(vlan=102) /
- ARP(op="who-has",
- psrc=eep3.ip4, pdst="10.0.0.128",
- hwsrc=eep3.mac, hwdst="ff:ff:ff:ff:ff:ff"))
+ p_arp = (
+ Ether(src=eep3.mac, dst="ff:ff:ff:ff:ff:ff")
+ / Dot1Q(vlan=102)
+ / ARP(
+ op="who-has",
+ psrc=eep3.ip4,
+ pdst="10.0.0.128",
+ hwsrc=eep3.mac,
+ hwdst="ff:ff:ff:ff:ff:ff",
+ )
+ )
rxs = self.send_and_expect(self.pg0, p_arp * 1, self.pg0)
#
# packets destined to unknown addresses in the BVI's subnet
# are ARP'd for
#
- p4 = (Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.0.0.1", dst="10.0.0.88") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- p6 = (Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IPv6(src="2001:10::1", dst="2001:10::88") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p4 = (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.0.0.1", dst="10.0.0.88")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ p6 = (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IPv6(src="2001:10::1", dst="2001:10::88")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p4 * 1, self.pg7)
@@ -4860,26 +5848,28 @@ class TestGBP(VppTestCase):
#
# remote to external
#
- p = (Ether(src=self.pg7.remote_mac,
- dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4,
- dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=444, gpid=113, flags=0x88) /
- Ether(src=self.pg0.remote_mac, dst=str(self.router_mac)) /
- IP(src="10.0.0.101", dst="10.0.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=444, gpid=113, flags=0x88)
+ / Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src="10.0.0.101", dst="10.0.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg7, p * 1, self.pg0)
#
# local EP pings router
#
- p = (Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src=eep1.ip4, dst="10.0.0.128") /
- ICMP(type='echo-request'))
+ p = (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src=eep1.ip4, dst="10.0.0.128")
+ / ICMP(type="echo-request")
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg0)
@@ -4891,10 +5881,12 @@ class TestGBP(VppTestCase):
#
# local EP pings other local EP
#
- p = (Ether(src=eep1.mac, dst=eep2.mac) /
- Dot1Q(vlan=100) /
- IP(src=eep1.ip4, dst=eep2.ip4) /
- ICMP(type='echo-request'))
+ p = (
+ Ether(src=eep1.mac, dst=eep2.mac)
+ / Dot1Q(vlan=100)
+ / IP(src=eep1.ip4, dst=eep2.ip4)
+ / ICMP(type="echo-request")
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg0)
@@ -4906,10 +5898,12 @@ class TestGBP(VppTestCase):
#
# local EP pings router w/o vlan tag poped
#
- p = (Ether(src=eep3.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=102) /
- IP(src=eep3.ip4, dst="10.0.0.128") /
- ICMP(type='echo-request'))
+ p = (
+ Ether(src=eep3.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=102)
+ / IP(src=eep3.ip4, dst="10.0.0.128")
+ / ICMP(type="echo-request")
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg0)
@@ -4920,56 +5914,79 @@ class TestGBP(VppTestCase):
#
# A ip4 subnet reachable through the external EP1
#
- ip_220 = VppIpRoute(self, "10.220.0.0", 24,
- [VppRoutePath(eep1.ip4,
- eep1.epg.bvi.sw_if_index)],
- table_id=t4.table_id)
+ ip_220 = VppIpRoute(
+ self,
+ "10.220.0.0",
+ 24,
+ [VppRoutePath(eep1.ip4, eep1.epg.bvi.sw_if_index)],
+ table_id=t4.table_id,
+ )
ip_220.add_vpp_config()
l3o_220 = VppGbpSubnet(
- self, rd1, "10.220.0.0", 24,
+ self,
+ rd1,
+ "10.220.0.0",
+ 24,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4220)
+ sclass=4220,
+ )
l3o_220.add_vpp_config()
#
# An ip6 subnet reachable through the external EP1
#
- ip6_220 = VppIpRoute(self, "10:220::", 64,
- [VppRoutePath(eep1.ip6,
- eep1.epg.bvi.sw_if_index)],
- table_id=t6.table_id)
+ ip6_220 = VppIpRoute(
+ self,
+ "10:220::",
+ 64,
+ [VppRoutePath(eep1.ip6, eep1.epg.bvi.sw_if_index)],
+ table_id=t6.table_id,
+ )
ip6_220.add_vpp_config()
l3o6_220 = VppGbpSubnet(
- self, rd1, "10:220::", 64,
+ self,
+ rd1,
+ "10:220::",
+ 64,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4220)
+ sclass=4220,
+ )
l3o6_220.add_vpp_config()
#
# A subnet reachable through the external EP2
#
- ip_221 = VppIpRoute(self, "10.221.0.0", 24,
- [VppRoutePath(eep2.ip4,
- eep2.epg.bvi.sw_if_index)],
- table_id=t4.table_id)
+ ip_221 = VppIpRoute(
+ self,
+ "10.221.0.0",
+ 24,
+ [VppRoutePath(eep2.ip4, eep2.epg.bvi.sw_if_index)],
+ table_id=t4.table_id,
+ )
ip_221.add_vpp_config()
l3o_221 = VppGbpSubnet(
- self, rd1, "10.221.0.0", 24,
+ self,
+ rd1,
+ "10.221.0.0",
+ 24,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4221)
+ sclass=4221,
+ )
l3o_221.add_vpp_config()
#
# ping between hosts in remote subnets
# dropped without a contract
#
- p = (Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst="10.221.0.1") /
- ICMP(type='echo-request'))
+ p = (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst="10.221.0.1")
+ / ICMP(type="echo-request")
+ )
self.send_and_assert_no_replies(self.pg0, p * 1)
@@ -4977,8 +5994,12 @@ class TestGBP(VppTestCase):
# contract for the external nets to communicate
#
rule4 = AclRule(is_permit=1, proto=17)
- rule6 = AclRule(src_prefix=IPv6Network((0, 0)),
- dst_prefix=IPv6Network((0, 0)), is_permit=1, proto=17)
+ rule6 = AclRule(
+ src_prefix=IPv6Network((0, 0)),
+ dst_prefix=IPv6Network((0, 0)),
+ is_permit=1,
+ proto=17,
+ )
acl = VppAcl(self, rules=[rule4, rule6])
acl.add_vpp_config()
@@ -4986,68 +6007,106 @@ class TestGBP(VppTestCase):
# A contract with the wrong scope is not matched
#
c_44 = VppGbpContract(
- self, 44, 4220, 4221, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
- VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ self,
+ 44,
+ 4220,
+ 4221,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c_44.add_vpp_config()
self.send_and_assert_no_replies(self.pg0, p * 1)
c1 = VppGbpContract(
- self, 55, 4220, 4221, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 55,
+ 4220,
+ 4221,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c1.add_vpp_config()
#
# Contracts allowing ext-net 200 to talk with external EPs
#
c2 = VppGbpContract(
- self, 55, 4220, 113, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 55,
+ 4220,
+ 113,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c2.add_vpp_config()
c3 = VppGbpContract(
- self, 55, 113, 4220, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 55,
+ 113,
+ 4220,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c3.add_vpp_config()
#
# ping between hosts in remote subnets
#
- p = (Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst="10.221.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst="10.221.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg0)
@@ -5063,27 +6122,29 @@ class TestGBP(VppTestCase):
#
# from remote external EP to local external EP
#
- p = (Ether(src=self.pg7.remote_mac,
- dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4,
- dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=444, gpid=113, flags=0x88) /
- Ether(src=self.pg0.remote_mac, dst=str(self.router_mac)) /
- IP(src="10.0.0.101", dst="10.220.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=444, gpid=113, flags=0x88)
+ / Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src="10.0.0.101", dst="10.220.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg7, p * 1, self.pg0)
#
# ping from an external host to the remote external EP
#
- p = (Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst=rep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst=rep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg7)
@@ -5113,10 +6174,14 @@ class TestGBP(VppTestCase):
# first the VXLAN-GBP tunnel over which it is reached
#
vx_tun_r1 = VppVxlanGbpTunnel(
- self, self.pg7.local_ip4,
- self.pg7.remote_ip4, 445,
- mode=(VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.
- VXLAN_GBP_API_TUNNEL_MODE_L3))
+ self,
+ self.pg7.local_ip4,
+ self.pg7.remote_ip4,
+ 445,
+ mode=(
+ VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.VXLAN_GBP_API_TUNNEL_MODE_L3
+ ),
+ )
vx_tun_r1.add_vpp_config()
VppIpInterfaceBind(self, vx_tun_r1, t4).add_vpp_config()
@@ -5125,36 +6190,44 @@ class TestGBP(VppTestCase):
#
# then the special adj to resolve through on that tunnel
#
- n1 = VppNeighbor(self,
- vx_tun_r1.sw_if_index,
- "00:0c:0c:0c:0c:0c",
- self.pg7.remote_ip4)
+ n1 = VppNeighbor(
+ self, vx_tun_r1.sw_if_index, "00:0c:0c:0c:0c:0c", self.pg7.remote_ip4
+ )
n1.add_vpp_config()
#
# the route via the adj above
#
- ip_222 = VppIpRoute(self, "10.222.0.0", 24,
- [VppRoutePath(self.pg7.remote_ip4,
- vx_tun_r1.sw_if_index)],
- table_id=t4.table_id)
+ ip_222 = VppIpRoute(
+ self,
+ "10.222.0.0",
+ 24,
+ [VppRoutePath(self.pg7.remote_ip4, vx_tun_r1.sw_if_index)],
+ table_id=t4.table_id,
+ )
ip_222.add_vpp_config()
l3o_222 = VppGbpSubnet(
- self, rd1, "10.222.0.0", 24,
+ self,
+ rd1,
+ "10.222.0.0",
+ 24,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4222)
+ sclass=4222,
+ )
l3o_222.add_vpp_config()
#
# ping between hosts in local and remote external subnets
# dropped without a contract
#
- p = (Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst="10.222.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst="10.222.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_assert_no_replies(self.pg0, p * 1)
@@ -5162,26 +6235,37 @@ class TestGBP(VppTestCase):
# Add contracts ext-nets for 220 -> 222
#
c4 = VppGbpContract(
- self, 55, 4220, 4222, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 55,
+ 4220,
+ 4222,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c4.add_vpp_config()
#
# ping from host in local to remote external subnets
#
- p = (Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst="10.222.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst="10.222.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * 3, self.pg7)
@@ -5208,39 +6292,50 @@ class TestGBP(VppTestCase):
# make the external subnet ECMP
#
vx_tun_r2 = VppVxlanGbpTunnel(
- self, self.pg7.local_ip4,
- self.pg7.remote_ip4, 446,
- mode=(VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.
- VXLAN_GBP_API_TUNNEL_MODE_L3))
+ self,
+ self.pg7.local_ip4,
+ self.pg7.remote_ip4,
+ 446,
+ mode=(
+ VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.VXLAN_GBP_API_TUNNEL_MODE_L3
+ ),
+ )
vx_tun_r2.add_vpp_config()
VppIpInterfaceBind(self, vx_tun_r2, t4).add_vpp_config()
self.logger.info(self.vapi.cli("sh vxlan-gbp tunnel"))
- n2 = VppNeighbor(self,
- vx_tun_r2.sw_if_index,
- "00:0c:0c:0c:0c:0c",
- self.pg7.remote_ip4)
+ n2 = VppNeighbor(
+ self, vx_tun_r2.sw_if_index, "00:0c:0c:0c:0c:0c", self.pg7.remote_ip4
+ )
n2.add_vpp_config()
- ip_222.modify([VppRoutePath(self.pg7.remote_ip4,
- vx_tun_r1.sw_if_index),
- VppRoutePath(self.pg7.remote_ip4,
- vx_tun_r2.sw_if_index)])
+ ip_222.modify(
+ [
+ VppRoutePath(self.pg7.remote_ip4, vx_tun_r1.sw_if_index),
+ VppRoutePath(self.pg7.remote_ip4, vx_tun_r2.sw_if_index),
+ ]
+ )
#
# now expect load-balance
#
- p = [(Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst="10.222.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst="10.222.0.1") /
- UDP(sport=1222, dport=1235) /
- Raw(b'\xa5' * 100))]
+ p = [
+ (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst="10.222.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst="10.222.0.1")
+ / UDP(sport=1222, dport=1235)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
rxs = self.send_and_expect(self.pg0, p, self.pg7)
@@ -5250,41 +6345,53 @@ class TestGBP(VppTestCase):
#
# Same LB test for v6
#
- n3 = VppNeighbor(self,
- vx_tun_r1.sw_if_index,
- "00:0c:0c:0c:0c:0c",
- self.pg7.remote_ip6)
+ n3 = VppNeighbor(
+ self, vx_tun_r1.sw_if_index, "00:0c:0c:0c:0c:0c", self.pg7.remote_ip6
+ )
n3.add_vpp_config()
- n4 = VppNeighbor(self,
- vx_tun_r2.sw_if_index,
- "00:0c:0c:0c:0c:0c",
- self.pg7.remote_ip6)
+ n4 = VppNeighbor(
+ self, vx_tun_r2.sw_if_index, "00:0c:0c:0c:0c:0c", self.pg7.remote_ip6
+ )
n4.add_vpp_config()
- ip_222_6 = VppIpRoute(self, "10:222::", 64,
- [VppRoutePath(self.pg7.remote_ip6,
- vx_tun_r1.sw_if_index),
- VppRoutePath(self.pg7.remote_ip6,
- vx_tun_r2.sw_if_index)],
- table_id=t6.table_id)
+ ip_222_6 = VppIpRoute(
+ self,
+ "10:222::",
+ 64,
+ [
+ VppRoutePath(self.pg7.remote_ip6, vx_tun_r1.sw_if_index),
+ VppRoutePath(self.pg7.remote_ip6, vx_tun_r2.sw_if_index),
+ ],
+ table_id=t6.table_id,
+ )
ip_222_6.add_vpp_config()
l3o_222_6 = VppGbpSubnet(
- self, rd1, "10:222::", 64,
+ self,
+ rd1,
+ "10:222::",
+ 64,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4222)
+ sclass=4222,
+ )
l3o_222_6.add_vpp_config()
- p = [(Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IPv6(src="10:220::1", dst="10:222::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(src=eep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IPv6(src="10:220::1", dst="10:222::1") /
- UDP(sport=7777, dport=8881) /
- Raw(b'\xa5' * 100))]
+ p = [
+ (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IPv6(src="10:220::1", dst="10:222::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(src=eep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IPv6(src="10:220::1", dst="10:222::1")
+ / UDP(sport=7777, dport=8881)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
self.logger.info(self.vapi.cli("sh ip6 fib 10:222::1"))
rxs = self.send_and_expect(self.pg0, p, self.pg7)
@@ -5296,14 +6403,16 @@ class TestGBP(VppTestCase):
# ping from host in remote to local external subnets
# there's no contract for this, but the A bit is set.
#
- p = (Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=445, gpid=4222, flags=0x88, gpflags='A') /
- Ether(src=self.pg0.remote_mac, dst=str(self.router_mac)) /
- IP(src="10.222.0.1", dst="10.220.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=445, gpid=4222, flags=0x88, gpflags="A")
+ / Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src="10.222.0.1", dst="10.220.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg7, p * 3, self.pg0)
self.assertFalse(find_gbp_endpoint(self, ip="10.222.0.1"))
@@ -5312,45 +6421,57 @@ class TestGBP(VppTestCase):
# ping from host in remote to remote external subnets
# this is dropped by reflection check.
#
- p = (Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=445, gpid=4222, flags=0x88, gpflags='A') /
- Ether(src=self.pg0.remote_mac, dst=str(self.router_mac)) /
- IP(src="10.222.0.1", dst="10.222.0.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=445, gpid=4222, flags=0x88, gpflags="A")
+ / Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src="10.222.0.1", dst="10.222.0.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_assert_no_replies(self.pg7, p * 3)
- p = (Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=445, gpid=4222, flags=0x88, gpflags='A') /
- Ether(src=self.pg0.remote_mac, dst=str(self.router_mac)) /
- IPv6(src="10:222::1", dst="10:222::2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=445, gpid=4222, flags=0x88, gpflags="A")
+ / Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IPv6(src="10:222::1", dst="10:222::2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_assert_no_replies(self.pg7, p * 3)
#
# local EP
#
- lep1 = VppGbpEndpoint(self, vlan_144,
- epg_220, None,
- "10.0.0.44", "11.0.0.44",
- "2001:10::44", "3001::44")
+ lep1 = VppGbpEndpoint(
+ self,
+ vlan_144,
+ epg_220,
+ None,
+ "10.0.0.44",
+ "11.0.0.44",
+ "2001:10::44",
+ "3001::44",
+ )
lep1.add_vpp_config()
#
# local EP to local ip4 external subnet
#
- p = (Ether(src=lep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=144) /
- IP(src=lep1.ip4, dst="10.220.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=lep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=144)
+ / IP(src=lep1.ip4, dst="10.220.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg0)
@@ -5362,11 +6483,13 @@ class TestGBP(VppTestCase):
#
# local EP to local ip6 external subnet
#
- p = (Ether(src=lep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=144) /
- IPv6(src=lep1.ip6, dst="10:220::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=lep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=144)
+ / IPv6(src=lep1.ip6, dst="10:220::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg0)
@@ -5378,48 +6501,70 @@ class TestGBP(VppTestCase):
#
# ip4 and ip6 subnets that load-balance
#
- ip_20 = VppIpRoute(self, "10.20.0.0", 24,
- [VppRoutePath(eep1.ip4,
- eep1.epg.bvi.sw_if_index),
- VppRoutePath(eep2.ip4,
- eep2.epg.bvi.sw_if_index)],
- table_id=t4.table_id)
+ ip_20 = VppIpRoute(
+ self,
+ "10.20.0.0",
+ 24,
+ [
+ VppRoutePath(eep1.ip4, eep1.epg.bvi.sw_if_index),
+ VppRoutePath(eep2.ip4, eep2.epg.bvi.sw_if_index),
+ ],
+ table_id=t4.table_id,
+ )
ip_20.add_vpp_config()
l3o_20 = VppGbpSubnet(
- self, rd1, "10.20.0.0", 24,
+ self,
+ rd1,
+ "10.20.0.0",
+ 24,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4220)
+ sclass=4220,
+ )
l3o_20.add_vpp_config()
- ip6_20 = VppIpRoute(self, "10:20::", 64,
- [VppRoutePath(eep1.ip6,
- eep1.epg.bvi.sw_if_index),
- VppRoutePath(eep2.ip6,
- eep2.epg.bvi.sw_if_index)],
- table_id=t6.table_id)
+ ip6_20 = VppIpRoute(
+ self,
+ "10:20::",
+ 64,
+ [
+ VppRoutePath(eep1.ip6, eep1.epg.bvi.sw_if_index),
+ VppRoutePath(eep2.ip6, eep2.epg.bvi.sw_if_index),
+ ],
+ table_id=t6.table_id,
+ )
ip6_20.add_vpp_config()
l3o6_20 = VppGbpSubnet(
- self, rd1, "10:20::", 64,
+ self,
+ rd1,
+ "10:20::",
+ 64,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4220)
+ sclass=4220,
+ )
l3o6_20.add_vpp_config()
self.logger.info(self.vapi.cli("sh ip fib 10.20.0.1"))
self.logger.info(self.vapi.cli("sh ip6 fib 10:20::1"))
# two ip6 packets whose port are chosen so they load-balance
- p = [(Ether(src=lep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=144) /
- IPv6(src=lep1.ip6, dst="10:20::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(src=lep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=144) /
- IPv6(src=lep1.ip6, dst="10:20::1") /
- UDP(sport=124, dport=1230) /
- Raw(b'\xa5' * 100))]
+ p = [
+ (
+ Ether(src=lep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=144)
+ / IPv6(src=lep1.ip6, dst="10:20::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(src=lep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=144)
+ / IPv6(src=lep1.ip6, dst="10:20::1")
+ / UDP(sport=124, dport=1230)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
rxs = self.send_and_expect(self.pg0, p, self.pg0, 2)
@@ -5427,16 +6572,22 @@ class TestGBP(VppTestCase):
self.assertEqual(rxs[1][Dot1Q].vlan, 100)
# two ip4 packets whose port are chosen so they load-balance
- p = [(Ether(src=lep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=144) /
- IP(src=lep1.ip4, dst="10.20.0.1") /
- UDP(sport=1235, dport=1235) /
- Raw(b'\xa5' * 100)),
- (Ether(src=lep1.mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=144) /
- IP(src=lep1.ip4, dst="10.20.0.1") /
- UDP(sport=124, dport=1230) /
- Raw(b'\xa5' * 100))]
+ p = [
+ (
+ Ether(src=lep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=144)
+ / IP(src=lep1.ip4, dst="10.20.0.1")
+ / UDP(sport=1235, dport=1235)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(src=lep1.mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=144)
+ / IP(src=lep1.ip4, dst="10.20.0.1")
+ / UDP(sport=124, dport=1230)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
rxs = self.send_and_expect(self.pg0, p, self.pg0, 2)
@@ -5452,7 +6603,7 @@ class TestGBP(VppTestCase):
self.vlan_100.set_vtr(L2_VTR_OP.L2_DISABLED)
def test_gbp_anon_l3_out(self):
- """ GBP Anonymous L3 Out """
+ """GBP Anonymous L3 Out"""
ep_flags = VppEnum.vl_api_gbp_endpoint_flags_t
self.vapi.cli("set logging class gbp level debug")
@@ -5497,23 +6648,34 @@ class TestGBP(VppTestCase):
#
# The Endpoint-groups in which the external endpoints exist
#
- epg_220 = VppGbpEndpointGroup(self, 220, 113, rd1, gbd1,
- None, gbd1.bvi,
- "10.0.0.128",
- "2001:10::128",
- VppGbpEndpointRetention(4))
+ epg_220 = VppGbpEndpointGroup(
+ self,
+ 220,
+ 113,
+ rd1,
+ gbd1,
+ None,
+ gbd1.bvi,
+ "10.0.0.128",
+ "2001:10::128",
+ VppGbpEndpointRetention(4),
+ )
epg_220.add_vpp_config()
# the BVIs have the subnet applied ...
- ip4_addr = VppIpInterfaceAddress(self, gbd1.bvi,
- "10.0.0.128", 24,
- bind=bind_l0_ip4).add_vpp_config()
+ ip4_addr = VppIpInterfaceAddress(
+ self, gbd1.bvi, "10.0.0.128", 24, bind=bind_l0_ip4
+ ).add_vpp_config()
# ... which is an Anonymous L3-out subnets
l3o_1 = VppGbpSubnet(
- self, rd1, "10.0.0.0", 24,
+ self,
+ rd1,
+ "10.0.0.0",
+ 24,
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_ANON_L3_OUT,
- sclass=113)
+ sclass=113,
+ )
l3o_1.add_vpp_config()
#
@@ -5535,22 +6697,31 @@ class TestGBP(VppTestCase):
# an unicast vxlan-gbp for inter-RD traffic
#
vx_tun_l3 = VppGbpVxlanTunnel(
- self, 444, rd1.rd_id,
+ self,
+ 444,
+ rd1.rd_id,
VppEnum.vl_api_gbp_vxlan_tunnel_mode_t.GBP_VXLAN_TUNNEL_MODE_L3,
- self.pg2.local_ip4)
+ self.pg2.local_ip4,
+ )
vx_tun_l3.add_vpp_config()
#
# A remote external endpoint
#
- rep = VppGbpEndpoint(self, vx_tun_l3,
- epg_220, None,
- "10.0.0.201", "11.0.0.201",
- "2001:10::201", "3001::101",
- ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
- self.pg7.local_ip4,
- self.pg7.remote_ip4,
- mac=None)
+ rep = VppGbpEndpoint(
+ self,
+ vx_tun_l3,
+ epg_220,
+ None,
+ "10.0.0.201",
+ "11.0.0.201",
+ "2001:10::201",
+ "3001::101",
+ ep_flags.GBP_API_ENDPOINT_FLAG_REMOTE,
+ self.pg7.local_ip4,
+ self.pg7.remote_ip4,
+ mac=None,
+ )
rep.add_vpp_config()
#
@@ -5559,48 +6730,56 @@ class TestGBP(VppTestCase):
# - APR request flooded over the other vlan subif
# - ARP reply from BVI
#
- p_arp = (Ether(src=self.vlan_100.remote_mac,
- dst="ff:ff:ff:ff:ff:ff") /
- Dot1Q(vlan=100) /
- ARP(op="who-has",
- psrc="10.0.0.100",
- pdst="10.0.0.128",
- hwsrc=self.vlan_100.remote_mac,
- hwdst="ff:ff:ff:ff:ff:ff"))
+ p_arp = (
+ Ether(src=self.vlan_100.remote_mac, dst="ff:ff:ff:ff:ff:ff")
+ / Dot1Q(vlan=100)
+ / ARP(
+ op="who-has",
+ psrc="10.0.0.100",
+ pdst="10.0.0.128",
+ hwsrc=self.vlan_100.remote_mac,
+ hwdst="ff:ff:ff:ff:ff:ff",
+ )
+ )
rxs = self.send_and_expect(self.pg0, p_arp * 1, self.pg0, n_rx=2)
- p_arp = (Ether(src=self.vlan_101.remote_mac,
- dst="ff:ff:ff:ff:ff:ff") /
- Dot1Q(vlan=101) /
- ARP(op="who-has",
- psrc='10.0.0.101',
- pdst="10.0.0.128",
- hwsrc=self.vlan_101.remote_mac,
- hwdst="ff:ff:ff:ff:ff:ff"))
+ p_arp = (
+ Ether(src=self.vlan_101.remote_mac, dst="ff:ff:ff:ff:ff:ff")
+ / Dot1Q(vlan=101)
+ / ARP(
+ op="who-has",
+ psrc="10.0.0.101",
+ pdst="10.0.0.128",
+ hwsrc=self.vlan_101.remote_mac,
+ hwdst="ff:ff:ff:ff:ff:ff",
+ )
+ )
rxs = self.send_and_expect(self.pg0, p_arp * 1, self.pg0, n_rx=2)
#
# remote to external
#
- p = (Ether(src=self.pg7.remote_mac,
- dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4,
- dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=vx_tun_l3.vni, gpid=epg_220.sclass, flags=0x88) /
- Ether(src=self.pg0.remote_mac, dst=str(self.router_mac)) /
- IP(src=str(rep.ip4), dst="10.0.0.100") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=vx_tun_l3.vni, gpid=epg_220.sclass, flags=0x88)
+ / Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src=str(rep.ip4), dst="10.0.0.100")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg7, p * 1, self.pg0)
#
# local EP pings router
#
- p = (Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.0.0.100", dst="10.0.0.128") /
- ICMP(type='echo-request'))
+ p = (
+ Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.0.0.100", dst="10.0.0.128")
+ / ICMP(type="echo-request")
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg0)
for rx in rxs:
@@ -5611,11 +6790,12 @@ class TestGBP(VppTestCase):
#
# local EP pings other local EP
#
- p = (Ether(src=self.vlan_100.remote_mac,
- dst=self.vlan_101.remote_mac) /
- Dot1Q(vlan=100) /
- IP(src="10.0.0.100", dst="10.0.0.101") /
- ICMP(type='echo-request'))
+ p = (
+ Ether(src=self.vlan_100.remote_mac, dst=self.vlan_101.remote_mac)
+ / Dot1Q(vlan=100)
+ / IP(src="10.0.0.100", dst="10.0.0.101")
+ / ICMP(type="echo-request")
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg0)
for rx in rxs:
@@ -5626,43 +6806,59 @@ class TestGBP(VppTestCase):
#
# A subnet reachable through an external router on vlan 100
#
- ip_220 = VppIpRoute(self, "10.220.0.0", 24,
- [VppRoutePath("10.0.0.100",
- epg_220.bvi.sw_if_index)],
- table_id=t4.table_id)
+ ip_220 = VppIpRoute(
+ self,
+ "10.220.0.0",
+ 24,
+ [VppRoutePath("10.0.0.100", epg_220.bvi.sw_if_index)],
+ table_id=t4.table_id,
+ )
ip_220.add_vpp_config()
l3o_220 = VppGbpSubnet(
- self, rd1, "10.220.0.0", 24,
+ self,
+ rd1,
+ "10.220.0.0",
+ 24,
# note: this a "regular" L3 out subnet (not connected)
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4220)
+ sclass=4220,
+ )
l3o_220.add_vpp_config()
#
# A subnet reachable through an external router on vlan 101
#
- ip_221 = VppIpRoute(self, "10.221.0.0", 24,
- [VppRoutePath("10.0.0.101",
- epg_220.bvi.sw_if_index)],
- table_id=t4.table_id)
+ ip_221 = VppIpRoute(
+ self,
+ "10.221.0.0",
+ 24,
+ [VppRoutePath("10.0.0.101", epg_220.bvi.sw_if_index)],
+ table_id=t4.table_id,
+ )
ip_221.add_vpp_config()
l3o_221 = VppGbpSubnet(
- self, rd1, "10.221.0.0", 24,
+ self,
+ rd1,
+ "10.221.0.0",
+ 24,
# note: this a "regular" L3 out subnet (not connected)
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4221)
+ sclass=4221,
+ )
l3o_221.add_vpp_config()
#
# ping between hosts in remote subnets
# dropped without a contract
#
- p = (Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst="10.221.0.1") /
- ICMP(type='echo-request'))
+ p = (
+ Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst="10.221.0.1")
+ / ICMP(type="echo-request")
+ )
rxs = self.send_and_assert_no_replies(self.pg0, p * 1)
@@ -5670,60 +6866,93 @@ class TestGBP(VppTestCase):
# contract for the external nets to communicate
#
rule4 = AclRule(is_permit=1, proto=17)
- rule6 = AclRule(src_prefix=IPv6Network((0, 0)),
- dst_prefix=IPv6Network((0, 0)), is_permit=1, proto=17)
+ rule6 = AclRule(
+ src_prefix=IPv6Network((0, 0)),
+ dst_prefix=IPv6Network((0, 0)),
+ is_permit=1,
+ proto=17,
+ )
acl = VppAcl(self, rules=[rule4, rule6])
acl.add_vpp_config()
c1 = VppGbpContract(
- self, 55, 4220, 4221, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 55,
+ 4220,
+ 4221,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c1.add_vpp_config()
#
# Contracts allowing ext-net 200 to talk with external EPs
#
c2 = VppGbpContract(
- self, 55, 4220, 113, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 55,
+ 4220,
+ 113,
+ acl.acl_index,
+ [
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c2.add_vpp_config()
c3 = VppGbpContract(
- self, 55, 113, 4220, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 55,
+ 113,
+ 4220,
+ acl.acl_index,
+ [
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c3.add_vpp_config()
#
# ping between hosts in remote subnets
#
- p = (Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst="10.221.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst="10.221.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg0)
@@ -5739,27 +6968,29 @@ class TestGBP(VppTestCase):
#
# from remote external EP to local external EP
#
- p = (Ether(src=self.pg7.remote_mac,
- dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4,
- dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=444, gpid=113, flags=0x88) /
- Ether(src=self.pg0.remote_mac, dst=str(self.router_mac)) /
- IP(src=rep.ip4, dst="10.220.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=444, gpid=113, flags=0x88)
+ / Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src=rep.ip4, dst="10.220.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg7, p * 1, self.pg0)
#
# ping from an external host to the remote external EP
#
- p = (Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst=rep.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst=rep.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * 1, self.pg7)
@@ -5789,10 +7020,14 @@ class TestGBP(VppTestCase):
# first the VXLAN-GBP tunnel over which it is reached
#
vx_tun_r = VppVxlanGbpTunnel(
- self, self.pg7.local_ip4,
- self.pg7.remote_ip4, 445,
- mode=(VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.
- VXLAN_GBP_API_TUNNEL_MODE_L3))
+ self,
+ self.pg7.local_ip4,
+ self.pg7.remote_ip4,
+ 445,
+ mode=(
+ VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.VXLAN_GBP_API_TUNNEL_MODE_L3
+ ),
+ )
vx_tun_r.add_vpp_config()
VppIpInterfaceBind(self, vx_tun_r, t4).add_vpp_config()
@@ -5801,37 +7036,45 @@ class TestGBP(VppTestCase):
#
# then the special adj to resolve through on that tunnel
#
- n1 = VppNeighbor(self,
- vx_tun_r.sw_if_index,
- "00:0c:0c:0c:0c:0c",
- self.pg7.remote_ip4)
+ n1 = VppNeighbor(
+ self, vx_tun_r.sw_if_index, "00:0c:0c:0c:0c:0c", self.pg7.remote_ip4
+ )
n1.add_vpp_config()
#
# the route via the adj above
#
- ip_222 = VppIpRoute(self, "10.222.0.0", 24,
- [VppRoutePath(self.pg7.remote_ip4,
- vx_tun_r.sw_if_index)],
- table_id=t4.table_id)
+ ip_222 = VppIpRoute(
+ self,
+ "10.222.0.0",
+ 24,
+ [VppRoutePath(self.pg7.remote_ip4, vx_tun_r.sw_if_index)],
+ table_id=t4.table_id,
+ )
ip_222.add_vpp_config()
l3o_222 = VppGbpSubnet(
- self, rd1, "10.222.0.0", 24,
+ self,
+ rd1,
+ "10.222.0.0",
+ 24,
# note: this a "regular" l3out subnet (not connected)
VppEnum.vl_api_gbp_subnet_type_t.GBP_API_SUBNET_L3_OUT,
- sclass=4222)
+ sclass=4222,
+ )
l3o_222.add_vpp_config()
#
# ping between hosts in local and remote external subnets
# dropped without a contract
#
- p = (Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst="10.222.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst="10.222.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_assert_no_replies(self.pg0, p * 1)
@@ -5839,26 +7082,37 @@ class TestGBP(VppTestCase):
# Add contracts ext-nets for 220 -> 222
#
c4 = VppGbpContract(
- self, 55, 4220, 4222, acl.acl_index,
- [VppGbpContractRule(
- VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
- VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- []),
+ self,
+ 55,
+ 4220,
+ 4222,
+ acl.acl_index,
+ [
+ VppGbpContractRule(
+ VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
+ VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
+ [],
+ ),
VppGbpContractRule(
VppEnum.vl_api_gbp_rule_action_t.GBP_API_RULE_PERMIT,
VppEnum.vl_api_gbp_hash_mode_t.GBP_API_HASH_MODE_SRC_IP,
- [])],
- [ETH_P_IP, ETH_P_IPV6])
+ [],
+ ),
+ ],
+ [ETH_P_IP, ETH_P_IPV6],
+ )
c4.add_vpp_config()
#
# ping from host in local to remote external subnets
#
- p = (Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac)) /
- Dot1Q(vlan=100) /
- IP(src="10.220.0.1", dst="10.222.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.vlan_100.remote_mac, dst=str(self.router_mac))
+ / Dot1Q(vlan=100)
+ / IP(src="10.220.0.1", dst="10.222.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * 3, self.pg7)
@@ -5885,14 +7139,16 @@ class TestGBP(VppTestCase):
# ping from host in remote to local external subnets
# there's no contract for this, but the A bit is set.
#
- p = (Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=445, gpid=4222, flags=0x88, gpflags='A') /
- Ether(src=self.pg0.remote_mac, dst=str(self.router_mac)) /
- IP(src="10.222.0.1", dst="10.220.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=445, gpid=4222, flags=0x88, gpflags="A")
+ / Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src="10.222.0.1", dst="10.220.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg7, p * 3, self.pg0)
self.assertFalse(find_gbp_endpoint(self, ip="10.222.0.1"))
@@ -5901,14 +7157,16 @@ class TestGBP(VppTestCase):
# ping from host in remote to remote external subnets
# this is dropped by reflection check.
#
- p = (Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac) /
- IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4) /
- UDP(sport=1234, dport=48879) /
- VXLAN(vni=445, gpid=4222, flags=0x88, gpflags='A') /
- Ether(src=self.pg0.remote_mac, dst=str(self.router_mac)) /
- IP(src="10.222.0.1", dst="10.222.0.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg7.remote_mac, dst=self.pg7.local_mac)
+ / IP(src=self.pg7.remote_ip4, dst=self.pg7.local_ip4)
+ / UDP(sport=1234, dport=48879)
+ / VXLAN(vni=445, gpid=4222, flags=0x88, gpflags="A")
+ / Ether(src=self.pg0.remote_mac, dst=str(self.router_mac))
+ / IP(src="10.222.0.1", dst="10.222.0.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_assert_no_replies(self.pg7, p * 3)
@@ -5922,5 +7180,5 @@ class TestGBP(VppTestCase):
self.wait_for_ep_timeout(sw_if_index=rep.itf.sw_if_index, ip=rep.ip4)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/extras/deprecated/vnet/vxlan-gbp/test_vxlan_gbp.py b/extras/deprecated/vnet/vxlan-gbp/test_vxlan_gbp.py
index f332aced7d8..1d64937b6dd 100644
--- a/extras/deprecated/vnet/vxlan-gbp/test_vxlan_gbp.py
+++ b/extras/deprecated/vnet/vxlan-gbp/test_vxlan_gbp.py
@@ -16,37 +16,43 @@ from vpp_ip import INVALID_INDEX
class TestVxlanGbp(VppTestCase):
- """ VXLAN GBP Test Case """
+ """VXLAN GBP Test Case"""
@property
def frame_request(self):
- """ Ethernet frame modeling a generic request """
- return (Ether(src='00:00:00:00:00:01', dst='00:00:00:00:00:02') /
- IP(src='1.2.3.4', dst='4.3.2.1') /
- UDP(sport=10000, dport=20000) /
- Raw(b'\xa5' * 100))
+ """Ethernet frame modeling a generic request"""
+ return (
+ Ether(src="00:00:00:00:00:01", dst="00:00:00:00:00:02")
+ / IP(src="1.2.3.4", dst="4.3.2.1")
+ / UDP(sport=10000, dport=20000)
+ / Raw(b"\xa5" * 100)
+ )
@property
def frame_reply(self):
- """ Ethernet frame modeling a generic reply """
- return (Ether(src='00:00:00:00:00:02', dst='00:00:00:00:00:01') /
- IP(src='4.3.2.1', dst='1.2.3.4') /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 100))
+ """Ethernet frame modeling a generic reply"""
+ return (
+ Ether(src="00:00:00:00:00:02", dst="00:00:00:00:00:01")
+ / IP(src="4.3.2.1", dst="1.2.3.4")
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 100)
+ )
def encapsulate(self, pkt, vni):
"""
Encapsulate the original payload frame by adding VXLAN GBP header with
its UDP, IP and Ethernet fields
"""
- return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=self.dport, dport=self.dport, chksum=0) /
- VXLAN(vni=vni, flags=self.flags, gpflags=self.gpflags,
- gpid=self.sclass) / pkt)
+ return (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ / VXLAN(vni=vni, flags=self.flags, gpflags=self.gpflags, gpid=self.sclass)
+ / pkt
+ )
def ip_range(self, start, end):
- """ range of remote ip's """
+ """range of remote ip's"""
return ip4_range(self.pg0.remote_ip4, start, end)
def decapsulate(self, pkt):
@@ -54,7 +60,7 @@ class TestVxlanGbp(VppTestCase):
Decapsulate the original payload frame by removing VXLAN header
"""
# check if is set G and I flag
- self.assertEqual(pkt[VXLAN].flags, int('0x88', 16))
+ self.assertEqual(pkt[VXLAN].flags, int("0x88", 16))
return pkt[VXLAN].payload
# Method for checking VXLAN GBP encapsulation.
@@ -94,28 +100,28 @@ class TestVxlanGbp(VppTestCase):
ip_range_start = 10
ip_range_end = ip_range_start + n_ucast_tunnels
next_hop_address = cls.pg0.remote_ip4
- for dest_ip4 in ip4_range(cls.pg0.remote_ip4,
- ip_range_start,
- ip_range_end):
+ for dest_ip4 in ip4_range(cls.pg0.remote_ip4, ip_range_start, ip_range_end):
# add host route so dest_ip4 will not be resolved
- rip = VppIpRoute(cls, dest_ip4, 32,
- [VppRoutePath(next_hop_address,
- INVALID_INDEX)],
- register=False)
+ rip = VppIpRoute(
+ cls,
+ dest_ip4,
+ 32,
+ [VppRoutePath(next_hop_address, INVALID_INDEX)],
+ register=False,
+ )
rip.add_vpp_config()
r = cls.vapi.vxlan_gbp_tunnel_add_del(
tunnel={
- 'src': cls.pg0.local_ip4,
- 'dst': dest_ip4,
- 'vni': vni,
- 'instance': INVALID_INDEX,
- 'mcast_sw_if_index': INVALID_INDEX,
- 'mode': 1,
+ "src": cls.pg0.local_ip4,
+ "dst": dest_ip4,
+ "vni": vni,
+ "instance": INVALID_INDEX,
+ "mcast_sw_if_index": INVALID_INDEX,
+ "mode": 1,
},
- is_add=1
+ is_add=1,
)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=vni)
+ cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, bd_id=vni)
# Class method to start the VXLAN GBP test case.
# Overrides setUpClass method in VppTestCase class.
@@ -146,33 +152,33 @@ class TestVxlanGbp(VppTestCase):
# Create VXLAN GBP VTEP on VPP pg0, and put vxlan_gbp_tunnel0 and
# pg1 into BD.
cls.single_tunnel_bd = 1
- cls.single_tunnel_vni = 0xabcde
+ cls.single_tunnel_vni = 0xABCDE
r = cls.vapi.vxlan_gbp_tunnel_add_del(
tunnel={
- 'src': cls.pg0.local_ip4,
- 'dst': cls.pg0.remote_ip4,
- 'vni': cls.single_tunnel_vni,
- 'instance': INVALID_INDEX,
- 'mcast_sw_if_index': INVALID_INDEX,
- 'mode': 1,
+ "src": cls.pg0.local_ip4,
+ "dst": cls.pg0.remote_ip4,
+ "vni": cls.single_tunnel_vni,
+ "instance": INVALID_INDEX,
+ "mcast_sw_if_index": INVALID_INDEX,
+ "mode": 1,
},
- is_add=1
+ is_add=1,
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=r.sw_if_index, bd_id=cls.single_tunnel_bd
)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=cls.single_tunnel_bd)
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg1.sw_if_index,
- bd_id=cls.single_tunnel_bd)
+ rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.single_tunnel_bd
+ )
# Setup vni 2 to test multicast flooding
cls.n_ucast_tunnels = 2
# Setup vni 3 to test unicast flooding
cls.ucast_flood_bd = 3
- cls.create_vxlan_gbp_flood_test_bd(cls.ucast_flood_bd,
- cls.n_ucast_tunnels)
+ cls.create_vxlan_gbp_flood_test_bd(cls.ucast_flood_bd, cls.n_ucast_tunnels)
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg3.sw_if_index,
- bd_id=cls.ucast_flood_bd)
+ rx_sw_if_index=cls.pg3.sw_if_index, bd_id=cls.ucast_flood_bd
+ )
except Exception:
super(TestVxlanGbp, cls).tearDownClass()
raise
@@ -182,7 +188,7 @@ class TestVxlanGbp(VppTestCase):
super(TestVxlanGbp, cls).tearDownClass()
def assert_eq_pkts(self, pkt1, pkt2):
- """ Verify the Ether, IP, UDP, payload are equal in both
+ """Verify the Ether, IP, UDP, payload are equal in both
packets
"""
self.assertEqual(pkt1[Ether].src, pkt2[Ether].src)
@@ -194,14 +200,17 @@ class TestVxlanGbp(VppTestCase):
self.assertEqual(pkt1[Raw], pkt2[Raw])
def test_decap(self):
- """ Decapsulation test
+ """Decapsulation test
Send encapsulated frames from pg0
Verify receipt of decapsulated frames on pg1
"""
- encapsulated_pkt = self.encapsulate(self.frame_request,
- self.single_tunnel_vni)
+ encapsulated_pkt = self.encapsulate(self.frame_request, self.single_tunnel_vni)
- self.pg0.add_stream([encapsulated_pkt, ])
+ self.pg0.add_stream(
+ [
+ encapsulated_pkt,
+ ]
+ )
self.pg1.enable_capture()
@@ -214,7 +223,7 @@ class TestVxlanGbp(VppTestCase):
self.assert_eq_pkts(pkt, self.frame_request)
def test_encap(self):
- """ Encapsulation test
+ """Encapsulation test
Send frames from pg1
Verify receipt of encapsulated frames on pg0
"""
@@ -233,7 +242,7 @@ class TestVxlanGbp(VppTestCase):
self.assert_eq_pkts(payload, self.frame_reply)
def test_ucast_flood(self):
- """ Unicast flood test
+ """Unicast flood test
Send frames from pg3
Verify receipt of encapsulated frames on pg0
"""
@@ -251,16 +260,18 @@ class TestVxlanGbp(VppTestCase):
self.assert_eq_pkts(payload, self.frame_reply)
def test_encap_big_packet(self):
- """ Encapsulation test send big frame from pg1
+ """Encapsulation test send big frame from pg1
Verify receipt of encapsulated frames on pg0
"""
self.vapi.sw_interface_set_mtu(self.pg0.sw_if_index, [1500, 0, 0, 0])
- frame = (Ether(src='00:00:00:00:00:02', dst='00:00:00:00:00:01') /
- IP(src='4.3.2.1', dst='1.2.3.4') /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 1450))
+ frame = (
+ Ether(src="00:00:00:00:00:02", dst="00:00:00:00:00:01")
+ / IP(src="4.3.2.1", dst="1.2.3.4")
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 1450)
+ )
self.pg1.add_stream([frame])
@@ -276,9 +287,9 @@ class TestVxlanGbp(VppTestCase):
payload = self.decapsulate(pkt)
self.assert_eq_pkts(payload, frame)
-# Method to define VPP actions before tear down of the test case.
-# Overrides tearDown method in VppTestCase class.
-# @param self The object pointer.
+ # Method to define VPP actions before tear down of the test case.
+ # Overrides tearDown method in VppTestCase class.
+ # @param self The object pointer.
def tearDown(self):
super(TestVxlanGbp, self).tearDown()
@@ -289,5 +300,5 @@ class TestVxlanGbp(VppTestCase):
self.logger.info(self.vapi.cli("show error"))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/extras/deprecated/vnet/vxlan-gbp/vpp_vxlan_gbp_tunnel.py b/extras/deprecated/vnet/vxlan-gbp/vpp_vxlan_gbp_tunnel.py
index 0898bd9f810..1b6b4e731ca 100644
--- a/extras/deprecated/vnet/vxlan-gbp/vpp_vxlan_gbp_tunnel.py
+++ b/extras/deprecated/vnet/vxlan-gbp/vpp_vxlan_gbp_tunnel.py
@@ -1,17 +1,18 @@
-
from vpp_interface import VppInterface
from vpp_papi import VppEnum
-INDEX_INVALID = 0xffffffff
+INDEX_INVALID = 0xFFFFFFFF
def find_vxlan_gbp_tunnel(test, src, dst, vni):
ts = test.vapi.vxlan_gbp_tunnel_dump(INDEX_INVALID)
for t in ts:
- if src == str(t.tunnel.src) and \
- dst == str(t.tunnel.dst) and \
- t.tunnel.vni == vni:
+ if (
+ src == str(t.tunnel.src)
+ and dst == str(t.tunnel.dst)
+ and t.tunnel.vni == vni
+ ):
return t.tunnel.sw_if_index
return INDEX_INVALID
@@ -21,9 +22,19 @@ class VppVxlanGbpTunnel(VppInterface):
VPP VXLAN GBP interface
"""
- def __init__(self, test, src, dst, vni, mcast_itf=None, mode=None,
- is_ipv6=None, encap_table_id=None, instance=0xffffffff):
- """ Create VXLAN-GBP Tunnel interface """
+ def __init__(
+ self,
+ test,
+ src,
+ dst,
+ vni,
+ mcast_itf=None,
+ mode=None,
+ is_ipv6=None,
+ encap_table_id=None,
+ instance=0xFFFFFFFF,
+ ):
+ """Create VXLAN-GBP Tunnel interface"""
super(VppVxlanGbpTunnel, self).__init__(test)
self.src = src
self.dst = dst
@@ -33,21 +44,23 @@ class VppVxlanGbpTunnel(VppInterface):
self.encap_table_id = encap_table_id
self.instance = instance
if not mode:
- self.mode = (VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.
- VXLAN_GBP_API_TUNNEL_MODE_L2)
+ self.mode = (
+ VppEnum.vl_api_vxlan_gbp_api_tunnel_mode_t.VXLAN_GBP_API_TUNNEL_MODE_L2
+ )
else:
self.mode = mode
def encode(self):
return {
- 'src': self.src,
- 'dst': self.dst,
- 'mode': self.mode,
- 'vni': self.vni,
- 'mcast_sw_if_index': self.mcast_itf.sw_if_index
- if self.mcast_itf else INDEX_INVALID,
- 'encap_table_id': self.encap_table_id,
- 'instance': self.instance,
+ "src": self.src,
+ "dst": self.dst,
+ "mode": self.mode,
+ "vni": self.vni,
+ "mcast_sw_if_index": self.mcast_itf.sw_if_index
+ if self.mcast_itf
+ else INDEX_INVALID,
+ "encap_table_id": self.encap_table_id,
+ "instance": self.instance,
}
def add_vpp_config(self):
@@ -65,11 +78,14 @@ class VppVxlanGbpTunnel(VppInterface):
)
def query_vpp_config(self):
- return (INDEX_INVALID != find_vxlan_gbp_tunnel(self._test,
- self.src,
- self.dst,
- self.vni))
+ return INDEX_INVALID != find_vxlan_gbp_tunnel(
+ self._test, self.src, self.dst, self.vni
+ )
def object_id(self):
- return "vxlan-gbp-%d-%d-%s-%s" % (self.sw_if_index, self.vni,
- self.src, self.dst)
+ return "vxlan-gbp-%d-%d-%s-%s" % (
+ self.sw_if_index,
+ self.vni,
+ self.src,
+ self.dst,
+ )
diff --git a/extras/deprecated/vom/test/test_vom.py b/extras/deprecated/vom/test/test_vom.py
index a77b935263d..51944296233 100644
--- a/extras/deprecated/vom/test/test_vom.py
+++ b/extras/deprecated/vom/test/test_vom.py
@@ -4,13 +4,12 @@
import unittest
import os
import signal
-from framework import VppTestCase, running_extended_tests, \
- VppTestRunner, Worker
+from framework import VppTestCase, running_extended_tests, VppTestRunner, Worker
@unittest.skipUnless(running_extended_tests, "part of extended tests")
class VOMTestCase(VppTestCase):
- """ VPP Object Model Test """
+ """VPP Object Model Test"""
@classmethod
def setUpClass(cls):
@@ -21,14 +20,14 @@ class VOMTestCase(VppTestCase):
super(VOMTestCase, cls).tearDownClass()
def test_vom_cpp(self):
- """ run C++ VOM tests """
+ """run C++ VOM tests"""
var = "TEST_BR"
built_root = os.getenv(var, None)
- self.assertIsNotNone(built_root,
- "Environment variable `%s' not set" % var)
+ self.assertIsNotNone(built_root, "Environment variable `%s' not set" % var)
executable = "%s/vom_test/vom_test" % built_root
- worker = Worker([executable, "vpp object model",
- self.get_api_segment_prefix()], self.logger)
+ worker = Worker(
+ [executable, "vpp object model", self.get_api_segment_prefix()], self.logger
+ )
worker.start()
timeout = 120
worker.join(timeout)
@@ -37,17 +36,15 @@ class VOMTestCase(VppTestCase):
if worker.result is None:
try:
error = True
- self.logger.error(
- "Timeout! Worker did not finish in %ss" % timeout)
+ self.logger.error("Timeout! Worker did not finish in %ss" % timeout)
os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM)
worker.join()
except:
raise Exception("Couldn't kill worker-spawned process")
if error:
- raise Exception(
- "Timeout! Worker did not finish in %ss" % timeout)
+ raise Exception("Timeout! Worker did not finish in %ss" % timeout)
self.assert_equal(worker.result, 0, "Binary test return code")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/extras/scripts/crcchecker.py b/extras/scripts/crcchecker.py
index f3021c3c8b6..01cb02523d0 100755
--- a/extras/scripts/crcchecker.py
+++ b/extras/scripts/crcchecker.py
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
-'''
+"""
crcchecker is a tool to used to enforce that .api messages do not change.
API files with a semantic version < 1.0.0 are ignored.
-'''
+"""
import sys
import os
@@ -14,67 +14,75 @@ from subprocess import run, PIPE, check_output, CalledProcessError
# pylint: disable=subprocess-run-check
-ROOTDIR = os.path.dirname(os.path.realpath(__file__)) + '/../..'
-APIGENBIN = f'{ROOTDIR}/src/tools/vppapigen/vppapigen.py'
+ROOTDIR = os.path.dirname(os.path.realpath(__file__)) + "/../.."
+APIGENBIN = f"{ROOTDIR}/src/tools/vppapigen/vppapigen.py"
def crc_from_apigen(revision, filename):
- '''Runs vppapigen with crc plugin returning a JSON object with CRCs for
- all APIs in filename'''
+ """Runs vppapigen with crc plugin returning a JSON object with CRCs for
+ all APIs in filename"""
if not revision and not os.path.isfile(filename):
- print(f'skipping: {filename}', file=sys.stderr)
+ print(f"skipping: {filename}", file=sys.stderr)
# Return <class 'set'> instead of <class 'dict'>
return {-1}
if revision:
- apigen = (f'{APIGENBIN} --git-revision {revision} --includedir src '
- f'--input {filename} CRC')
+ apigen = (
+ f"{APIGENBIN} --git-revision {revision} --includedir src "
+ f"--input {filename} CRC"
+ )
else:
- apigen = (f'{APIGENBIN} --includedir src --input {filename} CRC')
+ apigen = f"{APIGENBIN} --includedir src --input {filename} CRC"
returncode = run(apigen.split(), stdout=PIPE, stderr=PIPE)
if returncode.returncode == 2: # No such file
- print(f'skipping: {revision}:{filename} {returncode}', file=sys.stderr)
+ print(f"skipping: {revision}:{filename} {returncode}", file=sys.stderr)
return {}
if returncode.returncode != 0:
- print(f'vppapigen failed for {revision}:{filename} with '
- 'command\n {apigen}\n error: {rv}',
- returncode.stderr.decode('ascii'), file=sys.stderr)
+ print(
+ f"vppapigen failed for {revision}:{filename} with "
+ "command\n {apigen}\n error: {rv}",
+ returncode.stderr.decode("ascii"),
+ file=sys.stderr,
+ )
sys.exit(-2)
return json.loads(returncode.stdout)
def dict_compare(dict1, dict2):
- '''Compare two dictionaries returning added, removed, modified
- and equal entries'''
+ """Compare two dictionaries returning added, removed, modified
+ and equal entries"""
d1_keys = set(dict1.keys())
d2_keys = set(dict2.keys())
intersect_keys = d1_keys.intersection(d2_keys)
added = d1_keys - d2_keys
removed = d2_keys - d1_keys
- modified = {o: (dict1[o], dict2[o]) for o in intersect_keys
- if dict1[o]['crc'] != dict2[o]['crc']}
+ modified = {
+ o: (dict1[o], dict2[o])
+ for o in intersect_keys
+ if dict1[o]["crc"] != dict2[o]["crc"]
+ }
same = set(o for o in intersect_keys if dict1[o] == dict2[o])
return added, removed, modified, same
def filelist_from_git_ls():
- '''Returns a list of all api files in the git repository'''
+ """Returns a list of all api files in the git repository"""
filelist = []
- git_ls = 'git ls-files *.api'
+ git_ls = "git ls-files *.api"
returncode = run(git_ls.split(), stdout=PIPE, stderr=PIPE)
if returncode.returncode != 0:
sys.exit(returncode.returncode)
- for line in returncode.stdout.decode('ascii').split('\n'):
+ for line in returncode.stdout.decode("ascii").split("\n"):
if line:
filelist.append(line)
return filelist
def is_uncommitted_changes():
- '''Returns true if there are uncommitted changes in the repo'''
- git_status = 'git status --porcelain -uno'
+ """Returns true if there are uncommitted changes in the repo"""
+ git_status = "git status --porcelain -uno"
returncode = run(git_status.split(), stdout=PIPE, stderr=PIPE)
if returncode.returncode != 0:
sys.exit(returncode.returncode)
@@ -85,27 +93,29 @@ def is_uncommitted_changes():
def filelist_from_git_grep(filename):
- '''Returns a list of api files that this <filename> api files imports.'''
+ """Returns a list of api files that this <filename> api files imports."""
filelist = []
try:
- returncode = check_output(f'git grep -e "import .*{filename}"'
- ' -- *.api',
- shell=True)
+ returncode = check_output(
+ f'git grep -e "import .*{filename}"' " -- *.api", shell=True
+ )
except CalledProcessError:
return []
- for line in returncode.decode('ascii').split('\n'):
+ for line in returncode.decode("ascii").split("\n"):
if line:
- filename, _ = line.split(':')
+ filename, _ = line.split(":")
filelist.append(filename)
return filelist
def filelist_from_patchset(pattern):
- '''Returns list of api files in changeset and the list of api
- files they import.'''
+ """Returns list of api files in changeset and the list of api
+ files they import."""
filelist = []
- git_cmd = ('((git diff HEAD~1.. --name-only;git ls-files -m) | '
- 'sort -u | grep "\\.api$")')
+ git_cmd = (
+ "((git diff HEAD~1.. --name-only;git ls-files -m) | "
+ 'sort -u | grep "\\.api$")'
+ )
try:
res = check_output(git_cmd, shell=True)
except CalledProcessError:
@@ -113,7 +123,7 @@ def filelist_from_patchset(pattern):
# Check for dependencies (imports)
imported_files = []
- for line in res.decode('ascii').split('\n'):
+ for line in res.decode("ascii").split("\n"):
if not line:
continue
if not re.search(pattern, line):
@@ -126,88 +136,91 @@ def filelist_from_patchset(pattern):
def is_deprecated(message):
- '''Given a message, return True if message is deprecated'''
- if 'options' in message:
- if 'deprecated' in message['options']:
+ """Given a message, return True if message is deprecated"""
+ if "options" in message:
+ if "deprecated" in message["options"]:
return True
# recognize the deprecated format
- if 'status' in message['options'] and \
- message['options']['status'] == 'deprecated':
+ if (
+ "status" in message["options"]
+ and message["options"]["status"] == "deprecated"
+ ):
print("WARNING: please use 'option deprecated;'")
return True
return False
def is_in_progress(message):
- '''Given a message, return True if message is marked as in_progress'''
- if 'options' in message:
- if 'in_progress' in message['options']:
+ """Given a message, return True if message is marked as in_progress"""
+ if "options" in message:
+ if "in_progress" in message["options"]:
return True
# recognize the deprecated format
- if 'status' in message['options'] and \
- message['options']['status'] == 'in_progress':
+ if (
+ "status" in message["options"]
+ and message["options"]["status"] == "in_progress"
+ ):
print("WARNING: please use 'option in_progress;'")
return True
return False
def report(new, old):
- '''Given a dictionary of new crcs and old crcs, print all the
+ """Given a dictionary of new crcs and old crcs, print all the
added, removed, modified, in-progress, deprecated messages.
- Return the number of backwards incompatible changes made.'''
+ Return the number of backwards incompatible changes made."""
# pylint: disable=too-many-branches
- new.pop('_version', None)
- old.pop('_version', None)
+ new.pop("_version", None)
+ old.pop("_version", None)
added, removed, modified, _ = dict_compare(new, old)
backwards_incompatible = 0
# print the full list of in-progress messages
# they should eventually either disappear of become supported
for k in new.keys():
- newversion = int(new[k]['version'])
+ newversion = int(new[k]["version"])
if newversion == 0 or is_in_progress(new[k]):
- print(f'in-progress: {k}')
+ print(f"in-progress: {k}")
for k in added:
- print(f'added: {k}')
+ print(f"added: {k}")
for k in removed:
- oldversion = int(old[k]['version'])
- if oldversion > 0 and not is_deprecated(old[k]) and not \
- is_in_progress(old[k]):
+ oldversion = int(old[k]["version"])
+ if oldversion > 0 and not is_deprecated(old[k]) and not is_in_progress(old[k]):
backwards_incompatible += 1
- print(f'removed: ** {k}')
+ print(f"removed: ** {k}")
else:
- print(f'removed: {k}')
+ print(f"removed: {k}")
for k in modified.keys():
- oldversion = int(old[k]['version'])
- newversion = int(new[k]['version'])
+ oldversion = int(old[k]["version"])
+ newversion = int(new[k]["version"])
if oldversion > 0 and not is_in_progress(old[k]):
backwards_incompatible += 1
- print(f'modified: ** {k}')
+ print(f"modified: ** {k}")
else:
- print(f'modified: {k}')
+ print(f"modified: {k}")
# check which messages are still there but were marked for deprecation
for k in new.keys():
- newversion = int(new[k]['version'])
+ newversion = int(new[k]["version"])
if newversion > 0 and is_deprecated(new[k]):
if k in old:
if not is_deprecated(old[k]):
- print(f'deprecated: {k}')
+ print(f"deprecated: {k}")
else:
- print(f'added+deprecated: {k}')
+ print(f"added+deprecated: {k}")
return backwards_incompatible
def check_patchset():
- '''Compare the changes to API messages in this changeset.
+ """Compare the changes to API messages in this changeset.
Ignores API files with version < 1.0.0.
Only considers API files located under the src directory in the repo.
- '''
- files = filelist_from_patchset('^src/')
- revision = 'HEAD~1'
+ """
+ files = filelist_from_patchset("^src/")
+ revision = "HEAD~1"
oldcrcs = {}
newcrcs = {}
@@ -216,7 +229,7 @@ def check_patchset():
_ = crc_from_apigen(None, filename)
# Ignore removed files
if isinstance(_, set) == 0:
- if isinstance(_, set) == 0 and _['_version']['major'] == '0':
+ if isinstance(_, set) == 0 and _["_version"]["major"] == "0":
continue
newcrcs.update(_)
@@ -225,27 +238,31 @@ def check_patchset():
backwards_incompatible = report(newcrcs, oldcrcs)
if backwards_incompatible:
# alert on changing production API
- print("crcchecker: Changing production APIs in an incompatible way",
- file=sys.stderr)
+ print(
+ "crcchecker: Changing production APIs in an incompatible way",
+ file=sys.stderr,
+ )
sys.exit(-1)
else:
- print('*' * 67)
- print('* VPP CHECKAPI SUCCESSFULLY COMPLETED')
- print('*' * 67)
+ print("*" * 67)
+ print("* VPP CHECKAPI SUCCESSFULLY COMPLETED")
+ print("*" * 67)
def main():
- '''Main entry point.'''
- parser = argparse.ArgumentParser(description='VPP CRC checker.')
- parser.add_argument('--git-revision',
- help='Git revision to compare against')
- parser.add_argument('--dump-manifest', action='store_true',
- help='Dump CRC for all messages')
- parser.add_argument('--check-patchset', action='store_true',
- help='Check patchset for backwards incompatbile changes')
- parser.add_argument('files', nargs='*')
- parser.add_argument('--diff', help='Files to compare (on filesystem)',
- nargs=2)
+ """Main entry point."""
+ parser = argparse.ArgumentParser(description="VPP CRC checker.")
+ parser.add_argument("--git-revision", help="Git revision to compare against")
+ parser.add_argument(
+ "--dump-manifest", action="store_true", help="Dump CRC for all messages"
+ )
+ parser.add_argument(
+ "--check-patchset",
+ action="store_true",
+ help="Check patchset for backwards incompatbile changes",
+ )
+ parser.add_argument("files", nargs="*")
+ parser.add_argument("--diff", help="Files to compare (on filesystem)", nargs=2)
args = parser.parse_args()
@@ -267,17 +284,16 @@ def main():
for filename in files:
crcs.update(crc_from_apigen(args.git_revision, filename))
for k, value in crcs.items():
- print(f'{k}: {value}')
+ print(f"{k}: {value}")
sys.exit(0)
# Find changes between current patchset and given revision (previous)
if args.check_patchset:
if args.git_revision:
- print('Argument git-revision ignored', file=sys.stderr)
+ print("Argument git-revision ignored", file=sys.stderr)
# Check there are no uncomitted changes
if is_uncommitted_changes():
- print('Please stash or commit changes in workspace',
- file=sys.stderr)
+ print("Please stash or commit changes in workspace", file=sys.stderr)
sys.exit(-1)
check_patchset()
sys.exit(0)
@@ -286,7 +302,7 @@ def main():
# Find changes between a given file and a revision
files = args.files if args.files else filelist_from_git_ls()
- revision = args.git_revision if args.git_revision else 'HEAD~1'
+ revision = args.git_revision if args.git_revision else "HEAD~1"
oldcrcs = {}
newcrcs = {}
@@ -299,13 +315,16 @@ def main():
if args.check_patchset:
if backwards_incompatible:
# alert on changing production API
- print("crcchecker: Changing production APIs in an incompatible way", file=sys.stderr)
+ print(
+ "crcchecker: Changing production APIs in an incompatible way",
+ file=sys.stderr,
+ )
sys.exit(-1)
else:
- print('*' * 67)
- print('* VPP CHECKAPI SUCCESSFULLY COMPLETED')
- print('*' * 67)
+ print("*" * 67)
+ print("* VPP CHECKAPI SUCCESSFULLY COMPLETED")
+ print("*" * 67)
-if __name__ == '__main__':
+if __name__ == "__main__":
main()
diff --git a/extras/scripts/list_api_changes.py b/extras/scripts/list_api_changes.py
index ac8cf477810..7433f542aaa 100755
--- a/extras/scripts/list_api_changes.py
+++ b/extras/scripts/list_api_changes.py
@@ -4,21 +4,21 @@ import fnmatch
import os
import subprocess
-starttag = 'v19.08-rc0'
-endtag = 'HEAD'
+starttag = "v19.08-rc0"
+endtag = "HEAD"
emit_md = True
apifiles = []
-for root, dirnames, filenames in os.walk('.'):
- for filename in fnmatch.filter(filenames, '*.api'):
+for root, dirnames, filenames in os.walk("."):
+ for filename in fnmatch.filter(filenames, "*.api"):
apifiles.append(os.path.join(root, filename))
for f in apifiles:
- commits = subprocess.check_output(['git', 'log',
- '--oneline', starttag + '..' + endtag,
- f])
+ commits = subprocess.check_output(
+ ["git", "log", "--oneline", starttag + ".." + endtag, f]
+ )
if commits:
- if f[0:2] == './':
+ if f[0:2] == "./":
f = f[2:]
if emit_md:
print("| @c %s ||" % f)
@@ -27,9 +27,10 @@ for f in apifiles:
parts = line.strip().split()
commit = parts[0]
message = b" ".join(parts[1:]).decode().replace("|", r"\|")
- print("| [%s](https://gerrit.fd.io/r/gitweb?"
- "p=vpp.git;a=commit;h=%s) | %s |" % (
- commit, commit, message))
+ print(
+ "| [%s](https://gerrit.fd.io/r/gitweb?"
+ "p=vpp.git;a=commit;h=%s) | %s |" % (commit, commit, message)
+ )
print()
else:
print(f)
diff --git a/extras/vpp_config/scripts/dpdk-devbind.py b/extras/vpp_config/scripts/dpdk-devbind.py
index 80edb3b9eea..140e4346894 100755
--- a/extras/vpp_config/scripts/dpdk-devbind.py
+++ b/extras/vpp_config/scripts/dpdk-devbind.py
@@ -56,9 +56,10 @@ args = []
def usage():
- '''Print usage information for the program'''
+ """Print usage information for the program"""
argv0 = basename(sys.argv[0])
- print("""
+ print(
+ """
Usage:
------
@@ -115,33 +116,40 @@ To unbind 0000:01:00.0 from using any driver
To bind 0000:02:00.0 and 0000:02:00.1 to the ixgbe kernel driver
%(argv0)s -b ixgbe 02:00.0 02:00.1
- """ % locals()) # replace items from local variables
+ """
+ % locals()
+ ) # replace items from local variables
# This is roughly compatible with check_output function in subprocess module
# which is only available in python 2.7.
def check_output(args, stderr=None):
- '''Run a command and capture its output'''
- return subprocess.Popen(args, stdout=subprocess.PIPE,
- stderr=stderr).communicate()[0]
+ """Run a command and capture its output"""
+ return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr).communicate()[
+ 0
+ ]
def find_module(mod):
- '''find the .ko file for kernel module named mod.
+ """find the .ko file for kernel module named mod.
Searches the $RTE_SDK/$RTE_TARGET directory, the kernel
modules directory and finally under the parent directory of
- the script '''
+ the script"""
# check $RTE_SDK/$RTE_TARGET directory
- if 'RTE_SDK' in os.environ and 'RTE_TARGET' in os.environ:
- path = "%s/%s/kmod/%s.ko" % (os.environ['RTE_SDK'],
- os.environ['RTE_TARGET'], mod)
+ if "RTE_SDK" in os.environ and "RTE_TARGET" in os.environ:
+ path = "%s/%s/kmod/%s.ko" % (
+ os.environ["RTE_SDK"],
+ os.environ["RTE_TARGET"],
+ mod,
+ )
if exists(path):
return path
# check using depmod
try:
- depmod_out = check_output(["modinfo", "-n", mod],
- stderr=subprocess.STDOUT).lower()
+ depmod_out = check_output(
+ ["modinfo", "-n", mod], stderr=subprocess.STDOUT
+ ).lower()
if "error" not in depmod_out:
path = depmod_out.strip()
if exists(path):
@@ -151,7 +159,7 @@ def find_module(mod):
# check for a copy based off current path
tools_dir = dirname(abspath(sys.argv[0]))
- if (tools_dir.endswith("tools")):
+ if tools_dir.endswith("tools"):
base_dir = dirname(tools_dir)
find_out = check_output(["find", base_dir, "-name", mod + ".ko"])
if len(find_out) > 0: # something matched
@@ -161,7 +169,7 @@ def find_module(mod):
def check_modules():
- '''Checks that igb_uio is loaded'''
+ """Checks that igb_uio is loaded"""
global dpdk_drivers
# list of supported modules
@@ -170,20 +178,21 @@ def check_modules():
# first check if module is loaded
try:
# Get list of sysfs modules (both built-in and dynamically loaded)
- sysfs_path = '/sys/module/'
+ sysfs_path = "/sys/module/"
# Get the list of directories in sysfs_path
- sysfs_mods = [os.path.join(sysfs_path, o) for o
- in os.listdir(sysfs_path)
- if os.path.isdir(os.path.join(sysfs_path, o))]
+ sysfs_mods = [
+ os.path.join(sysfs_path, o)
+ for o in os.listdir(sysfs_path)
+ if os.path.isdir(os.path.join(sysfs_path, o))
+ ]
# Extract the last element of '/sys/module/abc' in the array
- sysfs_mods = [a.split('/')[-1] for a in sysfs_mods]
+ sysfs_mods = [a.split("/")[-1] for a in sysfs_mods]
# special case for vfio_pci (module is named vfio-pci,
# but its .ko is named vfio_pci)
- sysfs_mods = map(lambda a:
- a if a != 'vfio_pci' else 'vfio-pci', sysfs_mods)
+ sysfs_mods = map(lambda a: a if a != "vfio_pci" else "vfio-pci", sysfs_mods)
for mod in mods:
if mod["Name"] in sysfs_mods:
@@ -204,12 +213,12 @@ def check_modules():
def has_driver(dev_id):
- '''return true if a device is assigned to a driver. False otherwise'''
+ """return true if a device is assigned to a driver. False otherwise"""
return "Driver_str" in devices[dev_id]
def get_pci_device_details(dev_id):
- '''This function gets additional details for a PCI device'''
+ """This function gets additional details for a PCI device"""
device = {}
extra_info = check_output(["lspci", "-vmmks", dev_id]).splitlines()
@@ -225,8 +234,7 @@ def get_pci_device_details(dev_id):
device["Interface"] = ""
for base, dirs, _ in os.walk("/sys/bus/pci/devices/%s/" % dev_id):
if "net" in dirs:
- device["Interface"] = \
- ",".join(os.listdir(os.path.join(base, "net")))
+ device["Interface"] = ",".join(os.listdir(os.path.join(base, "net")))
break
# check if a port is used for ssh connection
device["Ssh_if"] = False
@@ -236,9 +244,9 @@ def get_pci_device_details(dev_id):
def get_nic_details():
- '''This function populates the "devices" dictionary. The keys used are
+ """This function populates the "devices" dictionary. The keys used are
the pci addresses (domain:bus:slot.func). The values are themselves
- dictionaries - one for each NIC.'''
+ dictionaries - one for each NIC."""
global devices
global dpdk_drivers
@@ -249,7 +257,7 @@ def get_nic_details():
dev = {}
dev_lines = check_output(["lspci", "-Dvmmn"]).splitlines()
for dev_line in dev_lines:
- if (len(dev_line) == 0):
+ if len(dev_line) == 0:
if dev["Class"][0:2] == NETWORK_BASE_CLASS:
# convert device and vendor ids to numbers, then add to global
dev["Vendor"] = int(dev["Vendor"], 16)
@@ -265,12 +273,13 @@ def get_nic_details():
ssh_if = []
route = check_output(["ip", "-o", "route"])
# filter out all lines for 169.254 routes
- route = "\n".join(filter(lambda ln: not ln.startswith("169.254"),
- route.decode().splitlines()))
+ route = "\n".join(
+ filter(lambda ln: not ln.startswith("169.254"), route.decode().splitlines())
+ )
rt_info = route.split()
for i in range(len(rt_info) - 1):
if rt_info[i] == "dev":
- ssh_if.append(rt_info[i+1])
+ ssh_if.append(rt_info[i + 1])
# based on the basic info, get extended text details
for d in devices.keys():
@@ -288,8 +297,7 @@ def get_nic_details():
if "Module_str" in devices[d]:
for driver in dpdk_drivers:
if driver not in devices[d]["Module_str"]:
- devices[d]["Module_str"] = \
- devices[d]["Module_str"] + ",%s" % driver
+ devices[d]["Module_str"] = devices[d]["Module_str"] + ",%s" % driver
else:
devices[d]["Module_str"] = ",".join(dpdk_drivers)
@@ -302,9 +310,9 @@ def get_nic_details():
def get_crypto_details():
- '''This function populates the "devices" dictionary. The keys used are
+ """This function populates the "devices" dictionary. The keys used are
the pci addresses (domain:bus:slot.func). The values are themselves
- dictionaries - one for each NIC.'''
+ dictionaries - one for each NIC."""
global devices
global dpdk_drivers
@@ -315,8 +323,8 @@ def get_crypto_details():
dev = {}
dev_lines = check_output(["lspci", "-Dvmmn"]).splitlines()
for dev_line in dev_lines:
- if (len(dev_line) == 0):
- if (dev["Class"][0:2] == CRYPTO_BASE_CLASS):
+ if len(dev_line) == 0:
+ if dev["Class"][0:2] == CRYPTO_BASE_CLASS:
# convert device and vendor ids to numbers, then add to global
dev["Vendor"] = int(dev["Vendor"], 16)
dev["Device"] = int(dev["Device"], 16)
@@ -336,8 +344,7 @@ def get_crypto_details():
if "Module_str" in devices[d]:
for driver in dpdk_drivers:
if driver not in devices[d]["Module_str"]:
- devices[d]["Module_str"] = \
- devices[d]["Module_str"] + ",%s" % driver
+ devices[d]["Module_str"] = devices[d]["Module_str"] + ",%s" % driver
else:
devices[d]["Module_str"] = ",".join(dpdk_drivers)
@@ -350,9 +357,9 @@ def get_crypto_details():
def dev_id_from_dev_name(dev_name):
- '''Take a device "name" - a string passed in by user to identify a NIC
+ """Take a device "name" - a string passed in by user to identify a NIC
device, and determine the device id - i.e. the domain:bus:slot.func - for
- it, which can then be used to index into the devices array'''
+ it, which can then be used to index into the devices array"""
# check if it's already a suitable index
if dev_name in devices:
@@ -366,23 +373,29 @@ def dev_id_from_dev_name(dev_name):
if dev_name in devices[d]["Interface"].split(","):
return devices[d]["Slot"]
# if nothing else matches - error
- print("Unknown device: %s. "
- "Please specify device in \"bus:slot.func\" format" % dev_name)
+ print(
+ "Unknown device: %s. "
+ 'Please specify device in "bus:slot.func" format' % dev_name
+ )
sys.exit(1)
def unbind_one(dev_id, force):
- '''Unbind the device identified by "dev_id" from its current driver'''
+ """Unbind the device identified by "dev_id" from its current driver"""
dev = devices[dev_id]
if not has_driver(dev_id):
- print("%s %s %s is not currently managed by any driver\n" %
- (dev["Slot"], dev["Device_str"], dev["Interface"]))
+ print(
+ "%s %s %s is not currently managed by any driver\n"
+ % (dev["Slot"], dev["Device_str"], dev["Interface"])
+ )
return
# prevent us disconnecting ourselves
if dev["Ssh_if"] and not force:
- print("Routing table indicates that interface %s is active. "
- "Skipping unbind" % (dev_id))
+ print(
+ "Routing table indicates that interface %s is active. "
+ "Skipping unbind" % (dev_id)
+ )
return
# write to /sys to unbind
@@ -390,30 +403,30 @@ def unbind_one(dev_id, force):
try:
f = open(filename, "a")
except:
- print("Error: unbind failed for %s - Cannot open %s"
- % (dev_id, filename))
+ print("Error: unbind failed for %s - Cannot open %s" % (dev_id, filename))
sys.exit(1)
f.write(dev_id)
f.close()
def bind_one(dev_id, driver, force):
- '''Bind the device given by "dev_id" to the driver "driver". If the device
- is already bound to a different driver, it will be unbound first'''
+ """Bind the device given by "dev_id" to the driver "driver". If the device
+ is already bound to a different driver, it will be unbound first"""
dev = devices[dev_id]
saved_driver = None # used to rollback any unbind in case of failure
# prevent disconnection of our ssh session
if dev["Ssh_if"] and not force:
- print("Routing table indicates that interface %s is active. "
- "Not modifying" % (dev_id))
+ print(
+ "Routing table indicates that interface %s is active. "
+ "Not modifying" % (dev_id)
+ )
return
# unbind any existing drivers we don't want
if has_driver(dev_id):
if dev["Driver_str"] == driver:
- print("%s already bound to driver %s, skipping\n"
- % (dev_id, driver))
+ print("%s already bound to driver %s, skipping\n" % (dev_id, driver))
return
else:
saved_driver = dev["Driver_str"]
@@ -426,15 +439,16 @@ def bind_one(dev_id, driver, force):
try:
f = open(filename, "w")
except:
- print("Error: bind failed for %s - Cannot open %s"
- % (dev_id, filename))
+ print("Error: bind failed for %s - Cannot open %s" % (dev_id, filename))
return
try:
f.write("%04x %04x" % (dev["Vendor"], dev["Device"]))
f.close()
except:
- print("Error: bind failed for %s - Cannot write new PCI ID to "
- "driver %s" % (dev_id, driver))
+ print(
+ "Error: bind failed for %s - Cannot write new PCI ID to "
+ "driver %s" % (dev_id, driver)
+ )
return
# do the bind by writing to /sys
@@ -442,8 +456,7 @@ def bind_one(dev_id, driver, force):
try:
f = open(filename, "a")
except:
- print("Error: bind failed for %s - Cannot open %s"
- % (dev_id, filename))
+ print("Error: bind failed for %s - Cannot open %s" % (dev_id, filename))
if saved_driver is not None: # restore any previous driver
bind_one(dev_id, saved_driver, force)
return
@@ -457,8 +470,7 @@ def bind_one(dev_id, driver, force):
tmp = get_pci_device_details(dev_id)
if "Driver_str" in tmp and tmp["Driver_str"] == driver:
return
- print("Error: bind failed for %s - Cannot bind to driver %s"
- % (dev_id, driver))
+ print("Error: bind failed for %s - Cannot bind to driver %s" % (dev_id, driver))
if saved_driver is not None: # restore any previous driver
bind_one(dev_id, saved_driver, force)
return
@@ -491,8 +503,7 @@ def bind_all(dev_list, driver, force=False):
continue
# update information about this device
- devices[d] = dict(devices[d].items() +
- get_pci_device_details(d).items())
+ devices[d] = dict(devices[d].items() + get_pci_device_details(d).items())
# check if updated information indicates that the device was bound
if "Driver_str" in devices[d]:
@@ -500,20 +511,21 @@ def bind_all(dev_list, driver, force=False):
def display_devices(title, dev_list, extra_params=None):
- '''Displays to the user the details of a list of devices given in
+ """Displays to the user the details of a list of devices given in
"dev_list". The "extra_params" parameter, if given, should contain a string
with %()s fields in it for replacement by the named fields in each
- device's dictionary.'''
+ device's dictionary."""
strings = [] # this holds the strings to print. We sort before printing
print("\n%s" % title)
- print("="*len(title))
+ print("=" * len(title))
if len(dev_list) == 0:
strings.append("<none>")
else:
for dev in dev_list:
if extra_params is not None:
- strings.append("%s '%s' %s" % (dev["Slot"],
- dev["Device_str"], extra_params % dev))
+ strings.append(
+ "%s '%s' %s" % (dev["Slot"], dev["Device_str"], extra_params % dev)
+ )
else:
strings.append("%s '%s'" % (dev["Slot"], dev["Device_str"]))
# sort before printing, so that the entries appear in PCI order
@@ -522,9 +534,9 @@ def display_devices(title, dev_list, extra_params=None):
def show_status():
- '''Function called when the script is passed the "--status" option.
+ """Function called when the script is passed the "--status" option.
Displays to the user what devices are bound to the igb_uio driver, the
- kernel driver or to no driver'''
+ kernel driver or to no driver"""
global dpdk_drivers
kernel_drv = []
dpdk_drv = []
@@ -532,7 +544,7 @@ def show_status():
# split our list of network devices into the three categories above
for d in devices.keys():
- if (NETWORK_BASE_CLASS in devices[d]["Class"]):
+ if NETWORK_BASE_CLASS in devices[d]["Class"]:
if not has_driver(d):
no_drv.append(devices[d])
continue
@@ -542,11 +554,16 @@ def show_status():
kernel_drv.append(devices[d])
# print each category separately, so we can clearly see what's used by DPDK
- display_devices("Network devices using DPDK-compatible driver", dpdk_drv,
- "drv=%(Driver_str)s unused=%(Module_str)s")
- display_devices("Network devices using kernel driver", kernel_drv,
- "if=%(Interface)s drv=%(Driver_str)s "
- "unused=%(Module_str)s %(Active)s")
+ display_devices(
+ "Network devices using DPDK-compatible driver",
+ dpdk_drv,
+ "drv=%(Driver_str)s unused=%(Module_str)s",
+ )
+ display_devices(
+ "Network devices using kernel driver",
+ kernel_drv,
+ "if=%(Interface)s drv=%(Driver_str)s " "unused=%(Module_str)s %(Active)s",
+ )
display_devices("Other network devices", no_drv, "unused=%(Module_str)s")
# split our list of crypto devices into the three categories above
@@ -555,7 +572,7 @@ def show_status():
no_drv = []
for d in devices.keys():
- if (CRYPTO_BASE_CLASS in devices[d]["Class"]):
+ if CRYPTO_BASE_CLASS in devices[d]["Class"]:
if not has_driver(d):
no_drv.append(devices[d])
continue
@@ -564,17 +581,22 @@ def show_status():
else:
kernel_drv.append(devices[d])
- display_devices("Crypto devices using DPDK-compatible driver", dpdk_drv,
- "drv=%(Driver_str)s unused=%(Module_str)s")
- display_devices("Crypto devices using kernel driver", kernel_drv,
- "drv=%(Driver_str)s "
- "unused=%(Module_str)s")
+ display_devices(
+ "Crypto devices using DPDK-compatible driver",
+ dpdk_drv,
+ "drv=%(Driver_str)s unused=%(Module_str)s",
+ )
+ display_devices(
+ "Crypto devices using kernel driver",
+ kernel_drv,
+ "drv=%(Driver_str)s " "unused=%(Module_str)s",
+ )
display_devices("Other crypto devices", no_drv, "unused=%(Module_str)s")
def parse_args():
- '''Parses the command-line arguments given by the user and takes the
- appropriate action for each'''
+ """Parses the command-line arguments given by the user and takes the
+ appropriate action for each"""
global b_flag
global status_flag
global force_flag
@@ -584,9 +606,11 @@ def parse_args():
sys.exit(0)
try:
- opts, args = getopt.getopt(sys.argv[1:], "b:us",
- ["help", "usage", "status", "force",
- "bind=", "unbind"])
+ opts, args = getopt.getopt(
+ sys.argv[1:],
+ "b:us",
+ ["help", "usage", "status", "force", "bind=", "unbind"],
+ )
except getopt.GetoptError as error:
print(str(error))
print("Run '%s --usage' for further information" % sys.argv[0])
@@ -611,15 +635,14 @@ def parse_args():
def do_arg_actions():
- '''do the actual action requested by the user'''
+ """do the actual action requested by the user"""
global b_flag
global status_flag
global force_flag
global args
if b_flag is None and not status_flag:
- print("Error: No action specified for devices."
- "Please give a -b or -u option")
+ print("Error: No action specified for devices." "Please give a -b or -u option")
print("Run '%s --usage' for further information" % sys.argv[0])
sys.exit(1)
@@ -640,7 +663,7 @@ def do_arg_actions():
def main():
- '''program main function'''
+ """program main function"""
parse_args()
check_modules()
get_nic_details()
diff --git a/extras/vpp_config/setup.py b/extras/vpp_config/setup.py
index 64f75d7cc89..010920bd7d5 100644
--- a/extras/vpp_config/setup.py
+++ b/extras/vpp_config/setup.py
@@ -1,33 +1,31 @@
from setuptools import setup
-setup(name="vpp_config",
- version="20.05.1",
- author="John DeNisco",
- author_email="jdenisco@cisco.com",
- description="VPP Configuration Utility",
- license='Apache-2.0',
- keywords="vppconfig",
- url='https://wiki.fd.io/view/VPP',
- py_modules=['vpp_config'],
- install_requires=['distro', 'pyyaml', 'requests'],
- extra_requires=["ipaddress; python_version < '3.3'"],
- packages=['vpplib'],
- entry_points={
- 'console_scripts': ['vpp-config=vpp_config:config_main'],
- },
- data_files=[('vpp/vpp-config/scripts', ['scripts/dpdk-devbind.py']),
- ('vpp/vpp-config/configs', ['data/auto-config.yaml']),
- ('vpp/vpp-config/configs', ['data/cloud-config.iso']),
- ('vpp/vpp-config/configs',
- ['data/iperf-centos.xml.template']),
- ('vpp/vpp-config/configs',
- ['data/iperf-ubuntu.xml.template']),
- ('vpp/vpp-config/dryrun/sysctl.d',
- ['data/80-vpp.conf.template']),
- ('vpp/vpp-config/dryrun/default', ['data/grub.template']),
- ('vpp/vpp-config/dryrun/vpp',
- ['data/startup.conf.template']),
- ],
- long_description="The VPP configuration utility can be used to "
- "easily configure VPP.",
- )
+setup(
+ name="vpp_config",
+ version="20.05.1",
+ author="John DeNisco",
+ author_email="jdenisco@cisco.com",
+ description="VPP Configuration Utility",
+ license="Apache-2.0",
+ keywords="vppconfig",
+ url="https://wiki.fd.io/view/VPP",
+ py_modules=["vpp_config"],
+ install_requires=["distro", "pyyaml", "requests"],
+ extra_requires=["ipaddress; python_version < '3.3'"],
+ packages=["vpplib"],
+ entry_points={
+ "console_scripts": ["vpp-config=vpp_config:config_main"],
+ },
+ data_files=[
+ ("vpp/vpp-config/scripts", ["scripts/dpdk-devbind.py"]),
+ ("vpp/vpp-config/configs", ["data/auto-config.yaml"]),
+ ("vpp/vpp-config/configs", ["data/cloud-config.iso"]),
+ ("vpp/vpp-config/configs", ["data/iperf-centos.xml.template"]),
+ ("vpp/vpp-config/configs", ["data/iperf-ubuntu.xml.template"]),
+ ("vpp/vpp-config/dryrun/sysctl.d", ["data/80-vpp.conf.template"]),
+ ("vpp/vpp-config/dryrun/default", ["data/grub.template"]),
+ ("vpp/vpp-config/dryrun/vpp", ["data/startup.conf.template"]),
+ ],
+ long_description="The VPP configuration utility can be used to "
+ "easily configure VPP.",
+)
diff --git a/extras/vpp_config/vpp_config.py b/extras/vpp_config/vpp_config.py
index e863cde854e..74051300677 100755
--- a/extras/vpp_config/vpp_config.py
+++ b/extras/vpp_config/vpp_config.py
@@ -32,16 +32,16 @@ try:
except NameError:
pass
-VPP_DRYRUNDIR = '/vpp/vpp-config/dryrun'
-VPP_AUTO_CONFIGURATION_FILE = '/vpp/vpp-config/configs/auto-config.yaml'
-VPP_HUGE_PAGE_FILE = '/vpp/vpp-config/dryrun/sysctl.d/80-vpp.conf'
-VPP_STARTUP_FILE = '/vpp/vpp-config/dryrun/vpp/startup.conf'
-VPP_GRUB_FILE = '/vpp/vpp-config/dryrun/default/grub'
-VPP_REAL_HUGE_PAGE_FILE = '/etc/sysctl.d/80-vpp.conf'
-VPP_REAL_STARTUP_FILE = '/etc/vpp/startup.conf'
-VPP_REAL_GRUB_FILE = '/etc/default/grub'
+VPP_DRYRUNDIR = "/vpp/vpp-config/dryrun"
+VPP_AUTO_CONFIGURATION_FILE = "/vpp/vpp-config/configs/auto-config.yaml"
+VPP_HUGE_PAGE_FILE = "/vpp/vpp-config/dryrun/sysctl.d/80-vpp.conf"
+VPP_STARTUP_FILE = "/vpp/vpp-config/dryrun/vpp/startup.conf"
+VPP_GRUB_FILE = "/vpp/vpp-config/dryrun/default/grub"
+VPP_REAL_HUGE_PAGE_FILE = "/etc/sysctl.d/80-vpp.conf"
+VPP_REAL_STARTUP_FILE = "/etc/vpp/startup.conf"
+VPP_REAL_GRUB_FILE = "/etc/default/grub"
-rootdir = ''
+rootdir = ""
def autoconfig_yn(question, default):
@@ -57,16 +57,16 @@ def autoconfig_yn(question, default):
"""
input_valid = False
default = default.lower()
- answer = ''
+ answer = ""
while not input_valid:
answer = input(question)
if len(answer) == 0:
answer = default
- if re.findall(r'[YyNn]', answer):
+ if re.findall(r"[YyNn]", answer):
input_valid = True
answer = answer[0].lower()
else:
- print ("Please answer Y, N or Return.")
+ print("Please answer Y, N or Return.")
return answer
@@ -86,24 +86,21 @@ def autoconfig_cp(node, src, dst):
# If the destination file exist, create a copy if one does not already
# exist
- ofile = dst + '.orig'
- (ret, stdout, stderr) = VPPUtil.exec_command('ls {}'.format(dst))
+ ofile = dst + ".orig"
+ (ret, stdout, stderr) = VPPUtil.exec_command("ls {}".format(dst))
if ret == 0:
- cmd = 'cp {} {}'.format(dst, ofile)
+ cmd = "cp {} {}".format(dst, ofile)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.
- format(cmd,
- node['host'],
- stdout,
- stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
# Copy the source file
- cmd = 'cp {} {}'.format(src, os.path.dirname(dst))
+ cmd = "cp {} {}".format(src, os.path.dirname(dst))
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {}'.
- format(cmd, node['host'], stderr))
+ raise RuntimeError("{} failed on node {} {}".format(cmd, node["host"], stderr))
def autoconfig_diff(node, src, dst):
@@ -124,12 +121,10 @@ def autoconfig_diff(node, src, dst):
# Diff the files and return the output
cmd = "diff {} {}".format(src, dst)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
- if stderr != '':
- raise RuntimeError('{} failed on node {} {} {}'.
- format(cmd,
- node['host'],
- ret,
- stderr))
+ if stderr != "":
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], ret, stderr)
+ )
return stdout
@@ -160,13 +155,15 @@ def autoconfig_hugepage_apply(node, ask_questions=True):
"""
diffs = autoconfig_diff(node, VPP_REAL_HUGE_PAGE_FILE, rootdir + VPP_HUGE_PAGE_FILE)
- if diffs != '':
- print ("These are the changes we will apply to")
- print ("the huge page file ({}).\n".format(VPP_REAL_HUGE_PAGE_FILE))
- print (diffs)
+ if diffs != "":
+ print("These are the changes we will apply to")
+ print("the huge page file ({}).\n".format(VPP_REAL_HUGE_PAGE_FILE))
+ print(diffs)
if ask_questions:
- answer = autoconfig_yn("\nAre you sure you want to apply these changes [Y/n]? ", 'y')
- if answer == 'n':
+ answer = autoconfig_yn(
+ "\nAre you sure you want to apply these changes [Y/n]? ", "y"
+ )
+ if answer == "n":
return -1
# Copy and sysctl
@@ -174,10 +171,11 @@ def autoconfig_hugepage_apply(node, ask_questions=True):
cmd = "sysctl -p {}".format(VPP_REAL_HUGE_PAGE_FILE)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.
- format(cmd, node['host'], stdout, stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
else:
- print ('\nThere are no changes to the huge page configuration.')
+ print("\nThere are no changes to the huge page configuration.")
return 0
@@ -196,19 +194,21 @@ def autoconfig_vpp_apply(node, ask_questions=True):
"""
diffs = autoconfig_diff(node, VPP_REAL_STARTUP_FILE, rootdir + VPP_STARTUP_FILE)
- if diffs != '':
- print ("These are the changes we will apply to")
- print ("the VPP startup file ({}).\n".format(VPP_REAL_STARTUP_FILE))
- print (diffs)
+ if diffs != "":
+ print("These are the changes we will apply to")
+ print("the VPP startup file ({}).\n".format(VPP_REAL_STARTUP_FILE))
+ print(diffs)
if ask_questions:
- answer = autoconfig_yn("\nAre you sure you want to apply these changes [Y/n]? ", 'y')
- if answer == 'n':
+ answer = autoconfig_yn(
+ "\nAre you sure you want to apply these changes [Y/n]? ", "y"
+ )
+ if answer == "n":
return -1
# Copy the VPP startup
autoconfig_cp(node, rootdir + VPP_STARTUP_FILE, VPP_REAL_STARTUP_FILE)
else:
- print ('\nThere are no changes to VPP startup.')
+ print("\nThere are no changes to VPP startup.")
return 0
@@ -226,49 +226,52 @@ def autoconfig_grub_apply(node, ask_questions=True):
"""
- print ("\nThe configured grub cmdline looks like this:")
- configured_cmdline = node['grub']['default_cmdline']
- current_cmdline = node['grub']['current_cmdline']
- print (configured_cmdline)
- print ("\nThe current boot cmdline looks like this:")
- print (current_cmdline)
+ print("\nThe configured grub cmdline looks like this:")
+ configured_cmdline = node["grub"]["default_cmdline"]
+ current_cmdline = node["grub"]["current_cmdline"]
+ print(configured_cmdline)
+ print("\nThe current boot cmdline looks like this:")
+ print(current_cmdline)
if ask_questions:
question = "\nDo you want to keep the current boot cmdline [Y/n]? "
- answer = autoconfig_yn(question, 'y')
- if answer == 'y':
+ answer = autoconfig_yn(question, "y")
+ if answer == "y":
return
- node['grub']['keep_cmdline'] = False
+ node["grub"]["keep_cmdline"] = False
# Diff the file
diffs = autoconfig_diff(node, VPP_REAL_GRUB_FILE, rootdir + VPP_GRUB_FILE)
- if diffs != '':
- print ("These are the changes we will apply to")
- print ("the GRUB file ({}).\n".format(VPP_REAL_GRUB_FILE))
- print (diffs)
+ if diffs != "":
+ print("These are the changes we will apply to")
+ print("the GRUB file ({}).\n".format(VPP_REAL_GRUB_FILE))
+ print(diffs)
if ask_questions:
- answer = autoconfig_yn("\nAre you sure you want to apply these changes [y/N]? ", 'n')
- if answer == 'n':
+ answer = autoconfig_yn(
+ "\nAre you sure you want to apply these changes [y/N]? ", "n"
+ )
+ if answer == "n":
return -1
# Copy and update grub
autoconfig_cp(node, rootdir + VPP_GRUB_FILE, VPP_REAL_GRUB_FILE)
distro = VPPUtil.get_linux_distro()
- if distro[0] == 'Ubuntu':
+ if distro[0] == "Ubuntu":
cmd = "update-grub"
else:
cmd = "grub2-mkconfig -o /boot/grub2/grub.cfg"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.
- format(cmd, node['host'], stdout, stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
- print ("There have been changes to the GRUB config a", end=' ')
- print ("reboot will be required.")
+ print("There have been changes to the GRUB config a", end=" ")
+ print("reboot will be required.")
return -1
else:
- print ('\nThere are no changes to the GRUB config.')
+ print("\nThere are no changes to the GRUB config.")
return 0
@@ -289,15 +292,15 @@ def autoconfig_apply(ask_questions=True):
vutil = VPPUtil()
pkgs = vutil.get_installed_vpp_pkgs()
if len(pkgs) == 0:
- print ("\nVPP is not installed, Install VPP with option 4.")
+ print("\nVPP is not installed, Install VPP with option 4.")
return
acfg = AutoConfig(rootdir, VPP_AUTO_CONFIGURATION_FILE)
if ask_questions:
- print ("\nWe are now going to configure your system(s).\n")
- answer = autoconfig_yn("Are you sure you want to do this [Y/n]? ", 'y')
- if answer == 'n':
+ print("\nWe are now going to configure your system(s).\n")
+ answer = autoconfig_yn("Are you sure you want to do this [Y/n]? ", "y")
+ if answer == "n":
return
nodes = acfg.get_nodes()
@@ -369,7 +372,9 @@ def autoconfig_dryrun(ask_questions=True):
for i in nodes.items():
node = i[1]
if not acfg.has_interfaces(node):
- print("\nThere are no VPP interfaces configured, please configure at least 1.")
+ print(
+ "\nThere are no VPP interfaces configured, please configure at least 1."
+ )
return
# Modify CPU
@@ -414,34 +419,31 @@ def autoconfig_install():
pkgs = vutil.get_installed_vpp_pkgs()
if len(pkgs) > 0:
- print ("\nThese packages are installed on node {}"
- .format(node['host']))
- print ("{:25} {}".format("Name", "Version"))
+ print("\nThese packages are installed on node {}".format(node["host"]))
+ print("{:25} {}".format("Name", "Version"))
for pkg in pkgs:
try:
- print ("{:25} {}".format(
- pkg['name'], pkg['version']))
+ print("{:25} {}".format(pkg["name"], pkg["version"]))
except KeyError:
- print ("{}".format(pkg['name']))
+ print("{}".format(pkg["name"]))
question = "\nDo you want to uninstall these "
question += "packages [y/N]? "
- answer = autoconfig_yn(question, 'n')
- if answer == 'y':
+ answer = autoconfig_yn(question, "n")
+ if answer == "y":
logger.setLevel(logging.INFO)
vutil.uninstall_vpp(node)
else:
- print ("\nThere are no VPP packages on node {}."
- .format(node['host']))
+ print("\nThere are no VPP packages on node {}.".format(node["host"]))
question = "Do you want to install VPP [Y/n]? "
- answer = autoconfig_yn(question, 'y')
- if answer == 'y':
+ answer = autoconfig_yn(question, "y")
+ if answer == "y":
question = "Do you want to install the release version [Y/n]? "
- answer = autoconfig_yn(question, 'y')
- if answer == 'y':
- branch = 'release'
+ answer = autoconfig_yn(question, "y")
+ if answer == "y":
+ branch = "release"
else:
- branch = 'master'
+ branch = "master"
logger.setLevel(logging.INFO)
vutil.install_vpp(node, branch)
@@ -486,9 +488,9 @@ def autoconfig_create_iperf_vm():
"""
acfg = AutoConfig(rootdir, VPP_AUTO_CONFIGURATION_FILE)
- acfg.destroy_iperf_vm('iperf-server')
+ acfg.destroy_iperf_vm("iperf-server")
acfg.create_and_bridge_iperf_virtual_interface()
- acfg.create_iperf_vm('iperf-server')
+ acfg.create_iperf_vm("iperf-server")
def autoconfig_not_implemented():
@@ -497,7 +499,7 @@ def autoconfig_not_implemented():
"""
- print ("\nThis Feature is not implemented yet....")
+ print("\nThis Feature is not implemented yet....")
def autoconfig_basic_test_menu():
@@ -506,28 +508,28 @@ def autoconfig_basic_test_menu():
"""
- basic_menu_text = '\nWhat would you like to do?\n\n\
+ basic_menu_text = "\nWhat would you like to do?\n\n\
1) List/Create Simple IPv4 Setup\n\
2) Create an iperf VM and Connect to VPP an interface\n\
-9 or q) Back to main menu.'
+9 or q) Back to main menu."
- print ("{}".format(basic_menu_text))
+ print("{}".format(basic_menu_text))
input_valid = False
- answer = ''
+ answer = ""
while not input_valid:
answer = input("\nCommand: ")
if len(answer) > 1:
- print ("Please enter only 1 character.")
+ print("Please enter only 1 character.")
continue
- if re.findall(r'[Qq1-29]', answer):
+ if re.findall(r"[Qq1-29]", answer):
input_valid = True
answer = answer[0].lower()
else:
- print ("Please enter a character between 1 and 2 or 9.")
+ print("Please enter a character between 1 and 2 or 9.")
- if answer == '9':
- answer = 'q'
+ if answer == "9":
+ answer = "q"
return answer
@@ -540,17 +542,17 @@ def autoconfig_basic_test():
vutil = VPPUtil()
pkgs = vutil.get_installed_vpp_pkgs()
if len(pkgs) == 0:
- print ("\nVPP is not installed, install VPP with option 4.")
+ print("\nVPP is not installed, install VPP with option 4.")
return
- answer = ''
- while answer != 'q':
+ answer = ""
+ while answer != "q":
answer = autoconfig_basic_test_menu()
- if answer == '1':
+ if answer == "1":
autoconfig_ipv4_setup()
- elif answer == '2':
+ elif answer == "2":
autoconfig_create_iperf_vm()
- elif answer == '9' or answer == 'q':
+ elif answer == "9" or answer == "q":
return
else:
autoconfig_not_implemented()
@@ -562,30 +564,32 @@ def autoconfig_main_menu():
"""
- main_menu_text = '\nWhat would you like to do?\n\n\
+ main_menu_text = "\nWhat would you like to do?\n\n\
1) Show basic system information\n\
2) Dry Run (Saves the configuration files in {}/vpp/vpp-config/dryrun.\n\
3) Full configuration (WARNING: This will change the system configuration)\n\
4) List/Install/Uninstall VPP.\n\
-q) Quit'.format(rootdir, rootdir)
+q) Quit".format(
+ rootdir, rootdir
+ )
# 5) Dry Run from {}/vpp/vpp-config/auto-config.yaml (will not ask questions).\n\
# 6) Install QEMU patch (Needed when running openstack).\n\
- print ("{}".format(main_menu_text))
+ print("{}".format(main_menu_text))
input_valid = False
- answer = ''
+ answer = ""
while not input_valid:
answer = input("\nCommand: ")
if len(answer) > 1:
- print ("Please enter only 1 character.")
+ print("Please enter only 1 character.")
continue
- if re.findall(r'[Qq1-4]', answer):
+ if re.findall(r"[Qq1-4]", answer):
input_valid = True
answer = answer[0].lower()
else:
- print ("Please enter a character between 1 and 4 or q.")
+ print("Please enter a character between 1 and 4 or q.")
return answer
@@ -599,18 +603,18 @@ def autoconfig_main():
# Setup
autoconfig_setup()
- answer = ''
- while answer != 'q':
+ answer = ""
+ while answer != "q":
answer = autoconfig_main_menu()
- if answer == '1':
+ if answer == "1":
autoconfig_show_system()
- elif answer == '2':
+ elif answer == "2":
autoconfig_dryrun()
- elif answer == '3':
+ elif answer == "3":
autoconfig_apply()
- elif answer == '4':
+ elif answer == "4":
autoconfig_install()
- elif answer == 'q':
+ elif answer == "q":
return
else:
autoconfig_not_implemented()
@@ -627,53 +631,65 @@ def autoconfig_setup(ask_questions=True):
global rootdir
distro = VPPUtil.get_linux_distro()
- if distro[0] == 'Ubuntu':
- rootdir = '/usr/local'
+ if distro[0] == "Ubuntu":
+ rootdir = "/usr/local"
else:
- rootdir = '/usr'
+ rootdir = "/usr"
# If there is a system configuration file use that, if not use the initial auto-config file
filename = rootdir + VPP_AUTO_CONFIGURATION_FILE
if os.path.isfile(filename) is True:
acfg = AutoConfig(rootdir, VPP_AUTO_CONFIGURATION_FILE)
else:
- raise RuntimeError('The Auto configuration file does not exist {}'.
- format(filename))
+ raise RuntimeError(
+ "The Auto configuration file does not exist {}".format(filename)
+ )
if ask_questions:
- print ("\nWelcome to the VPP system configuration utility")
+ print("\nWelcome to the VPP system configuration utility")
- print ("\nThese are the files we will modify:")
- print (" /etc/vpp/startup.conf")
- print (" /etc/sysctl.d/80-vpp.conf")
- print (" /etc/default/grub")
+ print("\nThese are the files we will modify:")
+ print(" /etc/vpp/startup.conf")
+ print(" /etc/sysctl.d/80-vpp.conf")
+ print(" /etc/default/grub")
- print (
+ print(
"\nBefore we change them, we'll create working copies in "
- "{}".format(rootdir + VPP_DRYRUNDIR))
- print (
+ "{}".format(rootdir + VPP_DRYRUNDIR)
+ )
+ print(
"Please inspect them carefully before applying the actual "
- "configuration (option 3)!")
+ "configuration (option 3)!"
+ )
nodes = acfg.get_nodes()
for i in nodes.items():
node = i[1]
- if (os.path.isfile(rootdir + VPP_STARTUP_FILE) is not True) and \
- (os.path.isfile(VPP_REAL_STARTUP_FILE) is True):
- autoconfig_cp(node, VPP_REAL_STARTUP_FILE, '{}'.format(rootdir + VPP_STARTUP_FILE))
- if (os.path.isfile(rootdir + VPP_HUGE_PAGE_FILE) is not True) and \
- (os.path.isfile(VPP_REAL_HUGE_PAGE_FILE) is True):
- autoconfig_cp(node, VPP_REAL_HUGE_PAGE_FILE, '{}'.format(rootdir + VPP_HUGE_PAGE_FILE))
- if (os.path.isfile(rootdir + VPP_GRUB_FILE) is not True) and \
- (os.path.isfile(VPP_REAL_GRUB_FILE) is True):
- autoconfig_cp(node, VPP_REAL_GRUB_FILE, '{}'.format(rootdir + VPP_GRUB_FILE))
+ if (os.path.isfile(rootdir + VPP_STARTUP_FILE) is not True) and (
+ os.path.isfile(VPP_REAL_STARTUP_FILE) is True
+ ):
+ autoconfig_cp(
+ node, VPP_REAL_STARTUP_FILE, "{}".format(rootdir + VPP_STARTUP_FILE)
+ )
+ if (os.path.isfile(rootdir + VPP_HUGE_PAGE_FILE) is not True) and (
+ os.path.isfile(VPP_REAL_HUGE_PAGE_FILE) is True
+ ):
+ autoconfig_cp(
+ node, VPP_REAL_HUGE_PAGE_FILE, "{}".format(rootdir + VPP_HUGE_PAGE_FILE)
+ )
+ if (os.path.isfile(rootdir + VPP_GRUB_FILE) is not True) and (
+ os.path.isfile(VPP_REAL_GRUB_FILE) is True
+ ):
+ autoconfig_cp(
+ node, VPP_REAL_GRUB_FILE, "{}".format(rootdir + VPP_GRUB_FILE)
+ )
# Be sure the uio_pci_generic driver is installed
- cmd = 'modprobe uio_pci_generic'
+ cmd = "modprobe uio_pci_generic"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- logging.warning('{} failed on node {} {}'. format(cmd, node['host'], stderr))
+ logging.warning("{} failed on node {} {}".format(cmd, node["host"], stderr))
# noinspection PyUnresolvedReferences
@@ -707,10 +723,9 @@ def config_main():
# Check for root
if not os.geteuid() == 0:
- sys.exit('\nPlease run the VPP Configuration Utility as root.')
+ sys.exit("\nPlease run the VPP Configuration Utility as root.")
- if len(sys.argv) > 1 and ((sys.argv[1] == '-d') or (
- sys.argv[1] == '--debug')):
+ if len(sys.argv) > 1 and ((sys.argv[1] == "-d") or (sys.argv[1] == "--debug")):
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.ERROR)
@@ -720,37 +735,44 @@ def config_main():
if len(sys.argv) == 1:
autoconfig_main()
return
- elif len(sys.argv) == 2 and ((sys.argv[1] == '-d') or (
- sys.argv[1] == '--debug')):
+ elif len(sys.argv) == 2 and ((sys.argv[1] == "-d") or (sys.argv[1] == "--debug")):
autoconfig_main()
return
# There were arguments specified, so execute the utility using
# command line arguments
- description = 'The VPP configuration utility allows the user to '
- 'configure VPP in a simple and safe manner. The utility takes input '
- 'from the user or the specified .yaml file. The user should then '
- 'examine these files to be sure they are correct and then actually '
- 'apply the configuration. When run without arguments the utility run '
- 'in an interactive mode'
+ description = "The VPP configuration utility allows the user to "
+ "configure VPP in a simple and safe manner. The utility takes input "
+ "from the user or the specified .yaml file. The user should then "
+ "examine these files to be sure they are correct and then actually "
+ "apply the configuration. When run without arguments the utility run "
+ "in an interactive mode"
main_parser = argparse.ArgumentParser(
- prog='arg-test',
+ prog="arg-test",
description=description,
- epilog='See "%(prog)s help COMMAND" for help on a specific command.')
- main_parser.add_argument('--apply', '-a', action='store_true',
- help='Apply the cofiguration.')
- main_parser.add_argument('--dry-run', '-dr', action='store_true',
- help='Create the dryrun configuration files.')
- main_parser.add_argument('--show', '-s', action='store_true',
- help='Shows basic system information')
- main_parser.add_argument('--debug', '-d', action='count',
- help='Print debug output (multiple levels)')
+ epilog='See "%(prog)s help COMMAND" for help on a specific command.',
+ )
+ main_parser.add_argument(
+ "--apply", "-a", action="store_true", help="Apply the cofiguration."
+ )
+ main_parser.add_argument(
+ "--dry-run",
+ "-dr",
+ action="store_true",
+ help="Create the dryrun configuration files.",
+ )
+ main_parser.add_argument(
+ "--show", "-s", action="store_true", help="Shows basic system information"
+ )
+ main_parser.add_argument(
+ "--debug", "-d", action="count", help="Print debug output (multiple levels)"
+ )
args = main_parser.parse_args()
return execute_with_args(args)
-if __name__ == '__main__':
+if __name__ == "__main__":
config_main()
diff --git a/extras/vpp_config/vpplib/AutoConfig.py b/extras/vpp_config/vpplib/AutoConfig.py
index 62f18e27929..9a79039f69e 100644
--- a/extras/vpp_config/vpplib/AutoConfig.py
+++ b/extras/vpp_config/vpplib/AutoConfig.py
@@ -41,9 +41,9 @@ MIN_SYSTEM_CPUS = 2
MIN_TOTAL_HUGE_PAGES = 1024
MAX_PERCENT_FOR_HUGE_PAGES = 70
-IPERFVM_XML = 'configs/iperf-vm.xml'
-IPERFVM_IMAGE = 'images/xenial-mod.img'
-IPERFVM_ISO = 'configs/cloud-config.iso'
+IPERFVM_XML = "configs/iperf-vm.xml"
+IPERFVM_IMAGE = "images/xenial-mod.img"
+IPERFVM_ISO = "configs/cloud-config.iso"
class AutoConfig(object):
@@ -90,12 +90,12 @@ class AutoConfig(object):
"""
# Does a copy of the file exist, if not create one
- ofile = filename + '.orig'
- (ret, stdout, stderr) = VPPUtil.exec_command('ls {}'.format(ofile))
+ ofile = filename + ".orig"
+ (ret, stdout, stderr) = VPPUtil.exec_command("ls {}".format(ofile))
if ret != 0:
logging.debug(stderr)
- if stdout.strip('\n') != ofile:
- cmd = 'sudo cp {} {}'.format(filename, ofile)
+ if stdout.strip("\n") != ofile:
+ cmd = "sudo cp {} {}".format(filename, ofile)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
logging.debug(stderr)
@@ -114,14 +114,14 @@ class AutoConfig(object):
while True:
answer = input("Please enter the IPv4 Address [n.n.n.n/n]: ")
try:
- ipinput = answer.split('/')
+ ipinput = answer.split("/")
ipaddr = ip_address(ipinput[0])
if len(ipinput) > 1:
- plen = answer.split('/')[1]
+ plen = answer.split("/")[1]
else:
answer = input("Please enter the netmask [n.n.n.n]: ")
plen = ip_address(answer).netmask_bits()
- return '{}/{}'.format(ipaddr, plen)
+ return "{}/{}".format(ipaddr, plen)
except ValueError:
print("Please enter a valid IPv4 address.")
@@ -145,18 +145,22 @@ class AutoConfig(object):
while True:
answer = input(question)
- if answer == '':
+ if answer == "":
answer = default
break
- if re.findall(r'[0-9+]', answer):
+ if re.findall(r"[0-9+]", answer):
if int(answer) in range(first, last + 1):
break
else:
- print("Please a value between {} and {} or Return.".
- format(first, last))
+ print(
+ "Please a value between {} and {} or Return.".format(
+ first, last
+ )
+ )
else:
- print("Please a number between {} and {} or Return.".
- format(first, last))
+ print(
+ "Please a number between {} and {} or Return.".format(first, last)
+ )
return int(answer)
@@ -175,12 +179,12 @@ class AutoConfig(object):
input_valid = False
default = default.lower()
- answer = ''
+ answer = ""
while not input_valid:
answer = input(question)
- if answer == '':
+ if answer == "":
answer = default
- if re.findall(r'[YyNn]', answer):
+ if re.findall(r"[YyNn]", answer):
input_valid = True
answer = answer[0].lower()
else:
@@ -196,36 +200,40 @@ class AutoConfig(object):
# Get the Topology, from the topology layout file
topo = {}
- with open(self._autoconfig_filename, 'r') as stream:
+ with open(self._autoconfig_filename, "r") as stream:
try:
topo = yaml.load(stream)
- if 'metadata' in topo:
- self._metadata = topo['metadata']
+ if "metadata" in topo:
+ self._metadata = topo["metadata"]
except yaml.YAMLError as exc:
raise RuntimeError(
"Couldn't read the Auto config file {}.".format(
- self._autoconfig_filename, exc))
+ self._autoconfig_filename, exc
+ )
+ )
- systemfile = self._rootdir + self._metadata['system_config_file']
+ systemfile = self._rootdir + self._metadata["system_config_file"]
if self._clean is False and os.path.isfile(systemfile):
- with open(systemfile, 'r') as sysstream:
+ with open(systemfile, "r") as sysstream:
try:
systopo = yaml.load(sysstream)
- if 'nodes' in systopo:
- self._nodes = systopo['nodes']
+ if "nodes" in systopo:
+ self._nodes = systopo["nodes"]
except yaml.YAMLError as sysexc:
raise RuntimeError(
"Couldn't read the System config file {}.".format(
- systemfile, sysexc))
+ systemfile, sysexc
+ )
+ )
else:
# Get the nodes from Auto Config
- if 'nodes' in topo:
- self._nodes = topo['nodes']
+ if "nodes" in topo:
+ self._nodes = topo["nodes"]
# Set the root directory in all the nodes
for i in self._nodes.items():
node = i[1]
- node['rootdir'] = self._rootdir
+ node["rootdir"] = self._rootdir
def updateconfig(self):
"""
@@ -236,11 +244,11 @@ class AutoConfig(object):
"""
# Initialize the yaml data
- ydata = {'metadata': self._metadata, 'nodes': self._nodes}
+ ydata = {"metadata": self._metadata, "nodes": self._nodes}
# Write the system config file
- filename = self._rootdir + self._metadata['system_config_file']
- with open(filename, 'w') as yamlfile:
+ filename = self._rootdir + self._metadata["system_config_file"]
+ with open(filename, "w") as yamlfile:
yaml.dump(ydata, yamlfile)
def _update_auto_config(self):
@@ -252,11 +260,11 @@ class AutoConfig(object):
# Initialize the yaml data
nodes = {}
- with open(self._autoconfig_filename, 'r') as stream:
+ with open(self._autoconfig_filename, "r") as stream:
try:
ydata = yaml.load(stream)
- if 'nodes' in ydata:
- nodes = ydata['nodes']
+ if "nodes" in ydata:
+ nodes = ydata["nodes"]
except yaml.YAMLError as exc:
print(exc)
return
@@ -266,41 +274,45 @@ class AutoConfig(object):
node = i[1]
# Interfaces
- node['interfaces'] = {}
- for item in self._nodes[key]['interfaces'].items():
+ node["interfaces"] = {}
+ for item in self._nodes[key]["interfaces"].items():
port = item[0]
interface = item[1]
- node['interfaces'][port] = {}
- addr = '{}'.format(interface['pci_address'])
- node['interfaces'][port]['pci_address'] = addr
- if 'mac_address' in interface:
- node['interfaces'][port]['mac_address'] = \
- interface['mac_address']
-
- if 'total_other_cpus' in self._nodes[key]['cpu']:
- node['cpu']['total_other_cpus'] = \
- self._nodes[key]['cpu']['total_other_cpus']
- if 'total_vpp_cpus' in self._nodes[key]['cpu']:
- node['cpu']['total_vpp_cpus'] = \
- self._nodes[key]['cpu']['total_vpp_cpus']
- if 'reserve_vpp_main_core' in self._nodes[key]['cpu']:
- node['cpu']['reserve_vpp_main_core'] = \
- self._nodes[key]['cpu']['reserve_vpp_main_core']
+ node["interfaces"][port] = {}
+ addr = "{}".format(interface["pci_address"])
+ node["interfaces"][port]["pci_address"] = addr
+ if "mac_address" in interface:
+ node["interfaces"][port]["mac_address"] = interface["mac_address"]
+
+ if "total_other_cpus" in self._nodes[key]["cpu"]:
+ node["cpu"]["total_other_cpus"] = self._nodes[key]["cpu"][
+ "total_other_cpus"
+ ]
+ if "total_vpp_cpus" in self._nodes[key]["cpu"]:
+ node["cpu"]["total_vpp_cpus"] = self._nodes[key]["cpu"][
+ "total_vpp_cpus"
+ ]
+ if "reserve_vpp_main_core" in self._nodes[key]["cpu"]:
+ node["cpu"]["reserve_vpp_main_core"] = self._nodes[key]["cpu"][
+ "reserve_vpp_main_core"
+ ]
# TCP
- if 'active_open_sessions' in self._nodes[key]['tcp']:
- node['tcp']['active_open_sessions'] = \
- self._nodes[key]['tcp']['active_open_sessions']
- if 'passive_open_sessions' in self._nodes[key]['tcp']:
- node['tcp']['passive_open_sessions'] = \
- self._nodes[key]['tcp']['passive_open_sessions']
+ if "active_open_sessions" in self._nodes[key]["tcp"]:
+ node["tcp"]["active_open_sessions"] = self._nodes[key]["tcp"][
+ "active_open_sessions"
+ ]
+ if "passive_open_sessions" in self._nodes[key]["tcp"]:
+ node["tcp"]["passive_open_sessions"] = self._nodes[key]["tcp"][
+ "passive_open_sessions"
+ ]
# Huge pages
- node['hugepages']['total'] = self._nodes[key]['hugepages']['total']
+ node["hugepages"]["total"] = self._nodes[key]["hugepages"]["total"]
# Write the auto config config file
- with open(self._autoconfig_filename, 'w') as yamlfile:
+ with open(self._autoconfig_filename, "w") as yamlfile:
yaml.dump(ydata, yamlfile)
def apply_huge_pages(self):
@@ -325,28 +337,28 @@ class AutoConfig(object):
"""
# Get main core
- cpu = '\n'
- if 'vpp_main_core' in node['cpu']:
- vpp_main_core = node['cpu']['vpp_main_core']
+ cpu = "\n"
+ if "vpp_main_core" in node["cpu"]:
+ vpp_main_core = node["cpu"]["vpp_main_core"]
else:
vpp_main_core = 0
if vpp_main_core != 0:
- cpu += ' main-core {}\n'.format(vpp_main_core)
+ cpu += " main-core {}\n".format(vpp_main_core)
# Get workers
- vpp_workers = node['cpu']['vpp_workers']
+ vpp_workers = node["cpu"]["vpp_workers"]
vpp_worker_len = len(vpp_workers)
if vpp_worker_len > 0:
- vpp_worker_str = ''
+ vpp_worker_str = ""
for i, worker in enumerate(vpp_workers):
if i > 0:
- vpp_worker_str += ','
+ vpp_worker_str += ","
if worker[0] == worker[1]:
vpp_worker_str += "{}".format(worker[0])
else:
vpp_worker_str += "{}-{}".format(worker[0], worker[1])
- cpu += ' corelist-workers {}\n'.format(vpp_worker_str)
+ cpu += " corelist-workers {}\n".format(vpp_worker_str)
return cpu
@@ -359,41 +371,41 @@ class AutoConfig(object):
:type node: dict
"""
- devices = ''
- ports_per_numa = node['cpu']['ports_per_numa']
+ devices = ""
+ ports_per_numa = node["cpu"]["ports_per_numa"]
for item in ports_per_numa.items():
value = item[1]
- interfaces = value['interfaces']
+ interfaces = value["interfaces"]
# if 0 was specified for the number of vpp workers, use 1 queue
num_rx_queues = None
num_tx_queues = None
- if 'rx_queues' in value:
- num_rx_queues = value['rx_queues']
- if 'tx_queues' in value:
- num_tx_queues = value['tx_queues']
+ if "rx_queues" in value:
+ num_rx_queues = value["rx_queues"]
+ if "tx_queues" in value:
+ num_tx_queues = value["tx_queues"]
num_rx_desc = None
num_tx_desc = None
# Create the devices string
for interface in interfaces:
- pci_address = interface['pci_address']
+ pci_address = interface["pci_address"]
pci_address = pci_address.lstrip("'").rstrip("'")
- devices += '\n'
- devices += ' dev {} {{ \n'.format(pci_address)
+ devices += "\n"
+ devices += " dev {} {{ \n".format(pci_address)
if num_rx_queues:
- devices += ' num-rx-queues {}\n'.format(num_rx_queues)
+ devices += " num-rx-queues {}\n".format(num_rx_queues)
else:
- devices += ' num-rx-queues {}\n'.format(1)
+ devices += " num-rx-queues {}\n".format(1)
if num_tx_queues:
- devices += ' num-tx-queues {}\n'.format(num_tx_queues)
+ devices += " num-tx-queues {}\n".format(num_tx_queues)
if num_rx_desc:
- devices += ' num-rx-desc {}\n'.format(num_rx_desc)
+ devices += " num-rx-desc {}\n".format(num_rx_desc)
if num_tx_desc:
- devices += ' num-tx-desc {}\n'.format(num_tx_desc)
- devices += ' }'
+ devices += " num-tx-desc {}\n".format(num_tx_desc)
+ devices += " }"
return devices
@@ -405,20 +417,25 @@ class AutoConfig(object):
:param node: Node dictionary with cpuinfo.
:type node: dict
"""
- buffers = ''
- total_mbufs = node['cpu']['total_mbufs']
+ buffers = ""
+ total_mbufs = node["cpu"]["total_mbufs"]
# If the total mbufs is not 0 or less than the default, set num-bufs
logging.debug("Total mbufs: {}".format(total_mbufs))
if total_mbufs != 0 and total_mbufs > 16384:
- buffers += ' buffers-per-numa {}'.format(total_mbufs)
+ buffers += " buffers-per-numa {}".format(total_mbufs)
return buffers
@staticmethod
- def _calc_vpp_workers(node, vpp_workers, numa_node, other_cpus_end,
- total_vpp_workers,
- reserve_vpp_main_core):
+ def _calc_vpp_workers(
+ node,
+ vpp_workers,
+ numa_node,
+ other_cpus_end,
+ total_vpp_workers,
+ reserve_vpp_main_core,
+ ):
"""
Calculate the VPP worker information
@@ -440,7 +457,7 @@ class AutoConfig(object):
"""
# Can we fit the workers in one of these slices
- cpus = node['cpu']['cpus_per_node'][numa_node]
+ cpus = node["cpu"]["cpus_per_node"][numa_node]
for cpu in cpus:
start = cpu[0]
end = cpu[1]
@@ -454,7 +471,7 @@ class AutoConfig(object):
if workers_end <= end:
if reserve_vpp_main_core:
- node['cpu']['vpp_main_core'] = start - 1
+ node["cpu"]["vpp_main_core"] = start - 1
reserve_vpp_main_core = False
if total_vpp_workers:
vpp_workers.append((start, workers_end))
@@ -462,15 +479,14 @@ class AutoConfig(object):
# We still need to reserve the main core
if reserve_vpp_main_core:
- node['cpu']['vpp_main_core'] = other_cpus_end + 1
+ node["cpu"]["vpp_main_core"] = other_cpus_end + 1
return reserve_vpp_main_core
@staticmethod
- def _calc_desc_and_queues(total_numa_nodes,
- total_ports_per_numa,
- total_rx_queues,
- ports_per_numa_value):
+ def _calc_desc_and_queues(
+ total_numa_nodes, total_ports_per_numa, total_rx_queues, ports_per_numa_value
+ ):
"""
Calculate the number of descriptors and queues
@@ -494,8 +510,10 @@ class AutoConfig(object):
# Get the descriptor entries
desc_entries = 1024
- ports_per_numa_value['rx_queues'] = rx_queues
- total_mbufs = ((rx_queues * desc_entries) + (tx_queues * desc_entries)) * total_ports_per_numa
+ ports_per_numa_value["rx_queues"] = rx_queues
+ total_mbufs = (
+ (rx_queues * desc_entries) + (tx_queues * desc_entries)
+ ) * total_ports_per_numa
return total_mbufs
@@ -515,12 +533,12 @@ class AutoConfig(object):
ports_per_numa = {}
for item in interfaces.items():
i = item[1]
- if i['numa_node'] not in ports_per_numa:
- ports_per_numa[i['numa_node']] = {'interfaces': []}
- ports_per_numa[i['numa_node']]['interfaces'].append(i)
+ if i["numa_node"] not in ports_per_numa:
+ ports_per_numa[i["numa_node"]] = {"interfaces": []}
+ ports_per_numa[i["numa_node"]]["interfaces"].append(i)
else:
- ports_per_numa[i['numa_node']]['interfaces'].append(i)
- node['cpu']['ports_per_numa'] = ports_per_numa
+ ports_per_numa[i["numa_node"]]["interfaces"].append(i)
+ node["cpu"]["ports_per_numa"] = ports_per_numa
return ports_per_numa
@@ -536,24 +554,24 @@ class AutoConfig(object):
node = i[1]
# get total number of nic ports
- interfaces = node['interfaces']
+ interfaces = node["interfaces"]
# Make a list of ports by numa node
ports_per_numa = self._create_ports_per_numa(node, interfaces)
# Get the number of cpus to skip, we never use the first cpu
other_cpus_start = 1
- other_cpus_end = other_cpus_start + node['cpu']['total_other_cpus'] - 1
+ other_cpus_end = other_cpus_start + node["cpu"]["total_other_cpus"] - 1
other_workers = None
if other_cpus_end != 0:
other_workers = (other_cpus_start, other_cpus_end)
- node['cpu']['other_workers'] = other_workers
+ node["cpu"]["other_workers"] = other_workers
# Allocate the VPP main core and workers
vpp_workers = []
- reserve_vpp_main_core = node['cpu']['reserve_vpp_main_core']
- total_vpp_cpus = node['cpu']['total_vpp_cpus']
- total_rx_queues = node['cpu']['total_rx_queues']
+ reserve_vpp_main_core = node["cpu"]["reserve_vpp_main_core"]
+ total_vpp_cpus = node["cpu"]["total_vpp_cpus"]
+ total_rx_queues = node["cpu"]["total_rx_queues"]
# If total_vpp_cpus is 0 or is less than the numa nodes with ports
# then we shouldn't get workers
@@ -572,14 +590,21 @@ class AutoConfig(object):
# Get the number of descriptors and queues
mbufs = self._calc_desc_and_queues(
len(ports_per_numa),
- len(value['interfaces']), total_rx_queues, value)
+ len(value["interfaces"]),
+ total_rx_queues,
+ value,
+ )
total_mbufs += mbufs
# Get the VPP workers
reserve_vpp_main_core = self._calc_vpp_workers(
- node, vpp_workers, numa_node,
- other_cpus_end, total_workers_node,
- reserve_vpp_main_core)
+ node,
+ vpp_workers,
+ numa_node,
+ other_cpus_end,
+ total_workers_node,
+ reserve_vpp_main_core,
+ )
total_mbufs *= 2.5
total_mbufs = int(total_mbufs)
@@ -587,8 +612,8 @@ class AutoConfig(object):
total_mbufs = 0
# Save the info
- node['cpu']['vpp_workers'] = vpp_workers
- node['cpu']['total_mbufs'] = total_mbufs
+ node["cpu"]["vpp_workers"] = vpp_workers
+ node["cpu"]["total_mbufs"] = total_mbufs
# Write the config
self.updateconfig()
@@ -602,54 +627,55 @@ class AutoConfig(object):
:type node: dict
"""
- active_open_sessions = node['tcp']['active_open_sessions']
+ active_open_sessions = node["tcp"]["active_open_sessions"]
aos = int(active_open_sessions)
- passive_open_sessions = node['tcp']['passive_open_sessions']
+ passive_open_sessions = node["tcp"]["passive_open_sessions"]
pos = int(passive_open_sessions)
# Generate the api-segment gid vpp sheit in any case
if (aos + pos) == 0:
- tcp = '\n'.join([
+ tcp = "\n".join(["api-segment {", " gid vpp", "}"])
+ return tcp.rstrip("\n")
+
+ tcp = "\n".join(
+ [
+ "# TCP stack-related configuration parameters",
+ "# expecting {:d} client sessions, {:d} server sessions\n".format(
+ aos, pos
+ ),
+ "heapsize 4g\n",
"api-segment {",
- " gid vpp",
- "}"
- ])
- return tcp.rstrip('\n')
-
- tcp = '\n'.join([
- "# TCP stack-related configuration parameters",
- "# expecting {:d} client sessions, {:d} server sessions\n".format(
- aos, pos),
- "heapsize 4g\n",
- "api-segment {",
- " global-size 2000M",
- " api-size 1G",
- "}\n",
-
- "session {",
- " event-queue-length {:d}".format(aos + pos),
- " preallocated-sessions {:d}".format(aos + pos),
- " v4-session-table-buckets {:d}".format((aos + pos) // 4),
- " v4-session-table-memory 3g\n"
- ])
+ " global-size 2000M",
+ " api-size 1G",
+ "}\n",
+ "session {",
+ " event-queue-length {:d}".format(aos + pos),
+ " preallocated-sessions {:d}".format(aos + pos),
+ " v4-session-table-buckets {:d}".format((aos + pos) // 4),
+ " v4-session-table-memory 3g\n",
+ ]
+ )
if aos > 0:
- tcp = tcp + " v4-halfopen-table-buckets {:d}".format(
- (aos + pos) // 4) + "\n"
+ tcp = (
+ tcp + " v4-halfopen-table-buckets {:d}".format((aos + pos) // 4) + "\n"
+ )
tcp = tcp + " v4-halfopen-table-memory 3g\n"
- tcp = tcp + " local-endpoints-table-buckets {:d}".format(
- (aos + pos) // 4) + "\n"
+ tcp = (
+ tcp
+ + " local-endpoints-table-buckets {:d}".format((aos + pos) // 4)
+ + "\n"
+ )
tcp = tcp + " local-endpoints-table-memory 3g\n"
tcp = tcp + "}\n\n"
tcp = tcp + "tcp {\n"
tcp = tcp + " preallocated-connections {:d}".format(aos + pos) + "\n"
if aos > 0:
- tcp = tcp + " preallocated-half-open-connections {:d}".format(
- aos) + "\n"
+ tcp = tcp + " preallocated-half-open-connections {:d}".format(aos) + "\n"
tcp = tcp + "}\n\n"
- return tcp.rstrip('\n')
+ return tcp.rstrip("\n")
def apply_vpp_startup(self):
"""
@@ -662,8 +688,8 @@ class AutoConfig(object):
node = i[1]
# Get the startup file
- rootdir = node['rootdir']
- sfile = rootdir + node['vpp']['startup_config_file']
+ rootdir = node["rootdir"]
+ sfile = rootdir + node["vpp"]["startup_config_file"]
# Get the buffers
devices = self._apply_vpp_devices(node)
@@ -680,27 +706,22 @@ class AutoConfig(object):
self._autoconfig_backup_file(sfile)
# Get the template
- tfile = sfile + '.template'
- (ret, stdout, stderr) = \
- VPPUtil.exec_command('cat {}'.format(tfile))
+ tfile = sfile + ".template"
+ (ret, stdout, stderr) = VPPUtil.exec_command("cat {}".format(tfile))
if ret != 0:
- raise RuntimeError('Executing cat command failed to node {}'.
- format(node['host']))
- startup = stdout.format(cpu=cpu,
- buffers=buffers,
- devices=devices,
- tcp=tcp)
-
- (ret, stdout, stderr) = \
- VPPUtil.exec_command('rm {}'.format(sfile))
+ raise RuntimeError(
+ "Executing cat command failed to node {}".format(node["host"])
+ )
+ startup = stdout.format(cpu=cpu, buffers=buffers, devices=devices, tcp=tcp)
+
+ (ret, stdout, stderr) = VPPUtil.exec_command("rm {}".format(sfile))
if ret != 0:
logging.debug(stderr)
cmd = "sudo cat > {0} << EOF\n{1}\n".format(sfile, startup)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('Writing config failed node {}'.
- format(node['host']))
+ raise RuntimeError("Writing config failed node {}".format(node["host"]))
def apply_grub_cmdline(self):
"""
@@ -712,10 +733,10 @@ class AutoConfig(object):
node = i[1]
# Get the isolated CPUs
- other_workers = node['cpu']['other_workers']
- vpp_workers = node['cpu']['vpp_workers']
- if 'vpp_main_core' in node['cpu']:
- vpp_main_core = node['cpu']['vpp_main_core']
+ other_workers = node["cpu"]["other_workers"]
+ vpp_workers = node["cpu"]["vpp_workers"]
+ if "vpp_main_core" in node["cpu"]:
+ vpp_main_core = node["cpu"]["vpp_main_core"]
else:
vpp_main_core = 0
all_workers = []
@@ -724,12 +745,12 @@ class AutoConfig(object):
if vpp_main_core != 0:
all_workers += [(vpp_main_core, vpp_main_core)]
all_workers += vpp_workers
- isolated_cpus = ''
+ isolated_cpus = ""
for idx, worker in enumerate(all_workers):
if worker is None:
continue
if idx > 0:
- isolated_cpus += ','
+ isolated_cpus += ","
if worker[0] == worker[1]:
isolated_cpus += "{}".format(worker[0])
else:
@@ -737,11 +758,10 @@ class AutoConfig(object):
vppgrb = VppGrubUtil(node)
current_cmdline = vppgrb.get_current_cmdline()
- if 'grub' not in node:
- node['grub'] = {}
- node['grub']['current_cmdline'] = current_cmdline
- node['grub']['default_cmdline'] = \
- vppgrb.apply_cmdline(node, isolated_cpus)
+ if "grub" not in node:
+ node["grub"] = {}
+ node["grub"]["current_cmdline"] = current_cmdline
+ node["grub"]["default_cmdline"] = vppgrb.apply_cmdline(node, isolated_cpus)
self.updateconfig()
@@ -756,14 +776,14 @@ class AutoConfig(object):
hpg = VppHugePageUtil(node)
max_map_count, shmmax = hpg.get_huge_page_config()
- node['hugepages']['max_map_count'] = max_map_count
- node['hugepages']['shmax'] = shmmax
+ node["hugepages"]["max_map_count"] = max_map_count
+ node["hugepages"]["shmax"] = shmmax
total, free, size, memtotal, memfree = hpg.get_actual_huge_pages()
- node['hugepages']['actual_total'] = total
- node['hugepages']['free'] = free
- node['hugepages']['size'] = size
- node['hugepages']['memtotal'] = memtotal
- node['hugepages']['memfree'] = memfree
+ node["hugepages"]["actual_total"] = total
+ node["hugepages"]["free"] = free
+ node["hugepages"]["size"] = size
+ node["hugepages"]["memtotal"] = memtotal
+ node["hugepages"]["memfree"] = memfree
self.updateconfig()
@@ -782,14 +802,14 @@ class AutoConfig(object):
# Get the total number of isolated CPUs
current_iso_cpus = 0
- iso_cpur = re.findall(r'isolcpus=[\w+\-,]+', current_cmdline)
+ iso_cpur = re.findall(r"isolcpus=[\w+\-,]+", current_cmdline)
iso_cpurl = len(iso_cpur)
if iso_cpurl > 0:
iso_cpu_str = iso_cpur[0]
- iso_cpu_str = iso_cpu_str.split('=')[1]
- iso_cpul = iso_cpu_str.split(',')
+ iso_cpu_str = iso_cpu_str.split("=")[1]
+ iso_cpul = iso_cpu_str.split(",")
for iso_cpu in iso_cpul:
- isocpuspl = iso_cpu.split('-')
+ isocpuspl = iso_cpu.split("-")
if len(isocpuspl) == 1:
current_iso_cpus += 1
else:
@@ -800,11 +820,11 @@ class AutoConfig(object):
else:
current_iso_cpus += second - first
- if 'grub' not in node:
- node['grub'] = {}
- node['grub']['current_cmdline'] = current_cmdline
- node['grub']['default_cmdline'] = default_cmdline
- node['grub']['current_iso_cpus'] = current_iso_cpus
+ if "grub" not in node:
+ node["grub"] = {}
+ node["grub"]["current_cmdline"] = current_cmdline
+ node["grub"]["default_cmdline"] = default_cmdline
+ node["grub"]["current_iso_cpus"] = current_iso_cpus
self.updateconfig()
@@ -822,11 +842,11 @@ class AutoConfig(object):
vpp.get_all_devices()
# Save the device information
- node['devices'] = {}
- node['devices']['dpdk_devices'] = vpp.get_dpdk_devices()
- node['devices']['kernel_devices'] = vpp.get_kernel_devices()
- node['devices']['other_devices'] = vpp.get_other_devices()
- node['devices']['linkup_devices'] = vpp.get_link_up_devices()
+ node["devices"] = {}
+ node["devices"]["dpdk_devices"] = vpp.get_dpdk_devices()
+ node["devices"]["kernel_devices"] = vpp.get_kernel_devices()
+ node["devices"]["other_devices"] = vpp.get_other_devices()
+ node["devices"]["linkup_devices"] = vpp.get_link_up_devices()
def get_devices_per_node(self):
"""
@@ -856,20 +876,25 @@ class AutoConfig(object):
:rtype: list
"""
- cmd = 'lscpu -p'
+ cmd = "lscpu -p"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {}'.
- format(cmd, node['host'], stderr))
+ raise RuntimeError(
+ "{} failed on node {} {}".format(cmd, node["host"], stderr)
+ )
pcpus = []
- lines = stdout.split('\n')
+ lines = stdout.split("\n")
for line in lines:
- if line == '' or line[0] == '#':
+ if line == "" or line[0] == "#":
continue
- linesplit = line.split(',')
- layout = {'cpu': linesplit[0], 'core': linesplit[1],
- 'socket': linesplit[2], 'node': linesplit[3]}
+ linesplit = line.split(",")
+ layout = {
+ "cpu": linesplit[0],
+ "core": linesplit[1],
+ "socket": linesplit[2],
+ "node": linesplit[3],
+ }
# cpu, core, socket, node
pcpus.append(layout)
@@ -890,14 +915,14 @@ class AutoConfig(object):
# Get the cpu layout
layout = self.get_cpu_layout(node)
- node['cpu']['layout'] = layout
+ node["cpu"]["layout"] = layout
- cpuinfo = node['cpuinfo']
+ cpuinfo = node["cpuinfo"]
smt_enabled = CpuUtils.is_smt_enabled(cpuinfo)
- node['cpu']['smt_enabled'] = smt_enabled
+ node["cpu"]["smt_enabled"] = smt_enabled
# We don't want to write the cpuinfo
- node['cpuinfo'] = ""
+ node["cpuinfo"] = ""
# Write the config
self.updateconfig()
@@ -932,46 +957,59 @@ class AutoConfig(object):
:type numa_nodes: list
"""
- print("\nYour system has {} core(s) and {} Numa Nodes.".
- format(total_cpus, len(numa_nodes)))
- print("To begin, we suggest not reserving any cores for "
- "VPP or other processes.")
- print("Then to improve performance start reserving cores and "
- "adding queues as needed.")
+ print(
+ "\nYour system has {} core(s) and {} Numa Nodes.".format(
+ total_cpus, len(numa_nodes)
+ )
+ )
+ print(
+ "To begin, we suggest not reserving any cores for "
+ "VPP or other processes."
+ )
+ print(
+ "Then to improve performance start reserving cores and "
+ "adding queues as needed."
+ )
# Leave 1 for the general system
total_cpus -= 1
max_vpp_cpus = min(total_cpus, 4)
total_vpp_cpus = 0
if max_vpp_cpus > 0:
- question = "\nHow many core(s) shall we reserve for " \
- "VPP [0-{}][0]? ".format(max_vpp_cpus)
+ question = (
+ "\nHow many core(s) shall we reserve for "
+ "VPP [0-{}][0]? ".format(max_vpp_cpus)
+ )
total_vpp_cpus = self._ask_user_range(question, 0, max_vpp_cpus, 0)
- node['cpu']['total_vpp_cpus'] = total_vpp_cpus
+ node["cpu"]["total_vpp_cpus"] = total_vpp_cpus
total_other_cpus = 0
max_other_cores = total_cpus - total_vpp_cpus
if max_other_cores > 0:
- question = 'How many core(s) do you want to reserve for ' \
- 'processes other than VPP? [0-{}][0]? '. format(str(max_other_cores))
+ question = (
+ "How many core(s) do you want to reserve for "
+ "processes other than VPP? [0-{}][0]? ".format(str(max_other_cores))
+ )
total_other_cpus = self._ask_user_range(question, 0, max_other_cores, 0)
- node['cpu']['total_other_cpus'] = total_other_cpus
+ node["cpu"]["total_other_cpus"] = total_other_cpus
max_main_cpus = total_cpus - total_vpp_cpus - total_other_cpus
reserve_vpp_main_core = False
if max_main_cpus > 0:
question = "Should we reserve 1 core for the VPP Main thread? "
question += "[y/N]? "
- answer = self._ask_user_yn(question, 'n')
- if answer == 'y':
+ answer = self._ask_user_yn(question, "n")
+ if answer == "y":
reserve_vpp_main_core = True
- node['cpu']['reserve_vpp_main_core'] = reserve_vpp_main_core
- node['cpu']['vpp_main_core'] = 0
+ node["cpu"]["reserve_vpp_main_core"] = reserve_vpp_main_core
+ node["cpu"]["vpp_main_core"] = 0
- question = "How many RX queues per port shall we use for " \
- "VPP [1-4][1]? ".format(max_vpp_cpus)
+ question = (
+ "How many RX queues per port shall we use for "
+ "VPP [1-4][1]? ".format(max_vpp_cpus)
+ )
total_rx_queues = self._ask_user_range(question, 1, 4, 1)
- node['cpu']['total_rx_queues'] = total_rx_queues
+ node["cpu"]["total_rx_queues"] = total_rx_queues
def modify_cpu(self, ask_questions=True):
"""
@@ -995,50 +1033,50 @@ class AutoConfig(object):
# Assume the number of cpus per slice is always the same as the
# first slice
- first_node = '0'
+ first_node = "0"
for cpu in cpu_layout:
- if cpu['node'] != first_node:
+ if cpu["node"] != first_node:
break
total_cpus_per_slice += 1
# Get the total number of cpus, cores, and numa nodes from the
# cpu layout
for cpul in cpu_layout:
- numa_node = cpul['node']
- core = cpul['core']
- cpu = cpul['cpu']
+ numa_node = cpul["node"]
+ core = cpul["core"]
+ cpu = cpul["cpu"]
total_cpus += 1
if numa_node not in cpus_per_node:
cpus_per_node[numa_node] = []
cpuperslice = int(cpu) % total_cpus_per_slice
if cpuperslice == 0:
- cpus_per_node[numa_node].append((int(cpu), int(cpu) +
- total_cpus_per_slice - 1))
+ cpus_per_node[numa_node].append(
+ (int(cpu), int(cpu) + total_cpus_per_slice - 1)
+ )
if numa_node not in numa_nodes:
numa_nodes.append(numa_node)
if core not in cores:
cores.append(core)
- node['cpu']['cpus_per_node'] = cpus_per_node
+ node["cpu"]["cpus_per_node"] = cpus_per_node
# Ask the user some questions
if ask_questions and total_cpus >= 4:
self._modify_cpu_questions(node, total_cpus, numa_nodes)
# Populate the interfaces with the numa node
- if 'interfaces' in node:
- ikeys = node['interfaces'].keys()
+ if "interfaces" in node:
+ ikeys = node["interfaces"].keys()
VPPUtil.get_interfaces_numa_node(node, *tuple(ikeys))
# We don't want to write the cpuinfo
- node['cpuinfo'] = ""
+ node["cpuinfo"] = ""
# Write the configs
self._update_auto_config()
self.updateconfig()
- def _modify_other_devices(self, node,
- other_devices, kernel_devices, dpdk_devices):
+ def _modify_other_devices(self, node, other_devices, kernel_devices, dpdk_devices):
"""
Modify the devices configuration, asking for the user for the values.
@@ -1046,31 +1084,31 @@ class AutoConfig(object):
odevices_len = len(other_devices)
if odevices_len > 0:
- print("\nThese device(s) are currently NOT being used "
- "by VPP or the OS.\n")
+ print(
+ "\nThese device(s) are currently NOT being used " "by VPP or the OS.\n"
+ )
VppPCIUtil.show_vpp_devices(other_devices, show_interfaces=False)
question = "\nWould you like to give any of these devices"
question += " back to the OS [Y/n]? "
- answer = self._ask_user_yn(question, 'Y')
- if answer == 'y':
+ answer = self._ask_user_yn(question, "Y")
+ if answer == "y":
vppd = {}
for dit in other_devices.items():
dvid = dit[0]
device = dit[1]
- question = "Would you like to use device {} for". \
- format(dvid)
+ question = "Would you like to use device {} for".format(dvid)
question += " the OS [y/N]? "
- answer = self._ask_user_yn(question, 'n')
- if answer == 'y':
- if 'unused' in device and len(
- device['unused']) != 0 and \
- device['unused'][0] != '':
- driver = device['unused'][0]
- ret = VppPCIUtil.bind_vpp_device(
- node, driver, dvid)
+ answer = self._ask_user_yn(question, "n")
+ if answer == "y":
+ if (
+ "unused" in device
+ and len(device["unused"]) != 0
+ and device["unused"][0] != ""
+ ):
+ driver = device["unused"][0]
+ ret = VppPCIUtil.bind_vpp_device(node, driver, dvid)
if ret:
- logging.debug(
- 'Could not bind device {}'.format(dvid))
+ logging.debug("Could not bind device {}".format(dvid))
else:
vppd[dvid] = device
for dit in vppd.items():
@@ -1081,34 +1119,35 @@ class AutoConfig(object):
odevices_len = len(other_devices)
if odevices_len > 0:
- print("\nThese device(s) are still NOT being used "
- "by VPP or the OS.\n")
+ print("\nThese device(s) are still NOT being used " "by VPP or the OS.\n")
VppPCIUtil.show_vpp_devices(other_devices, show_interfaces=False)
question = "\nWould you like use any of these for VPP [y/N]? "
- answer = self._ask_user_yn(question, 'N')
- if answer == 'y':
+ answer = self._ask_user_yn(question, "N")
+ if answer == "y":
vppd = {}
for dit in other_devices.items():
dvid = dit[0]
device = dit[1]
question = "Would you like to use device {} ".format(dvid)
question += "for VPP [y/N]? "
- answer = self._ask_user_yn(question, 'n')
- if answer == 'y':
+ answer = self._ask_user_yn(question, "n")
+ if answer == "y":
vppd[dvid] = device
for dit in vppd.items():
dvid = dit[0]
device = dit[1]
- if 'unused' in device and len(device['unused']) != 0 and \
- device['unused'][0] != '':
- driver = device['unused'][0]
+ if (
+ "unused" in device
+ and len(device["unused"]) != 0
+ and device["unused"][0] != ""
+ ):
+ driver = device["unused"][0]
logging.debug(
- 'Binding device {} to driver {}'.format(dvid,
- driver))
+ "Binding device {} to driver {}".format(dvid, driver)
+ )
ret = VppPCIUtil.bind_vpp_device(node, driver, dvid)
if ret:
- logging.debug(
- 'Could not bind device {}'.format(dvid))
+ logging.debug("Could not bind device {}".format(dvid))
else:
dpdk_devices[dvid] = device
del other_devices[dvid]
@@ -1121,22 +1160,23 @@ class AutoConfig(object):
for i in self._nodes.items():
node = i[1]
- devices = node['devices']
- all_devices = devices['other_devices']
- all_devices.update(devices['dpdk_devices'])
- all_devices.update(devices['kernel_devices'])
+ devices = node["devices"]
+ all_devices = devices["other_devices"]
+ all_devices.update(devices["dpdk_devices"])
+ all_devices.update(devices["kernel_devices"])
current_ifcs = {}
interfaces = {}
- if 'interfaces' in node:
- current_ifcs = node['interfaces']
+ if "interfaces" in node:
+ current_ifcs = node["interfaces"]
if current_ifcs:
for ifc in current_ifcs.values():
- dvid = ifc['pci_address']
+ dvid = ifc["pci_address"]
if dvid in all_devices:
- VppPCIUtil.vpp_create_interface(interfaces, dvid,
- all_devices[dvid])
- node['interfaces'] = interfaces
+ VppPCIUtil.vpp_create_interface(
+ interfaces, dvid, all_devices[dvid]
+ )
+ node["interfaces"] = interfaces
self.updateconfig()
@@ -1148,86 +1188,98 @@ class AutoConfig(object):
for i in self._nodes.items():
node = i[1]
- devices = node['devices']
- other_devices = devices['other_devices']
- kernel_devices = devices['kernel_devices']
- dpdk_devices = devices['dpdk_devices']
+ devices = node["devices"]
+ other_devices = devices["other_devices"]
+ kernel_devices = devices["kernel_devices"]
+ dpdk_devices = devices["dpdk_devices"]
if other_devices:
- self._modify_other_devices(node, other_devices,
- kernel_devices, dpdk_devices)
+ self._modify_other_devices(
+ node, other_devices, kernel_devices, dpdk_devices
+ )
# Get the devices again for this node
self._get_device(node)
- devices = node['devices']
- kernel_devices = devices['kernel_devices']
- dpdk_devices = devices['dpdk_devices']
+ devices = node["devices"]
+ kernel_devices = devices["kernel_devices"]
+ dpdk_devices = devices["dpdk_devices"]
klen = len(kernel_devices)
if klen > 0:
print("\nThese devices are safe to be used with VPP.\n")
VppPCIUtil.show_vpp_devices(kernel_devices)
- question = "\nWould you like to use any of these " \
- "device(s) for VPP [y/N]? "
- answer = self._ask_user_yn(question, 'n')
- if answer == 'y':
+ question = (
+ "\nWould you like to use any of these " "device(s) for VPP [y/N]? "
+ )
+ answer = self._ask_user_yn(question, "n")
+ if answer == "y":
vppd = {}
for dit in kernel_devices.items():
dvid = dit[0]
device = dit[1]
question = "Would you like to use device {} ".format(dvid)
question += "for VPP [y/N]? "
- answer = self._ask_user_yn(question, 'n')
- if answer == 'y':
+ answer = self._ask_user_yn(question, "n")
+ if answer == "y":
vppd[dvid] = device
for dit in vppd.items():
dvid = dit[0]
device = dit[1]
- if 'unused' in device and len(
- device['unused']) != 0 and device['unused'][0] != '':
- driver = device['unused'][0]
- question = "Would you like to bind the driver {} for {} [y/N]? ".format(driver, dvid)
- answer = self._ask_user_yn(question, 'n')
- if answer == 'y':
- logging.debug('Binding device {} to driver {}'.format(dvid, driver))
+ if (
+ "unused" in device
+ and len(device["unused"]) != 0
+ and device["unused"][0] != ""
+ ):
+ driver = device["unused"][0]
+ question = "Would you like to bind the driver {} for {} [y/N]? ".format(
+ driver, dvid
+ )
+ answer = self._ask_user_yn(question, "n")
+ if answer == "y":
+ logging.debug(
+ "Binding device {} to driver {}".format(
+ dvid, driver
+ )
+ )
ret = VppPCIUtil.bind_vpp_device(node, driver, dvid)
if ret:
- logging.debug('Could not bind device {}'.format(dvid))
+ logging.debug(
+ "Could not bind device {}".format(dvid)
+ )
dpdk_devices[dvid] = device
del kernel_devices[dvid]
dlen = len(dpdk_devices)
if dlen > 0:
print("\nThese device(s) are already using DPDK.\n")
- VppPCIUtil.show_vpp_devices(dpdk_devices,
- show_interfaces=False)
+ VppPCIUtil.show_vpp_devices(dpdk_devices, show_interfaces=False)
question = "\nWould you like to remove any of "
question += "these device(s) [y/N]? "
- answer = self._ask_user_yn(question, 'n')
- if answer == 'y':
+ answer = self._ask_user_yn(question, "n")
+ if answer == "y":
vppdl = {}
for dit in dpdk_devices.items():
dvid = dit[0]
device = dit[1]
- question = "Would you like to remove {} [y/N]? ". \
- format(dvid)
- answer = self._ask_user_yn(question, 'n')
- if answer == 'y':
+ question = "Would you like to remove {} [y/N]? ".format(dvid)
+ answer = self._ask_user_yn(question, "n")
+ if answer == "y":
vppdl[dvid] = device
for dit in vppdl.items():
dvid = dit[0]
device = dit[1]
- if 'unused' in device and len(
- device['unused']) != 0 and device['unused'][0] != '':
- driver = device['unused'][0]
+ if (
+ "unused" in device
+ and len(device["unused"]) != 0
+ and device["unused"][0] != ""
+ ):
+ driver = device["unused"][0]
logging.debug(
- 'Binding device {} to driver {}'.format(
- dvid, driver))
- ret = VppPCIUtil.bind_vpp_device(node, driver,
- dvid)
+ "Binding device {} to driver {}".format(dvid, driver)
+ )
+ ret = VppPCIUtil.bind_vpp_device(node, driver, dvid)
if ret:
- logging.debug(
- 'Could not bind device {}'.format(dvid))
+ logging.debug("Could not bind device {}".format(dvid))
else:
kernel_devices[dvid] = device
del dpdk_devices[dvid]
@@ -1237,7 +1289,7 @@ class AutoConfig(object):
dvid = dit[0]
device = dit[1]
VppPCIUtil.vpp_create_interface(interfaces, dvid, device)
- node['interfaces'] = interfaces
+ node["interfaces"] = interfaces
self._update_auto_config()
self.updateconfig()
@@ -1251,29 +1303,27 @@ class AutoConfig(object):
for i in self._nodes.items():
node = i[1]
- total = node['hugepages']['actual_total']
- free = node['hugepages']['free']
- size = node['hugepages']['size']
- memfree = node['hugepages']['memfree'].split(' ')[0]
- hugesize = int(size.split(' ')[0])
+ total = node["hugepages"]["actual_total"]
+ free = node["hugepages"]["free"]
+ size = node["hugepages"]["size"]
+ memfree = node["hugepages"]["memfree"].split(" ")[0]
+ hugesize = int(size.split(" ")[0])
# The max number of huge pages should be no more than
# 70% of total free memory
maxpages = (int(memfree) * MAX_PERCENT_FOR_HUGE_PAGES // 100) // hugesize
- print("\nThere currently {} {} huge pages free.".format(
- free, size))
- question = "Do you want to reconfigure the number of " \
- "huge pages [y/N]? "
- answer = self._ask_user_yn(question, 'n')
- if answer == 'n':
- node['hugepages']['total'] = total
+ print("\nThere currently {} {} huge pages free.".format(free, size))
+ question = "Do you want to reconfigure the number of " "huge pages [y/N]? "
+ answer = self._ask_user_yn(question, "n")
+ if answer == "n":
+ node["hugepages"]["total"] = total
continue
- print("\nThere currently a total of {} huge pages.".
- format(total))
- question = "How many huge pages do you want [{} - {}][{}]? ". \
- format(MIN_TOTAL_HUGE_PAGES, maxpages, MIN_TOTAL_HUGE_PAGES)
+ print("\nThere currently a total of {} huge pages.".format(total))
+ question = "How many huge pages do you want [{} - {}][{}]? ".format(
+ MIN_TOTAL_HUGE_PAGES, maxpages, MIN_TOTAL_HUGE_PAGES
+ )
answer = self._ask_user_range(question, 1024, maxpages, 1024)
- node['hugepages']['total'] = str(answer)
+ node["hugepages"]["total"] = str(answer)
# Update auto-config.yaml
self._update_auto_config()
@@ -1298,21 +1348,25 @@ class AutoConfig(object):
for i in self._nodes.items():
node = i[1]
- question = "\nHow many active-open / tcp client sessions are " \
- "expected [0-10000000][0]? "
+ question = (
+ "\nHow many active-open / tcp client sessions are "
+ "expected [0-10000000][0]? "
+ )
answer = self._ask_user_range(question, 0, 10000000, 0)
# Less than 10K is equivalent to 0
if int(answer) < 10000:
answer = 0
- node['tcp']['active_open_sessions'] = answer
+ node["tcp"]["active_open_sessions"] = answer
- question = "How many passive-open / tcp server sessions are " \
- "expected [0-10000000][0]? "
+ question = (
+ "How many passive-open / tcp server sessions are "
+ "expected [0-10000000][0]? "
+ )
answer = self._ask_user_range(question, 0, 10000000, 0)
# Less than 10K is equivalent to 0
if int(answer) < 10000:
answer = 0
- node['tcp']['passive_open_sessions'] = answer
+ node["tcp"]["passive_open_sessions"] = answer
# Update auto-config.yaml
self._update_auto_config()
@@ -1329,7 +1383,7 @@ class AutoConfig(object):
:type node: dict
"""
- print('\nWe are patching the node "{}":\n'.format(node['host']))
+ print('\nWe are patching the node "{}":\n'.format(node["host"]))
QemuUtils.build_qemu(node, force_install=True, apply_patch=True)
@staticmethod
@@ -1341,44 +1395,44 @@ class AutoConfig(object):
cpu = CpuUtils.get_cpu_info_per_node(node)
- item = 'Model name'
+ item = "Model name"
if item in cpu:
print("{:>20}: {}".format(item, cpu[item]))
- item = 'CPU(s)'
+ item = "CPU(s)"
if item in cpu:
print("{:>20}: {}".format(item, cpu[item]))
- item = 'Thread(s) per core'
+ item = "Thread(s) per core"
if item in cpu:
print("{:>20}: {}".format(item, cpu[item]))
- item = 'Core(s) per socket'
+ item = "Core(s) per socket"
if item in cpu:
print("{:>20}: {}".format(item, cpu[item]))
- item = 'Socket(s)'
+ item = "Socket(s)"
if item in cpu:
print("{:>20}: {}".format(item, cpu[item]))
- item = 'NUMA node(s)'
+ item = "NUMA node(s)"
numa_nodes = 0
if item in cpu:
numa_nodes = int(cpu[item])
for i in range(0, numa_nodes):
item = "NUMA node{} CPU(s)".format(i)
print("{:>20}: {}".format(item, cpu[item]))
- item = 'CPU max MHz'
+ item = "CPU max MHz"
if item in cpu:
print("{:>20}: {}".format(item, cpu[item]))
- item = 'CPU min MHz'
+ item = "CPU min MHz"
if item in cpu:
print("{:>20}: {}".format(item, cpu[item]))
- if node['cpu']['smt_enabled']:
- smt = 'Enabled'
+ if node["cpu"]["smt_enabled"]:
+ smt = "Enabled"
else:
- smt = 'Disabled'
- print("{:>20}: {}".format('SMT', smt))
+ smt = "Disabled"
+ print("{:>20}: {}".format("SMT", smt))
# VPP Threads
print("\nVPP Threads: (Name: Cpu Number)")
- vpp_processes = cpu['vpp_processes']
+ vpp_processes = cpu["vpp_processes"]
for i in vpp_processes.items():
print(" {:10}: {:4}".format(i[0], i[1]))
@@ -1389,8 +1443,8 @@ class AutoConfig(object):
"""
- if 'cpu' in node and 'total_mbufs' in node['cpu']:
- total_mbufs = node['cpu']['total_mbufs']
+ if "cpu" in node and "total_mbufs" in node["cpu"]:
+ total_mbufs = node["cpu"]["total_mbufs"]
if total_mbufs != 0:
print("Total Number of Buffers: {}".format(total_mbufs))
@@ -1412,16 +1466,14 @@ class AutoConfig(object):
dpdk_devs = vpp.get_dpdk_devices()
if len(dpdk_devs):
print("\nDevices bound to DPDK drivers:")
- vpp.show_vpp_devices(dpdk_devs, show_interfaces=True,
- show_header=False)
+ vpp.show_vpp_devices(dpdk_devs, show_interfaces=True, show_header=False)
else:
print("\nNo devices bound to DPDK drivers")
other_devs = vpp.get_other_devices()
if len(other_devs):
print("\nDevices not bound to Kernel or DPDK drivers:")
- vpp.show_vpp_devices(other_devs, show_interfaces=True,
- show_header=False)
+ vpp.show_vpp_devices(other_devs, show_interfaces=True, show_header=False)
else:
print("\nNo devices not bound to Kernel or DPDK drivers")
@@ -1436,28 +1488,33 @@ class AutoConfig(object):
print("None")
return
- print("{:30} {:4} {:4} {:7} {:4} {:7}".
- format('Name', 'Numa', 'RXQs',
- 'RXDescs', 'TXQs', 'TXDescs'))
+ print(
+ "{:30} {:4} {:4} {:7} {:4} {:7}".format(
+ "Name", "Numa", "RXQs", "RXDescs", "TXQs", "TXDescs"
+ )
+ )
for intf in sorted(interfaces.items()):
name = intf[0]
value = intf[1]
- if name == 'local0':
+ if name == "local0":
continue
- numa = rx_qs = rx_ds = tx_qs = tx_ds = ''
- if 'numa' in value:
- numa = int(value['numa'])
- if 'rx queues' in value:
- rx_qs = int(value['rx queues'])
- if 'rx descs' in value:
- rx_ds = int(value['rx descs'])
- if 'tx queues' in value:
- tx_qs = int(value['tx queues'])
- if 'tx descs' in value:
- tx_ds = int(value['tx descs'])
-
- print("{:30} {:>4} {:>4} {:>7} {:>4} {:>7}".
- format(name, numa, rx_qs, rx_ds, tx_qs, tx_ds))
+ numa = rx_qs = rx_ds = tx_qs = tx_ds = ""
+ if "numa" in value:
+ numa = int(value["numa"])
+ if "rx queues" in value:
+ rx_qs = int(value["rx queues"])
+ if "rx descs" in value:
+ rx_ds = int(value["rx descs"])
+ if "tx queues" in value:
+ tx_qs = int(value["tx queues"])
+ if "tx descs" in value:
+ tx_ds = int(value["tx descs"])
+
+ print(
+ "{:30} {:>4} {:>4} {:>7} {:>4} {:>7}".format(
+ name, numa, rx_qs, rx_ds, tx_qs, tx_ds
+ )
+ )
@staticmethod
def hugepage_info(node):
@@ -1476,7 +1533,7 @@ class AutoConfig(object):
:returns: boolean
"""
- if 'interfaces' in node and len(node['interfaces']):
+ if "interfaces" in node and len(node["interfaces"]):
return True
else:
return False
@@ -1493,30 +1550,33 @@ class AutoConfig(object):
min_sys_res = True
# CPUs
- if 'layout' in node['cpu']:
- total_cpus = len(node['cpu']['layout'])
+ if "layout" in node["cpu"]:
+ total_cpus = len(node["cpu"]["layout"])
if total_cpus < 2:
- print("\nThere is only {} CPU(s) available on this system. "
- "This is not enough to run VPP.".format(total_cpus))
+ print(
+ "\nThere is only {} CPU(s) available on this system. "
+ "This is not enough to run VPP.".format(total_cpus)
+ )
min_sys_res = False
# System Memory
- if 'free' in node['hugepages'] and \
- 'memfree' in node['hugepages'] and \
- 'size' in node['hugepages']:
- free = node['hugepages']['free']
- memfree = float(node['hugepages']['memfree'].split(' ')[0])
- hugesize = float(node['hugepages']['size'].split(' ')[0])
+ if (
+ "free" in node["hugepages"]
+ and "memfree" in node["hugepages"]
+ and "size" in node["hugepages"]
+ ):
+ free = node["hugepages"]["free"]
+ memfree = float(node["hugepages"]["memfree"].split(" ")[0])
+ hugesize = float(node["hugepages"]["size"].split(" ")[0])
memhugepages = MIN_TOTAL_HUGE_PAGES * hugesize
percentmemhugepages = (memhugepages / memfree) * 100
- if free is '0' and \
- percentmemhugepages > MAX_PERCENT_FOR_HUGE_PAGES:
+ if free is "0" and percentmemhugepages > MAX_PERCENT_FOR_HUGE_PAGES:
print(
"\nThe System has only {} of free memory. You will not "
"be able to allocate enough Huge Pages for VPP.".format(
- int(
- memfree))
+ int(memfree)
+ )
)
min_sys_res = False
@@ -1541,11 +1601,9 @@ class AutoConfig(object):
# Grub
print("\nGrub Command Line:")
- if 'grub' in node:
- print(" Current: {}".format(
- node['grub']['current_cmdline']))
- print(" Configured: {}".format(
- node['grub']['default_cmdline']))
+ if "grub" in node:
+ print(" Current: {}".format(node["grub"]["current_cmdline"]))
+ print(" Configured: {}".format(node["grub"]["default_cmdline"]))
# Huge Pages
print("\nHuge Pages:")
@@ -1586,17 +1644,18 @@ class AutoConfig(object):
interfaces_with_ip = []
for intf in sorted(interfaces.items()):
name = intf[0]
- if name == 'local0':
+ if name == "local0":
continue
- question = "Would you like add address to " \
- "interface {} [Y/n]? ".format(name)
- answer = self._ask_user_yn(question, 'y')
- if answer == 'y':
+ question = "Would you like add address to " "interface {} [Y/n]? ".format(
+ name
+ )
+ answer = self._ask_user_yn(question, "y")
+ if answer == "y":
address = {}
addr = self._ask_user_ipv4()
- address['name'] = name
- address['addr'] = addr
+ address["name"] = name
+ address["addr"] = addr
interfaces_with_ip.append(address)
return interfaces_with_ip
@@ -1618,40 +1677,37 @@ class AutoConfig(object):
for items in sorted(current_ints.items()):
name = items[0]
value = items[1]
- if 'address' not in value:
- address = 'Not Set'
+ if "address" not in value:
+ address = "Not Set"
else:
- address = value['address']
- print("{:30} {:20} {:10}".format(name, address,
- value['state']))
- question = "\nWould you like to keep this configuration " \
- "[Y/n]? "
- answer = self._ask_user_yn(question, 'y')
- if answer == 'y':
+ address = value["address"]
+ print("{:30} {:20} {:10}".format(name, address, value["state"]))
+ question = "\nWould you like to keep this configuration " "[Y/n]? "
+ answer = self._ask_user_yn(question, "y")
+ if answer == "y":
continue
else:
- print("\nThere are currently no interfaces with IP "
- "addresses.")
+ print("\nThere are currently no interfaces with IP " "addresses.")
# Create a script that add the ip addresses to the interfaces
# and brings the interfaces up
ints_with_addrs = self._ipv4_interface_setup_questions(node)
- content = ''
+ content = ""
for ints in ints_with_addrs:
- name = ints['name']
- addr = ints['addr']
- setipstr = 'set int ip address {} {}\n'.format(name, addr)
- setintupstr = 'set int state {} up\n'.format(name)
+ name = ints["name"]
+ addr = ints["addr"]
+ setipstr = "set int ip address {} {}\n".format(name, addr)
+ setintupstr = "set int state {} up\n".format(name)
content += setipstr + setintupstr
# Write the content to the script
- rootdir = node['rootdir']
- filename = rootdir + '/vpp/vpp-config/scripts/set_int_ipv4_and_up'
- with open(filename, 'w+') as sfile:
+ rootdir = node["rootdir"]
+ filename = rootdir + "/vpp/vpp-config/scripts/set_int_ipv4_and_up"
+ with open(filename, "w+") as sfile:
sfile.write(content)
# Execute the script
- cmd = 'vppctl exec {}'.format(filename)
+ cmd = "vppctl exec {}".format(filename)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
logging.debug(stderr)
@@ -1679,12 +1735,13 @@ class AutoConfig(object):
# First delete all the Virtual interfaces
for intf in sorted(interfaces.items()):
name = intf[0]
- if name[:7] == 'Virtual':
- cmd = 'vppctl delete vhost-user {}'.format(name)
+ if name[:7] == "Virtual":
+ cmd = "vppctl delete vhost-user {}".format(name)
(ret, stdout, stderr) = vpputl.exec_command(cmd)
if ret != 0:
- logging.debug('{} failed on node {} {}'.format(
- cmd, node['host'], stderr))
+ logging.debug(
+ "{} failed on node {} {}".format(cmd, node["host"], stderr)
+ )
# Create a virtual interface, for each interface the user wants to use
interfaces = vpputl.get_hardware(node)
@@ -1694,36 +1751,38 @@ class AutoConfig(object):
inum = 1
for intf in sorted(interfaces.items()):
name = intf[0]
- if name == 'local0':
+ if name == "local0":
continue
- question = "Would you like connect this interface {} to " \
- "the VM [Y/n]? ".format(name)
- answer = self._ask_user_yn(question, 'y')
- if answer == 'y':
- sockfilename = '/var/run/vpp/{}.sock'.format(
- name.replace('/', '_'))
+ question = (
+ "Would you like connect this interface {} to "
+ "the VM [Y/n]? ".format(name)
+ )
+ answer = self._ask_user_yn(question, "y")
+ if answer == "y":
+ sockfilename = "/var/run/vpp/{}.sock".format(name.replace("/", "_"))
if os.path.exists(sockfilename):
os.remove(sockfilename)
- cmd = 'vppctl create vhost-user socket {} server'.format(
- sockfilename)
+ cmd = "vppctl create vhost-user socket {} server".format(sockfilename)
(ret, stdout, stderr) = vpputl.exec_command(cmd)
if ret != 0:
raise RuntimeError(
- "Couldn't execute the command {}, {}.".format(cmd,
- stderr))
- vintname = stdout.rstrip('\r\n')
+ "Couldn't execute the command {}, {}.".format(cmd, stderr)
+ )
+ vintname = stdout.rstrip("\r\n")
- cmd = 'chmod 777 {}'.format(sockfilename)
+ cmd = "chmod 777 {}".format(sockfilename)
(ret, stdout, stderr) = vpputl.exec_command(cmd)
if ret != 0:
raise RuntimeError(
- "Couldn't execute the command {}, {}.".format(cmd,
- stderr))
-
- interface = {'name': name,
- 'virtualinterface': '{}'.format(vintname),
- 'bridge': '{}'.format(inum)}
+ "Couldn't execute the command {}, {}.".format(cmd, stderr)
+ )
+
+ interface = {
+ "name": name,
+ "virtualinterface": "{}".format(vintname),
+ "bridge": "{}".format(inum),
+ }
inum += 1
interfaces_with_virtual_interfaces.append(interface)
@@ -1743,49 +1802,58 @@ class AutoConfig(object):
print("\nThis the current bridge configuration:")
VPPUtil.show_bridge(node)
question = "\nWould you like to keep this configuration [Y/n]? "
- answer = self._ask_user_yn(question, 'y')
- if answer == 'y':
+ answer = self._ask_user_yn(question, "y")
+ if answer == "y":
continue
# Create a script that builds a bridge configuration with
# physical interfaces and virtual interfaces
ints_with_vints = self._create_vints_questions(node)
- content = ''
+ content = ""
for intf in ints_with_vints:
- vhoststr = '\n'.join([
- 'comment { The following command creates the socket }',
- 'comment { and returns a virtual interface }',
- 'comment {{ create vhost-user socket '
- '/var/run/vpp/sock{}.sock server }}\n'.format(
- intf['bridge'])
- ])
-
- setintdnstr = 'set interface state {} down\n'.format(
- intf['name'])
-
- setintbrstr = 'set interface l2 bridge {} {}\n'.format(
- intf['name'], intf['bridge'])
- setvintbrstr = 'set interface l2 bridge {} {}\n'.format(
- intf['virtualinterface'], intf['bridge'])
+ vhoststr = "\n".join(
+ [
+ "comment { The following command creates the socket }",
+ "comment { and returns a virtual interface }",
+ "comment {{ create vhost-user socket "
+ "/var/run/vpp/sock{}.sock server }}\n".format(intf["bridge"]),
+ ]
+ )
+
+ setintdnstr = "set interface state {} down\n".format(intf["name"])
+
+ setintbrstr = "set interface l2 bridge {} {}\n".format(
+ intf["name"], intf["bridge"]
+ )
+ setvintbrstr = "set interface l2 bridge {} {}\n".format(
+ intf["virtualinterface"], intf["bridge"]
+ )
# set interface state VirtualEthernet/0/0/0 up
- setintvststr = 'set interface state {} up\n'.format(
- intf['virtualinterface'])
+ setintvststr = "set interface state {} up\n".format(
+ intf["virtualinterface"]
+ )
# set interface state VirtualEthernet/0/0/0 down
- setintupstr = 'set interface state {} up\n'.format(
- intf['name'])
-
- content += vhoststr + setintdnstr + setintbrstr + setvintbrstr + setintvststr + setintupstr
+ setintupstr = "set interface state {} up\n".format(intf["name"])
+
+ content += (
+ vhoststr
+ + setintdnstr
+ + setintbrstr
+ + setvintbrstr
+ + setintvststr
+ + setintupstr
+ )
# Write the content to the script
- rootdir = node['rootdir']
- filename = rootdir + '/vpp/vpp-config/scripts/create_vms_and_connect_to_vpp'
- with open(filename, 'w+') as sfile:
+ rootdir = node["rootdir"]
+ filename = rootdir + "/vpp/vpp-config/scripts/create_vms_and_connect_to_vpp"
+ with open(filename, "w+") as sfile:
sfile.write(content)
# Execute the script
- cmd = 'vppctl exec {}'.format(filename)
+ cmd = "vppctl exec {}".format(filename)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
logging.debug(stderr)
@@ -1813,12 +1881,13 @@ class AutoConfig(object):
# First delete all the Virtual interfaces
for intf in sorted(interfaces.items()):
name = intf[0]
- if name[:7] == 'Virtual':
- cmd = 'vppctl delete vhost-user {}'.format(name)
+ if name[:7] == "Virtual":
+ cmd = "vppctl delete vhost-user {}".format(name)
(ret, stdout, stderr) = vpputl.exec_command(cmd)
if ret != 0:
- logging.debug('{} failed on node {} {}'.format(
- cmd, node['host'], stderr))
+ logging.debug(
+ "{} failed on node {} {}".format(cmd, node["host"], stderr)
+ )
# Create a virtual interface, for each interface the user wants to use
interfaces = vpputl.get_hardware(node)
@@ -1828,39 +1897,45 @@ class AutoConfig(object):
inum = 1
while True:
- print('\nPlease pick one interface to connect to the iperf VM.')
+ print("\nPlease pick one interface to connect to the iperf VM.")
for intf in sorted(interfaces.items()):
name = intf[0]
- if name == 'local0':
+ if name == "local0":
continue
- question = "Would you like connect this interface {} to " \
- "the VM [y/N]? ".format(name)
- answer = self._ask_user_yn(question, 'n')
- if answer == 'y':
- self._sockfilename = '/var/run/vpp/{}.sock'.format(
- name.replace('/', '_'))
+ question = (
+ "Would you like connect this interface {} to "
+ "the VM [y/N]? ".format(name)
+ )
+ answer = self._ask_user_yn(question, "n")
+ if answer == "y":
+ self._sockfilename = "/var/run/vpp/{}.sock".format(
+ name.replace("/", "_")
+ )
if os.path.exists(self._sockfilename):
os.remove(self._sockfilename)
- cmd = 'vppctl create vhost-user socket {} server'.format(
- self._sockfilename)
+ cmd = "vppctl create vhost-user socket {} server".format(
+ self._sockfilename
+ )
(ret, stdout, stderr) = vpputl.exec_command(cmd)
if ret != 0:
raise RuntimeError(
- "Couldn't execute the command {}, {}.".format(
- cmd, stderr))
- vintname = stdout.rstrip('\r\n')
+ "Couldn't execute the command {}, {}.".format(cmd, stderr)
+ )
+ vintname = stdout.rstrip("\r\n")
- cmd = 'chmod 777 {}'.format(self._sockfilename)
+ cmd = "chmod 777 {}".format(self._sockfilename)
(ret, stdout, stderr) = vpputl.exec_command(cmd)
if ret != 0:
raise RuntimeError(
- "Couldn't execute the command {}, {}.".format(
- cmd, stderr))
-
- interface = {'name': name,
- 'virtualinterface': '{}'.format(vintname),
- 'bridge': '{}'.format(inum)}
+ "Couldn't execute the command {}, {}.".format(cmd, stderr)
+ )
+
+ interface = {
+ "name": name,
+ "virtualinterface": "{}".format(vintname),
+ "bridge": "{}".format(inum),
+ }
inum += 1
interfaces_with_virtual_interfaces.append(interface)
return interfaces_with_virtual_interfaces
@@ -1879,52 +1954,62 @@ class AutoConfig(object):
print("\nThis the current bridge configuration:")
ifaces = VPPUtil.show_bridge(node)
question = "\nWould you like to keep this configuration [Y/n]? "
- answer = self._ask_user_yn(question, 'y')
- if answer == 'y':
- self._sockfilename = '/var/run/vpp/{}.sock'.format(
- ifaces[0]['name'].replace('/', '_'))
+ answer = self._ask_user_yn(question, "y")
+ if answer == "y":
+ self._sockfilename = "/var/run/vpp/{}.sock".format(
+ ifaces[0]["name"].replace("/", "_")
+ )
if os.path.exists(self._sockfilename):
continue
# Create a script that builds a bridge configuration with
# physical interfaces and virtual interfaces
ints_with_vints = self._iperf_vm_questions(node)
- content = ''
+ content = ""
for intf in ints_with_vints:
- vhoststr = '\n'.join([
- 'comment { The following command creates the socket }',
- 'comment { and returns a virtual interface }',
- 'comment {{ create vhost-user socket '
- '/var/run/vpp/sock{}.sock server }}\n'.format(
- intf['bridge'])
- ])
-
- setintdnstr = 'set interface state {} down\n'.format(
- intf['name'])
-
- setintbrstr = 'set interface l2 bridge {} {}\n'.format(
- intf['name'], intf['bridge'])
- setvintbrstr = 'set interface l2 bridge {} {}\n'.format(
- intf['virtualinterface'], intf['bridge'])
+ vhoststr = "\n".join(
+ [
+ "comment { The following command creates the socket }",
+ "comment { and returns a virtual interface }",
+ "comment {{ create vhost-user socket "
+ "/var/run/vpp/sock{}.sock server }}\n".format(intf["bridge"]),
+ ]
+ )
+
+ setintdnstr = "set interface state {} down\n".format(intf["name"])
+
+ setintbrstr = "set interface l2 bridge {} {}\n".format(
+ intf["name"], intf["bridge"]
+ )
+ setvintbrstr = "set interface l2 bridge {} {}\n".format(
+ intf["virtualinterface"], intf["bridge"]
+ )
# set interface state VirtualEthernet/0/0/0 up
- setintvststr = 'set interface state {} up\n'.format(
- intf['virtualinterface'])
+ setintvststr = "set interface state {} up\n".format(
+ intf["virtualinterface"]
+ )
# set interface state VirtualEthernet/0/0/0 down
- setintupstr = 'set interface state {} up\n'.format(
- intf['name'])
-
- content += vhoststr + setintdnstr + setintbrstr + setvintbrstr + setintvststr + setintupstr
+ setintupstr = "set interface state {} up\n".format(intf["name"])
+
+ content += (
+ vhoststr
+ + setintdnstr
+ + setintbrstr
+ + setvintbrstr
+ + setintvststr
+ + setintupstr
+ )
# Write the content to the script
- rootdir = node['rootdir']
- filename = rootdir + '/vpp/vpp-config/scripts/create_iperf_vm'
- with open(filename, 'w+') as sfile:
+ rootdir = node["rootdir"]
+ filename = rootdir + "/vpp/vpp-config/scripts/create_iperf_vm"
+ with open(filename, "w+") as sfile:
sfile.write(content)
# Execute the script
- cmd = 'vppctl exec {}'.format(filename)
+ cmd = "vppctl exec {}".format(filename)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
logging.debug(stderr)
@@ -1943,21 +2028,22 @@ class AutoConfig(object):
:type name: str
"""
- cmd = 'virsh list'
+ cmd = "virsh list"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
logging.debug(stderr)
raise RuntimeError(
- "Couldn't execute the command {} : {}".format(cmd, stderr))
+ "Couldn't execute the command {} : {}".format(cmd, stderr)
+ )
if re.findall(name, stdout):
- cmd = 'virsh destroy {}'.format(name)
+ cmd = "virsh destroy {}".format(name)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
logging.debug(stderr)
raise RuntimeError(
- "Couldn't execute the command {} : {}".format(
- cmd, stderr))
+ "Couldn't execute the command {} : {}".format(cmd, stderr)
+ )
def create_iperf_vm(self, vmname):
"""
@@ -1968,36 +2054,39 @@ class AutoConfig(object):
# Read the iperf VM template file
distro = VPPUtil.get_linux_distro()
- if distro[0] == 'Ubuntu':
- tfilename = \
- '{}/vpp/vpp-config/configs/iperf-ubuntu.xml.template'.format(
- self._rootdir)
+ if distro[0] == "Ubuntu":
+ tfilename = "{}/vpp/vpp-config/configs/iperf-ubuntu.xml.template".format(
+ self._rootdir
+ )
else:
- tfilename = \
- '{}/vpp/vpp-config/configs/iperf-centos.xml.template'.format(
- self._rootdir)
+ tfilename = "{}/vpp/vpp-config/configs/iperf-centos.xml.template".format(
+ self._rootdir
+ )
- with open(tfilename, 'r') as tfile:
+ with open(tfilename, "r") as tfile:
tcontents = tfile.read()
tfile.close()
# Add the variables
- imagename = '{}/vpp/vpp-config/{}'.format(
- self._rootdir, IPERFVM_IMAGE)
- isoname = '{}/vpp/vpp-config/{}'.format(self._rootdir, IPERFVM_ISO)
- tcontents = tcontents.format(vmname=vmname, imagename=imagename,
- isoname=isoname,
- vhostsocketname=self._sockfilename)
+ imagename = "{}/vpp/vpp-config/{}".format(self._rootdir, IPERFVM_IMAGE)
+ isoname = "{}/vpp/vpp-config/{}".format(self._rootdir, IPERFVM_ISO)
+ tcontents = tcontents.format(
+ vmname=vmname,
+ imagename=imagename,
+ isoname=isoname,
+ vhostsocketname=self._sockfilename,
+ )
# Write the xml
- ifilename = '{}/vpp/vpp-config/{}'.format(self._rootdir, IPERFVM_XML)
- with open(ifilename, 'w+') as ifile:
+ ifilename = "{}/vpp/vpp-config/{}".format(self._rootdir, IPERFVM_XML)
+ with open(ifilename, "w+") as ifile:
ifile.write(tcontents)
ifile.close()
- cmd = 'virsh create {}'.format(ifilename)
+ cmd = "virsh create {}".format(ifilename)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
logging.debug(stderr)
raise RuntimeError(
- "Couldn't execute the command {} : {}".format(cmd, stderr))
+ "Couldn't execute the command {} : {}".format(cmd, stderr)
+ )
diff --git a/extras/vpp_config/vpplib/CpuUtils.py b/extras/vpp_config/vpplib/CpuUtils.py
index 23f418d33be..f6ba3d74746 100644
--- a/extras/vpp_config/vpplib/CpuUtils.py
+++ b/extras/vpp_config/vpplib/CpuUtils.py
@@ -78,13 +78,14 @@ class CpuUtils(object):
# 1,1,0,0,,1,1,1,0
if ret != 0:
raise RuntimeError(
- "Failed to execute ssh command, ret: {} err: {}".format(
- ret, stderr))
- node['cpuinfo'] = list()
+ "Failed to execute ssh command, ret: {} err: {}".format(ret, stderr)
+ )
+ node["cpuinfo"] = list()
for line in stdout.split("\n"):
- if line != '' and line[0] != "#":
- node['cpuinfo'].append([CpuUtils.__str2int(x) for x in
- line.split(",")])
+ if line != "" and line[0] != "#":
+ node["cpuinfo"].append(
+ [CpuUtils.__str2int(x) for x in line.split(",")]
+ )
@staticmethod
def cpu_node_count(node):
@@ -137,13 +138,14 @@ class CpuUtils(object):
if smt_enabled and not smt_used:
cpu_list_len = len(cpu_list)
- cpu_list = cpu_list[:cpu_list_len // CpuUtils.NR_OF_THREADS]
+ cpu_list = cpu_list[: cpu_list_len // CpuUtils.NR_OF_THREADS]
return cpu_list
@staticmethod
- def cpu_slice_of_list_per_node(node, cpu_node, skip_cnt=0, cpu_cnt=0,
- smt_used=False):
+ def cpu_slice_of_list_per_node(
+ node, cpu_node, skip_cnt=0, cpu_cnt=0, smt_used=False
+ ):
"""Return string of node related list of CPU numbers.
:param node: Node dictionary with cpuinfo.
@@ -171,20 +173,20 @@ class CpuUtils(object):
cpu_cnt = cpu_list_len - skip_cnt
if smt_used:
- cpu_list_0 = cpu_list[:cpu_list_len // CpuUtils.NR_OF_THREADS]
- cpu_list_1 = cpu_list[cpu_list_len // CpuUtils.NR_OF_THREADS:]
- cpu_list = [cpu for cpu in cpu_list_0[skip_cnt:skip_cnt + cpu_cnt]]
- cpu_list_ex = [cpu for cpu in
- cpu_list_1[skip_cnt:skip_cnt + cpu_cnt]]
+ cpu_list_0 = cpu_list[: cpu_list_len // CpuUtils.NR_OF_THREADS]
+ cpu_list_1 = cpu_list[cpu_list_len // CpuUtils.NR_OF_THREADS :]
+ cpu_list = [cpu for cpu in cpu_list_0[skip_cnt : skip_cnt + cpu_cnt]]
+ cpu_list_ex = [cpu for cpu in cpu_list_1[skip_cnt : skip_cnt + cpu_cnt]]
cpu_list.extend(cpu_list_ex)
else:
- cpu_list = [cpu for cpu in cpu_list[skip_cnt:skip_cnt + cpu_cnt]]
+ cpu_list = [cpu for cpu in cpu_list[skip_cnt : skip_cnt + cpu_cnt]]
return cpu_list
@staticmethod
- def cpu_list_per_node_str(node, cpu_node, skip_cnt=0, cpu_cnt=0, sep=",",
- smt_used=False):
+ def cpu_list_per_node_str(
+ node, cpu_node, skip_cnt=0, cpu_cnt=0, sep=",", smt_used=False
+ ):
"""Return string of node related list of CPU numbers.
:param node: Node dictionary with cpuinfo.
@@ -203,15 +205,15 @@ class CpuUtils(object):
:rtype: str
"""
- cpu_list = CpuUtils.cpu_slice_of_list_per_node(node, cpu_node,
- skip_cnt=skip_cnt,
- cpu_cnt=cpu_cnt,
- smt_used=smt_used)
+ cpu_list = CpuUtils.cpu_slice_of_list_per_node(
+ node, cpu_node, skip_cnt=skip_cnt, cpu_cnt=cpu_cnt, smt_used=smt_used
+ )
return sep.join(str(cpu) for cpu in cpu_list)
@staticmethod
- def cpu_range_per_node_str(node, cpu_node, skip_cnt=0, cpu_cnt=0, sep="-",
- smt_used=False):
+ def cpu_range_per_node_str(
+ node, cpu_node, skip_cnt=0, cpu_cnt=0, sep="-", smt_used=False
+ ):
"""Return string of node related range of CPU numbers, e.g. 0-4.
:param node: Node dictionary with cpuinfo.
@@ -230,18 +232,16 @@ class CpuUtils(object):
:rtype: str
"""
- cpu_list = CpuUtils.cpu_slice_of_list_per_node(node, cpu_node,
- skip_cnt=skip_cnt,
- cpu_cnt=cpu_cnt,
- smt_used=smt_used)
+ cpu_list = CpuUtils.cpu_slice_of_list_per_node(
+ node, cpu_node, skip_cnt=skip_cnt, cpu_cnt=cpu_cnt, smt_used=smt_used
+ )
if smt_used:
cpu_list_len = len(cpu_list)
- cpu_list_0 = cpu_list[:cpu_list_len // CpuUtils.NR_OF_THREADS]
- cpu_list_1 = cpu_list[cpu_list_len // CpuUtils.NR_OF_THREADS:]
- cpu_range = "{}{}{},{}{}{}".format(cpu_list_0[0], sep,
- cpu_list_0[-1],
- cpu_list_1[0], sep,
- cpu_list_1[-1])
+ cpu_list_0 = cpu_list[: cpu_list_len // CpuUtils.NR_OF_THREADS]
+ cpu_list_1 = cpu_list[cpu_list_len // CpuUtils.NR_OF_THREADS :]
+ cpu_range = "{}{}{},{}{}{}".format(
+ cpu_list_0[0], sep, cpu_list_0[-1], cpu_list_1[0], sep, cpu_list_1[-1]
+ )
else:
cpu_range = "{}{}{}".format(cpu_list[0], sep, cpu_list[-1])
@@ -260,28 +260,30 @@ class CpuUtils(object):
cmd = "lscpu"
ret, stdout, stderr = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError("lscpu command failed on node {} {}."
- .format(node['host'], stderr))
+ raise RuntimeError(
+ "lscpu command failed on node {} {}.".format(node["host"], stderr)
+ )
cpuinfo = {}
- lines = stdout.split('\n')
+ lines = stdout.split("\n")
for line in lines:
- if line != '':
- linesplit = re.split(r':\s+', line)
+ if line != "":
+ linesplit = re.split(r":\s+", line)
cpuinfo[linesplit[0]] = linesplit[1]
cmd = "cat /proc/*/task/*/stat | awk '{print $1" "$2" "$39}'"
ret, stdout, stderr = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError("cat command failed on node {} {}."
- .format(node['host'], stderr))
+ raise RuntimeError(
+ "cat command failed on node {} {}.".format(node["host"], stderr)
+ )
vpp_processes = {}
- vpp_lines = re.findall(r'\w+\(vpp_\w+\)\w+', stdout)
+ vpp_lines = re.findall(r"\w+\(vpp_\w+\)\w+", stdout)
for line in vpp_lines:
- linesplit = re.split(r'\w+\(', line)[1].split(')')
+ linesplit = re.split(r"\w+\(", line)[1].split(")")
vpp_processes[linesplit[0]] = linesplit[1]
- cpuinfo['vpp_processes'] = vpp_processes
+ cpuinfo["vpp_processes"] = vpp_processes
return cpuinfo
diff --git a/extras/vpp_config/vpplib/QemuUtils.py b/extras/vpp_config/vpplib/QemuUtils.py
index 0b7e08b12d8..e1da7ae72bf 100644
--- a/extras/vpp_config/vpplib/QemuUtils.py
+++ b/extras/vpp_config/vpplib/QemuUtils.py
@@ -12,7 +12,7 @@
# limitations under the License.
"""QEMU utilities library."""
-from __future__ import absolute_import, division
+from __future__ import absolute_import, division
from time import time, sleep
import json
@@ -24,12 +24,13 @@ from vpplib.constants import Constants
class NodeType(object):
"""Defines node types used in topology dictionaries."""
+
# Device Under Test (this node has VPP running on it)
- DUT = 'DUT'
+ DUT = "DUT"
# Traffic Generator (this node has traffic generator on it)
- TG = 'TG'
+ TG = "TG"
# Virtual Machine (this node running on DUT node)
- VM = 'VM'
+ VM = "VM"
class QemuUtils(object):
@@ -39,43 +40,46 @@ class QemuUtils(object):
def __init__(self, qemu_id=1):
self._qemu_id = qemu_id
# Path to QEMU binary
- self._qemu_bin = '/usr/bin/qemu-system-x86_64'
+ self._qemu_bin = "/usr/bin/qemu-system-x86_64"
# QEMU Machine Protocol socket
- self._qmp_sock = '/tmp/qmp{0}.sock'.format(self._qemu_id)
+ self._qmp_sock = "/tmp/qmp{0}.sock".format(self._qemu_id)
# QEMU Guest Agent socket
- self._qga_sock = '/tmp/qga{0}.sock'.format(self._qemu_id)
+ self._qga_sock = "/tmp/qga{0}.sock".format(self._qemu_id)
# QEMU PID file
- self._pid_file = '/tmp/qemu{0}.pid'.format(self._qemu_id)
+ self._pid_file = "/tmp/qemu{0}.pid".format(self._qemu_id)
self._qemu_opt = {}
# Default 1 CPU.
- self._qemu_opt['smp'] = '-smp 1,sockets=1,cores=1,threads=1'
+ self._qemu_opt["smp"] = "-smp 1,sockets=1,cores=1,threads=1"
# Daemonize the QEMU process after initialization. Default one
# management interface.
- self._qemu_opt['options'] = '-cpu host -daemonize -enable-kvm ' \
- '-machine pc,accel=kvm,usb=off,mem-merge=off ' \
- '-net nic,macaddr=52:54:00:00:{0:02x}:ff -balloon none'\
- .format(self._qemu_id)
- self._qemu_opt['ssh_fwd_port'] = 10021 + qemu_id
+ self._qemu_opt["options"] = (
+ "-cpu host -daemonize -enable-kvm "
+ "-machine pc,accel=kvm,usb=off,mem-merge=off "
+ "-net nic,macaddr=52:54:00:00:{0:02x}:ff -balloon none".format(
+ self._qemu_id
+ )
+ )
+ self._qemu_opt["ssh_fwd_port"] = 10021 + qemu_id
# Default serial console port
- self._qemu_opt['serial_port'] = 4555 + qemu_id
+ self._qemu_opt["serial_port"] = 4555 + qemu_id
# Default 512MB virtual RAM
- self._qemu_opt['mem_size'] = 512
+ self._qemu_opt["mem_size"] = 512
# Default huge page mount point, required for Vhost-user interfaces.
- self._qemu_opt['huge_mnt'] = '/mnt/huge'
+ self._qemu_opt["huge_mnt"] = "/mnt/huge"
# Default do not allocate huge pages.
- self._qemu_opt['huge_allocate'] = False
+ self._qemu_opt["huge_allocate"] = False
# Default image for CSIT virl setup
- self._qemu_opt['disk_image'] = '/var/lib/vm/vhost-nested.img'
+ self._qemu_opt["disk_image"] = "/var/lib/vm/vhost-nested.img"
# VM node info dict
self._vm_info = {
- 'type': NodeType.VM,
- 'port': self._qemu_opt['ssh_fwd_port'],
- 'username': 'cisco',
- 'password': 'cisco',
- 'interfaces': {},
+ "type": NodeType.VM,
+ "port": self._qemu_opt["ssh_fwd_port"],
+ "username": "cisco",
+ "password": "cisco",
+ "interfaces": {},
}
# Virtio queue count
- self._qemu_opt['queues'] = 1
+ self._qemu_opt["queues"] = 1
self._vhost_id = 0
self._ssh = None
self._node = None
@@ -101,9 +105,9 @@ class QemuUtils(object):
:type threads: int
:type sockets: int
"""
- self._qemu_opt['smp'] = \
- '-smp {},cores={},threads={},sockets={}'.format(
- cpus, cores, threads, sockets)
+ self._qemu_opt["smp"] = "-smp {},cores={},threads={},sockets={}".format(
+ cpus, cores, threads, sockets
+ )
def qemu_set_ssh_fwd_port(self, fwd_port):
"""Set host port for guest SSH forwarding.
@@ -111,8 +115,8 @@ class QemuUtils(object):
:param fwd_port: Port number on host for guest SSH forwarding.
:type fwd_port: int
"""
- self._qemu_opt['ssh_fwd_port'] = fwd_port
- self._vm_info['port'] = fwd_port
+ self._qemu_opt["ssh_fwd_port"] = fwd_port
+ self._vm_info["port"] = fwd_port
def qemu_set_serial_port(self, port):
"""Set serial console port.
@@ -120,7 +124,7 @@ class QemuUtils(object):
:param port: Serial console port.
:type port: int
"""
- self._qemu_opt['serial_port'] = port
+ self._qemu_opt["serial_port"] = port
def qemu_set_mem_size(self, mem_size):
"""Set virtual RAM size.
@@ -128,7 +132,7 @@ class QemuUtils(object):
:param mem_size: RAM size in Mega Bytes.
:type mem_size: int
"""
- self._qemu_opt['mem_size'] = int(mem_size)
+ self._qemu_opt["mem_size"] = int(mem_size)
def qemu_set_huge_mnt(self, huge_mnt):
"""Set hugefile mount point.
@@ -136,11 +140,11 @@ class QemuUtils(object):
:param huge_mnt: System hugefile mount point.
:type huge_mnt: int
"""
- self._qemu_opt['huge_mnt'] = huge_mnt
+ self._qemu_opt["huge_mnt"] = huge_mnt
def qemu_set_huge_allocate(self):
"""Set flag to allocate more huge pages if needed."""
- self._qemu_opt['huge_allocate'] = True
+ self._qemu_opt["huge_allocate"] = True
def qemu_set_disk_image(self, disk_image):
"""Set disk image.
@@ -148,7 +152,7 @@ class QemuUtils(object):
:param disk_image: Path of the disk image.
:type disk_image: str
"""
- self._qemu_opt['disk_image'] = disk_image
+ self._qemu_opt["disk_image"] = disk_image
def qemu_set_affinity(self, *host_cpus):
"""Set qemu affinity by getting thread PIDs via QMP and taskset to list
@@ -157,36 +161,41 @@ class QemuUtils(object):
:param host_cpus: List of CPU cores.
:type host_cpus: list
"""
- qemu_cpus = self._qemu_qmp_exec('query-cpus')['return']
+ qemu_cpus = self._qemu_qmp_exec("query-cpus")["return"]
if len(qemu_cpus) != len(host_cpus):
- logging.debug('Host CPU count {0}, Qemu Thread count {1}'.format(
- len(host_cpus), len(qemu_cpus)))
- raise ValueError('Host CPU count must match Qemu Thread count')
+ logging.debug(
+ "Host CPU count {0}, Qemu Thread count {1}".format(
+ len(host_cpus), len(qemu_cpus)
+ )
+ )
+ raise ValueError("Host CPU count must match Qemu Thread count")
for qemu_cpu, host_cpu in zip(qemu_cpus, host_cpus):
- cmd = 'taskset -pc {0} {1}'.format(host_cpu, qemu_cpu['thread_id'])
+ cmd = "taskset -pc {0} {1}".format(host_cpu, qemu_cpu["thread_id"])
(ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
if int(ret_code) != 0:
- logging.debug('Set affinity failed {0}'.format(stderr))
- raise RuntimeError('Set affinity failed on {0}'.format(
- self._node['host']))
+ logging.debug("Set affinity failed {0}".format(stderr))
+ raise RuntimeError(
+ "Set affinity failed on {0}".format(self._node["host"])
+ )
def qemu_set_scheduler_policy(self):
"""Set scheduler policy to SCHED_RR with priority 1 for all Qemu CPU
- processes.
+ processes.
- :raises RuntimeError: Set scheduler policy failed.
+ :raises RuntimeError: Set scheduler policy failed.
"""
- qemu_cpus = self._qemu_qmp_exec('query-cpus')['return']
+ qemu_cpus = self._qemu_qmp_exec("query-cpus")["return"]
for qemu_cpu in qemu_cpus:
- cmd = 'chrt -r -p 1 {0}'.format(qemu_cpu['thread_id'])
+ cmd = "chrt -r -p 1 {0}".format(qemu_cpu["thread_id"])
(ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
if int(ret_code) != 0:
- logging.debug('Set SCHED_RR failed {0}'.format(stderr))
- raise RuntimeError('Set SCHED_RR failed on {0}'.format(
- self._node['host']))
+ logging.debug("Set SCHED_RR failed {0}".format(stderr))
+ raise RuntimeError(
+ "Set SCHED_RR failed on {0}".format(self._node["host"])
+ )
def qemu_set_node(self, node):
"""Set node to run QEMU on.
@@ -195,7 +204,7 @@ class QemuUtils(object):
:type node: dict
"""
self._node = node
- self._vm_info['host'] = node['host']
+ self._vm_info["host"] = node["host"]
def qemu_add_vhost_user_if(self, socket, server=True, mac=None):
"""Add Vhost-user interface.
@@ -210,31 +219,33 @@ class QemuUtils(object):
"""
self._vhost_id += 1
# Create unix socket character device.
- chardev = ' -chardev socket,id=char{0},path={1}'.format(self._vhost_id,
- socket)
+ chardev = " -chardev socket,id=char{0},path={1}".format(self._vhost_id, socket)
if server is True:
- chardev += ',server'
- self._qemu_opt['options'] += chardev
+ chardev += ",server"
+ self._qemu_opt["options"] += chardev
# Create Vhost-user network backend.
- netdev = (' -netdev vhost-user,id=vhost{0},chardev=char{0},queues={1}'
- .format(self._vhost_id, self._qemu_opt['queues']))
- self._qemu_opt['options'] += netdev
+ netdev = " -netdev vhost-user,id=vhost{0},chardev=char{0},queues={1}".format(
+ self._vhost_id, self._qemu_opt["queues"]
+ )
+ self._qemu_opt["options"] += netdev
# If MAC is not specified use auto-generated MAC address based on
# template 52:54:00:00:<qemu_id>:<vhost_id>, e.g. vhost1 MAC of QEMU
# with ID 1 is 52:54:00:00:01:01
if mac is None:
- mac = '52:54:00:00:{0:02x}:{1:02x}'.\
- format(self._qemu_id, self._vhost_id)
- extend_options = 'mq=on,csum=off,gso=off,guest_tso4=off,'\
- 'guest_tso6=off,guest_ecn=off,mrg_rxbuf=off'
+ mac = "52:54:00:00:{0:02x}:{1:02x}".format(self._qemu_id, self._vhost_id)
+ extend_options = (
+ "mq=on,csum=off,gso=off,guest_tso4=off,"
+ "guest_tso6=off,guest_ecn=off,mrg_rxbuf=off"
+ )
# Create Virtio network device.
- device = ' -device virtio-net-pci,netdev=vhost{0},mac={1},{2}'.format(
- self._vhost_id, mac, extend_options)
- self._qemu_opt['options'] += device
+ device = " -device virtio-net-pci,netdev=vhost{0},mac={1},{2}".format(
+ self._vhost_id, mac, extend_options
+ )
+ self._qemu_opt["options"] += device
# Add interface MAC and socket to the node dict
- if_data = {'mac_address': mac, 'socket': socket}
- if_name = 'vhost{}'.format(self._vhost_id)
- self._vm_info['interfaces'][if_name] = if_data
+ if_data = {"mac_address": mac, "socket": socket}
+ if_name = "vhost{}".format(self._vhost_id)
+ self._vm_info["interfaces"][if_name] = if_data
# Add socket to the socket list
self._socks.append(socket)
@@ -250,41 +261,44 @@ class QemuUtils(object):
response will contain the "error" keyword instead of "return".
"""
# To enter command mode, the qmp_capabilities command must be issued.
- qmp_cmd = 'echo "{ \\"execute\\": \\"qmp_capabilities\\" }' \
- '{ \\"execute\\": \\"' + cmd + \
- '\\" }" | sudo -S socat - UNIX-CONNECT:' + self._qmp_sock
+ qmp_cmd = (
+ 'echo "{ \\"execute\\": \\"qmp_capabilities\\" }'
+ '{ \\"execute\\": \\"'
+ + cmd
+ + '\\" }" | sudo -S socat - UNIX-CONNECT:'
+ + self._qmp_sock
+ )
(ret_code, stdout, stderr) = self._ssh.exec_command(qmp_cmd)
if int(ret_code) != 0:
- logging.debug('QMP execute failed {0}'.format(stderr))
- raise RuntimeError('QMP execute "{0}"'
- ' failed on {1}'.format(
- cmd, self._node['host']))
+ logging.debug("QMP execute failed {0}".format(stderr))
+ raise RuntimeError(
+ 'QMP execute "{0}"' " failed on {1}".format(cmd, self._node["host"])
+ )
logging.debug(stdout)
# Skip capabilities negotiation messages.
out_list = stdout.splitlines()
if len(out_list) < 3:
- raise RuntimeError('Invalid QMP output on {0}'.format(
- self._node['host']))
+ raise RuntimeError("Invalid QMP output on {0}".format(self._node["host"]))
return json.loads(out_list[2])
def _qemu_qga_flush(self):
- """Flush the QGA parser state
- """
- qga_cmd = '(printf "\xFF"; sleep 1) | ' \
- 'sudo -S socat - UNIX-CONNECT:' + \
- self._qga_sock
+ """Flush the QGA parser state"""
+ qga_cmd = (
+ '(printf "\xFF"; sleep 1) | '
+ "sudo -S socat - UNIX-CONNECT:" + self._qga_sock
+ )
# TODO: probably need something else
(ret_code, stdout, stderr) = self._ssh.exec_command(qga_cmd)
if int(ret_code) != 0:
- logging.debug('QGA execute failed {0}'.format(stderr))
- raise RuntimeError('QGA execute "{0}" '
- 'failed on {1}'.format(qga_cmd,
- self._node['host']))
+ logging.debug("QGA execute failed {0}".format(stderr))
+ raise RuntimeError(
+ 'QGA execute "{0}" ' "failed on {1}".format(qga_cmd, self._node["host"])
+ )
logging.debug(stdout)
if not stdout:
return {}
- return json.loads(stdout.split('\n', 1)[0])
+ return json.loads(stdout.split("\n", 1)[0])
def _qemu_qga_exec(self, cmd):
"""Execute QGA command.
@@ -294,20 +308,22 @@ class QemuUtils(object):
:param cmd: QGA command to execute.
:type cmd: str
"""
- qga_cmd = '(echo "{ \\"execute\\": \\"' + \
- cmd + \
- '\\" }"; sleep 1) | sudo -S socat - UNIX-CONNECT:' + \
- self._qga_sock
+ qga_cmd = (
+ '(echo "{ \\"execute\\": \\"'
+ + cmd
+ + '\\" }"; sleep 1) | sudo -S socat - UNIX-CONNECT:'
+ + self._qga_sock
+ )
(ret_code, stdout, stderr) = self._ssh.exec_command(qga_cmd)
if int(ret_code) != 0:
- logging.debug('QGA execute failed {0}'.format(stderr))
- raise RuntimeError('QGA execute "{0}"'
- ' failed on {1}'.format(
- cmd, self._node['host']))
+ logging.debug("QGA execute failed {0}".format(stderr))
+ raise RuntimeError(
+ 'QGA execute "{0}"' " failed on {1}".format(cmd, self._node["host"])
+ )
logging.debug(stdout)
if not stdout:
return {}
- return json.loads(stdout.split('\n', 1)[0])
+ return json.loads(stdout.split("\n", 1)[0])
def _wait_until_vm_boot(self, timeout=60):
"""Wait until QEMU VM is booted.
@@ -320,65 +336,69 @@ class QemuUtils(object):
start = time()
while True:
if time() - start > timeout:
- raise RuntimeError('timeout, VM {0} not booted on {1}'.format(
- self._qemu_opt['disk_image'], self._node['host']))
+ raise RuntimeError(
+ "timeout, VM {0} not booted on {1}".format(
+ self._qemu_opt["disk_image"], self._node["host"]
+ )
+ )
out = None
try:
self._qemu_qga_flush()
- out = self._qemu_qga_exec('guest-ping')
+ out = self._qemu_qga_exec("guest-ping")
except ValueError:
- logging.debug(
- 'QGA guest-ping unexpected output {}'.format(out))
+ logging.debug("QGA guest-ping unexpected output {}".format(out))
# Empty output - VM not booted yet
if not out:
sleep(5)
# Non-error return - VM booted
- elif out.get('return') is not None:
+ elif out.get("return") is not None:
break
# Skip error and wait
- elif out.get('error') is not None:
+ elif out.get("error") is not None:
sleep(5)
else:
# If there is an unexpected output from QGA guest-info, try
# again until timeout.
- logging.debug(
- 'QGA guest-ping unexpected output {}'.format(out))
+ logging.debug("QGA guest-ping unexpected output {}".format(out))
logging.debug(
- 'VM {0} booted on {1}'.format(self._qemu_opt['disk_image'],
- self._node['host']))
+ "VM {0} booted on {1}".format(
+ self._qemu_opt["disk_image"], self._node["host"]
+ )
+ )
def _update_vm_interfaces(self):
"""Update interface names in VM node dict."""
# Send guest-network-get-interfaces command via QGA, output example:
# {"return": [{"name": "eth0", "hardware-address": "52:54:00:00:04:01"},
# {"name": "eth1", "hardware-address": "52:54:00:00:04:02"}]}
- out = self._qemu_qga_exec('guest-network-get-interfaces')
- interfaces = out.get('return')
+ out = self._qemu_qga_exec("guest-network-get-interfaces")
+ interfaces = out.get("return")
mac_name = {}
if not interfaces:
raise RuntimeError(
- 'Get VM {0} interface list failed on {1}'.format(
- self._qemu_opt['disk_image'], self._node['host']))
+ "Get VM {0} interface list failed on {1}".format(
+ self._qemu_opt["disk_image"], self._node["host"]
+ )
+ )
# Create MAC-name dict
for interface in interfaces:
- if 'hardware-address' not in interface:
+ if "hardware-address" not in interface:
continue
- mac_name[interface['hardware-address']] = interface['name']
+ mac_name[interface["hardware-address"]] = interface["name"]
# Match interface by MAC and save interface name
- for interface in self._vm_info['interfaces'].values():
- mac = interface.get('mac_address')
+ for interface in self._vm_info["interfaces"].values():
+ mac = interface.get("mac_address")
if_name = mac_name.get(mac)
if if_name is None:
- logging.debug(
- 'Interface name for MAC {} not found'.format(mac))
+ logging.debug("Interface name for MAC {} not found".format(mac))
else:
- interface['name'] = if_name
+ interface["name"] = if_name
def _huge_page_check(self, allocate=False):
"""Huge page check."""
- huge_mnt = self._qemu_opt.get('huge_mnt')
- mem_size = self._qemu_opt.get('mem_size')
+ huge_mnt = self._qemu_opt.get("huge_mnt")
+ mem_size = self._qemu_opt.get("mem_size")
# Get huge pages information
huge_size = self._get_huge_page_size()
@@ -391,55 +411,55 @@ class QemuUtils(object):
if allocate:
mem_needed = abs((huge_free * huge_size) - (mem_size * 1024))
huge_to_allocate = ((mem_needed // huge_size) * 2) + huge_total
- max_map_count = huge_to_allocate*4
+ max_map_count = huge_to_allocate * 4
# Increase maximum number of memory map areas a
# process may have
- cmd = \
- 'echo "{0}" | sudo tee /proc/sys/vm/max_map_count'.format(
- max_map_count)
+ cmd = 'echo "{0}" | sudo tee /proc/sys/vm/max_map_count'.format(
+ max_map_count
+ )
(ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
# Increase hugepage count
- cmd = \
- 'echo "{0}" | sudo tee /proc/sys/vm/nr_hugepages'.format(
- huge_to_allocate)
+ cmd = 'echo "{0}" | sudo tee /proc/sys/vm/nr_hugepages'.format(
+ huge_to_allocate
+ )
(ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
if int(ret_code) != 0:
- logging.debug(
- 'Mount huge pages failed {0}'.format(stderr))
+ logging.debug("Mount huge pages failed {0}".format(stderr))
raise RuntimeError(
- 'Mount huge pages failed on {0}'.format(
- self._node['host']))
+ "Mount huge pages failed on {0}".format(self._node["host"])
+ )
# If we do not want to allocate dynamicaly end with error
else:
raise RuntimeError(
- 'Not enough free huge pages: {0}, '
- '{1} MB'.format(huge_free, huge_free * huge_size)
+ "Not enough free huge pages: {0}, "
+ "{1} MB".format(huge_free, huge_free * huge_size)
)
# Check if huge pages mount point exist
has_huge_mnt = False
- (_, output, _) = self._ssh.exec_command('cat /proc/mounts')
+ (_, output, _) = self._ssh.exec_command("cat /proc/mounts")
for line in output.splitlines():
# Try to find something like:
# none /mnt/huge hugetlbfs rw,relatime,pagesize=2048k 0 0
mount = line.split()
- if mount[2] == 'hugetlbfs' and mount[1] == huge_mnt:
+ if mount[2] == "hugetlbfs" and mount[1] == huge_mnt:
has_huge_mnt = True
break
# If huge page mount point not exist create one
if not has_huge_mnt:
- cmd = 'mkdir -p {0}'.format(huge_mnt)
+ cmd = "mkdir -p {0}".format(huge_mnt)
(ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
if int(ret_code) != 0:
- logging.debug('Create mount dir failed: {0}'.format(stderr))
- raise RuntimeError('Create mount dir failed on {0}'.format(
- self._node['host']))
- cmd = 'mount -t hugetlbfs -o pagesize=2048k none {0}'.format(
- huge_mnt)
+ logging.debug("Create mount dir failed: {0}".format(stderr))
+ raise RuntimeError(
+ "Create mount dir failed on {0}".format(self._node["host"])
+ )
+ cmd = "mount -t hugetlbfs -o pagesize=2048k none {0}".format(huge_mnt)
(ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd)
if int(ret_code) != 0:
- logging.debug('Mount huge pages failed {0}'.format(stderr))
- raise RuntimeError('Mount huge pages failed on {0}'.format(
- self._node['host']))
+ logging.debug("Mount huge pages failed {0}".format(stderr))
+ raise RuntimeError(
+ "Mount huge pages failed on {0}".format(self._node["host"])
+ )
def _get_huge_page_size(self):
"""Get default size of huge pages in system.
@@ -456,11 +476,11 @@ class QemuUtils(object):
try:
huge_size = int(out)
except ValueError:
- logging.debug('Reading huge page size information failed')
+ logging.debug("Reading huge page size information failed")
else:
break
else:
- raise RuntimeError('Getting huge page size information failed.')
+ raise RuntimeError("Getting huge page size information failed.")
return huge_size
def _get_huge_page_free(self, huge_size):
@@ -474,20 +494,21 @@ class QemuUtils(object):
"""
# TODO: add numa aware option
# TODO: remove to dedicated library
- cmd_huge_free = 'cat /sys/kernel/mm/hugepages/hugepages-{0}kB/'\
- 'free_hugepages'.format(huge_size)
+ cmd_huge_free = (
+ "cat /sys/kernel/mm/hugepages/hugepages-{0}kB/"
+ "free_hugepages".format(huge_size)
+ )
for _ in range(3):
(ret, out, _) = self._ssh.exec_command_sudo(cmd_huge_free)
if ret == 0:
try:
huge_free = int(out)
except ValueError:
- logging.debug(
- 'Reading free huge pages information failed')
+ logging.debug("Reading free huge pages information failed")
else:
break
else:
- raise RuntimeError('Getting free huge pages information failed.')
+ raise RuntimeError("Getting free huge pages information failed.")
return huge_free
def _get_huge_page_total(self, huge_size):
@@ -501,20 +522,21 @@ class QemuUtils(object):
"""
# TODO: add numa aware option
# TODO: remove to dedicated library
- cmd_huge_total = 'cat /sys/kernel/mm/hugepages/hugepages-{0}kB/'\
- 'nr_hugepages'.format(huge_size)
+ cmd_huge_total = (
+ "cat /sys/kernel/mm/hugepages/hugepages-{0}kB/"
+ "nr_hugepages".format(huge_size)
+ )
for _ in range(3):
(ret, out, _) = self._ssh.exec_command_sudo(cmd_huge_total)
if ret == 0:
try:
huge_total = int(out)
except ValueError:
- logging.debug(
- 'Reading total huge pages information failed')
+ logging.debug("Reading total huge pages information failed")
else:
break
else:
- raise RuntimeError('Getting total huge pages information failed.')
+ raise RuntimeError("Getting total huge pages information failed.")
return huge_total
def qemu_start(self):
@@ -526,45 +548,63 @@ class QemuUtils(object):
.. warning:: Starts only one VM on the node.
"""
# SSH forwarding
- ssh_fwd = '-net user,hostfwd=tcp::{0}-:22'.format(
- self._qemu_opt.get('ssh_fwd_port'))
+ ssh_fwd = "-net user,hostfwd=tcp::{0}-:22".format(
+ self._qemu_opt.get("ssh_fwd_port")
+ )
# Memory and huge pages
- mem = '-object memory-backend-file,id=mem,size={0}M,mem-path={1},' \
- 'share=on -m {0} -numa node,memdev=mem'.format(
- self._qemu_opt.get('mem_size'), self._qemu_opt.get('huge_mnt'))
+ mem = (
+ "-object memory-backend-file,id=mem,size={0}M,mem-path={1},"
+ "share=on -m {0} -numa node,memdev=mem".format(
+ self._qemu_opt.get("mem_size"), self._qemu_opt.get("huge_mnt")
+ )
+ )
# By default check only if hugepages are available.
# If 'huge_allocate' is set to true try to allocate as well.
- self._huge_page_check(allocate=self._qemu_opt.get('huge_allocate'))
+ self._huge_page_check(allocate=self._qemu_opt.get("huge_allocate"))
# Disk option
- drive = '-drive file={0},format=raw,cache=none,if=virtio'.format(
- self._qemu_opt.get('disk_image'))
+ drive = "-drive file={0},format=raw,cache=none,if=virtio".format(
+ self._qemu_opt.get("disk_image")
+ )
# Setup QMP via unix socket
- qmp = '-qmp unix:{0},server,nowait'.format(self._qmp_sock)
+ qmp = "-qmp unix:{0},server,nowait".format(self._qmp_sock)
# Setup serial console
- serial = '-chardev socket,host=127.0.0.1,port={0},id=gnc0,server,' \
- 'nowait -device isa-serial,chardev=gnc0'.format(
- self._qemu_opt.get('serial_port'))
+ serial = (
+ "-chardev socket,host=127.0.0.1,port={0},id=gnc0,server,"
+ "nowait -device isa-serial,chardev=gnc0".format(
+ self._qemu_opt.get("serial_port")
+ )
+ )
# Setup QGA via chardev (unix socket) and isa-serial channel
- qga = '-chardev socket,path={0},server,nowait,id=qga0 ' \
- '-device isa-serial,chardev=qga0'.format(self._qga_sock)
+ qga = (
+ "-chardev socket,path={0},server,nowait,id=qga0 "
+ "-device isa-serial,chardev=qga0".format(self._qga_sock)
+ )
# Graphic setup
- graphic = '-monitor none -display none -vga none'
+ graphic = "-monitor none -display none -vga none"
# PID file
- pid = '-pidfile {}'.format(self._pid_file)
+ pid = "-pidfile {}".format(self._pid_file)
# Run QEMU
- cmd = '{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}'.format(
- self._qemu_bin, self._qemu_opt.get('smp'), mem, ssh_fwd,
- self._qemu_opt.get('options'),
- drive, qmp, serial, qga, graphic, pid)
+ cmd = "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}".format(
+ self._qemu_bin,
+ self._qemu_opt.get("smp"),
+ mem,
+ ssh_fwd,
+ self._qemu_opt.get("options"),
+ drive,
+ qmp,
+ serial,
+ qga,
+ graphic,
+ pid,
+ )
(ret_code, _, stderr) = self._ssh.exec_command_sudo(cmd, timeout=300)
if int(ret_code) != 0:
- logging.debug('QEMU start failed {0}'.format(stderr))
- raise RuntimeError('QEMU start failed on {0}'.format(
- self._node['host']))
- logging.debug('QEMU running')
+ logging.debug("QEMU start failed {0}".format(stderr))
+ raise RuntimeError("QEMU start failed on {0}".format(self._node["host"]))
+ logging.debug("QEMU running")
# Wait until VM boot
try:
self._wait_until_vm_boot()
@@ -579,40 +619,43 @@ class QemuUtils(object):
def qemu_quit(self):
"""Quit the QEMU emulator."""
- out = self._qemu_qmp_exec('quit')
- err = out.get('error')
+ out = self._qemu_qmp_exec("quit")
+ err = out.get("error")
if err is not None:
- raise RuntimeError('QEMU quit failed on {0}, error: {1}'.format(
- self._node['host'], json.dumps(err)))
+ raise RuntimeError(
+ "QEMU quit failed on {0}, error: {1}".format(
+ self._node["host"], json.dumps(err)
+ )
+ )
def qemu_system_powerdown(self):
"""Power down the system (if supported)."""
- out = self._qemu_qmp_exec('system_powerdown')
- err = out.get('error')
+ out = self._qemu_qmp_exec("system_powerdown")
+ err = out.get("error")
if err is not None:
raise RuntimeError(
- 'QEMU system powerdown failed on {0}, '
- 'error: {1}'.format(self._node['host'], json.dumps(err))
+ "QEMU system powerdown failed on {0}, "
+ "error: {1}".format(self._node["host"], json.dumps(err))
)
def qemu_system_reset(self):
"""Reset the system."""
- out = self._qemu_qmp_exec('system_reset')
- err = out.get('error')
+ out = self._qemu_qmp_exec("system_reset")
+ err = out.get("error")
if err is not None:
raise RuntimeError(
- 'QEMU system reset failed on {0}, '
- 'error: {1}'.format(self._node['host'], json.dumps(err)))
+ "QEMU system reset failed on {0}, "
+ "error: {1}".format(self._node["host"], json.dumps(err))
+ )
def qemu_kill(self):
"""Kill qemu process."""
# Note: in QEMU start phase there are 3 QEMU processes because we
# daemonize QEMU
- self._ssh.exec_command_sudo('chmod +r {}'.format(self._pid_file))
- self._ssh.exec_command_sudo('kill -SIGKILL $(cat {})'
- .format(self._pid_file))
+ self._ssh.exec_command_sudo("chmod +r {}".format(self._pid_file))
+ self._ssh.exec_command_sudo("kill -SIGKILL $(cat {})".format(self._pid_file))
# Delete PID file
- cmd = 'rm -f {}'.format(self._pid_file)
+ cmd = "rm -f {}".format(self._pid_file)
self._ssh.exec_command_sudo(cmd)
def qemu_kill_all(self, node=None):
@@ -623,16 +666,16 @@ class QemuUtils(object):
"""
if node:
self.qemu_set_node(node)
- self._ssh.exec_command_sudo('pkill -SIGKILL qemu')
+ self._ssh.exec_command_sudo("pkill -SIGKILL qemu")
def qemu_clear_socks(self):
"""Remove all sockets created by QEMU."""
# If serial console port still open kill process
- cmd = 'fuser -k {}/tcp'.format(self._qemu_opt.get('serial_port'))
+ cmd = "fuser -k {}/tcp".format(self._qemu_opt.get("serial_port"))
self._ssh.exec_command_sudo(cmd)
# Delete all created sockets
for sock in self._socks:
- cmd = 'rm -f {}'.format(sock)
+ cmd = "rm -f {}".format(sock)
self._ssh.exec_command_sudo(cmd)
def qemu_system_status(self):
@@ -659,15 +702,16 @@ class QemuUtils(object):
:return: VM status.
:rtype: str
"""
- out = self._qemu_qmp_exec('query-status')
- ret = out.get('return')
+ out = self._qemu_qmp_exec("query-status")
+ ret = out.get("return")
if ret is not None:
- return ret.get('status')
+ return ret.get("status")
else:
- err = out.get('error')
+ err = out.get("error")
raise RuntimeError(
- 'QEMU query-status failed on {0}, '
- 'error: {1}'.format(self._node['host'], json.dumps(err)))
+ "QEMU query-status failed on {0}, "
+ "error: {1}".format(self._node["host"], json.dumps(err))
+ )
@staticmethod
def build_qemu(node, force_install=False, apply_patch=False):
@@ -682,17 +726,23 @@ class QemuUtils(object):
:raises: RuntimeError if building QEMU failed.
"""
- directory = ' --directory={0}'.format(Constants.QEMU_INSTALL_DIR)
- version = ' --version={0}'.format(Constants.QEMU_INSTALL_VERSION)
- force = ' --force' if force_install else ''
- patch = ' --patch' if apply_patch else ''
-
- (ret_code, stdout, stderr) = VPPUtil. \
- exec_command(
- "sudo -E sh -c '{0}/{1}/qemu_build.sh{2}{3}{4}{5}'".
- format(Constants.REMOTE_FW_DIR, Constants.RESOURCES_LIB_SH,
- version, directory, force, patch), 1000)
+ directory = " --directory={0}".format(Constants.QEMU_INSTALL_DIR)
+ version = " --version={0}".format(Constants.QEMU_INSTALL_VERSION)
+ force = " --force" if force_install else ""
+ patch = " --patch" if apply_patch else ""
+
+ (ret_code, stdout, stderr) = VPPUtil.exec_command(
+ "sudo -E sh -c '{0}/{1}/qemu_build.sh{2}{3}{4}{5}'".format(
+ Constants.REMOTE_FW_DIR,
+ Constants.RESOURCES_LIB_SH,
+ version,
+ directory,
+ force,
+ patch,
+ ),
+ 1000,
+ )
if int(ret_code) != 0:
- logging.debug('QEMU build failed {0}'.format(stdout + stderr))
- raise RuntimeError('QEMU build failed on {0}'.format(node['host']))
+ logging.debug("QEMU build failed {0}".format(stdout + stderr))
+ raise RuntimeError("QEMU build failed on {0}".format(node["host"]))
diff --git a/extras/vpp_config/vpplib/VPPUtil.py b/extras/vpp_config/vpplib/VPPUtil.py
index 97747a31ca5..711f1032d96 100644
--- a/extras/vpp_config/vpplib/VPPUtil.py
+++ b/extras/vpp_config/vpplib/VPPUtil.py
@@ -23,15 +23,53 @@ from collections import Counter
import distro
-ubuntu_pkgs = {'release': ['vpp', 'vpp-plugin-core', 'vpp-plugin-dpdk', 'vpp-api-python', 'python3-vpp-api',
- 'vpp-dbg', 'vpp-dev', 'vpp-ext-deps'],
- 'master': ['vpp', 'vpp-plugin-core', 'vpp-plugin-dpdk', 'vpp-api-python', 'python3-vpp-api',
- 'vpp-dbg', 'vpp-dev', 'vpp-ext-deps']}
-
-centos_pkgs = {'release': ['vpp', 'vpp-selinux-policy', 'vpp-plugins', 'vpp-api-lua',
- 'vpp-api-python', 'vpp-debuginfo', 'vpp-devel', 'libvpp0', 'vpp-ext-deps'],
- 'master': ['vpp', 'vpp-selinux-policy', 'vpp-plugins', 'vpp-api-lua',
- 'vpp-api-python', 'vpp-debuginfo', 'vpp-devel', 'libvpp0', 'vpp-ext-deps']}
+ubuntu_pkgs = {
+ "release": [
+ "vpp",
+ "vpp-plugin-core",
+ "vpp-plugin-dpdk",
+ "vpp-api-python",
+ "python3-vpp-api",
+ "vpp-dbg",
+ "vpp-dev",
+ "vpp-ext-deps",
+ ],
+ "master": [
+ "vpp",
+ "vpp-plugin-core",
+ "vpp-plugin-dpdk",
+ "vpp-api-python",
+ "python3-vpp-api",
+ "vpp-dbg",
+ "vpp-dev",
+ "vpp-ext-deps",
+ ],
+}
+
+centos_pkgs = {
+ "release": [
+ "vpp",
+ "vpp-selinux-policy",
+ "vpp-plugins",
+ "vpp-api-lua",
+ "vpp-api-python",
+ "vpp-debuginfo",
+ "vpp-devel",
+ "libvpp0",
+ "vpp-ext-deps",
+ ],
+ "master": [
+ "vpp",
+ "vpp-selinux-policy",
+ "vpp-plugins",
+ "vpp-api-lua",
+ "vpp-api-python",
+ "vpp-debuginfo",
+ "vpp-devel",
+ "libvpp0",
+ "vpp-ext-deps",
+ ],
+}
class VPPUtil(object):
@@ -50,19 +88,23 @@ class VPPUtil(object):
"""
logging.info(" Local Command: {}".format(cmd))
- out = ''
- err = ''
- prc = subprocess.Popen(cmd, shell=True, bufsize=1,
- stdin=subprocess.PIPE,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
+ out = ""
+ err = ""
+ prc = subprocess.Popen(
+ cmd,
+ shell=True,
+ bufsize=1,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
with prc.stdout:
lines = prc.stdout.readlines()
for line in lines:
if type(line) != str:
line = line.decode()
- logging.info(" {}".format(line.strip('\n')))
+ logging.info(" {}".format(line.strip("\n")))
out += line
with prc.stderr:
@@ -70,7 +112,7 @@ class VPPUtil(object):
for line in lines:
if type(line) != str:
line = line.decode()
- logging.warning(" {}".format(line.strip('\n')))
+ logging.warning(" {}".format(line.strip("\n")))
err += line
ret = prc.wait()
@@ -86,17 +128,17 @@ class VPPUtil(object):
"""
# Does a copy of the file exist, if not create one
- ofile = filename + '.orig'
- (ret, stdout, stderr) = self.exec_command('ls {}'.format(ofile))
+ ofile = filename + ".orig"
+ (ret, stdout, stderr) = self.exec_command("ls {}".format(ofile))
if ret != 0:
logging.debug(stderr)
- if stdout.strip('\n') != ofile:
- cmd = 'sudo cp {} {}'.format(filename, ofile)
+ if stdout.strip("\n") != ofile:
+ cmd = "sudo cp {} {}".format(filename, ofile)
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
logging.debug(stderr)
- def _install_vpp_ubuntu(self, node, branch, ubuntu_version='xenial'):
+ def _install_vpp_ubuntu(self, node, branch, ubuntu_version="xenial"):
"""
Install the VPP packages
@@ -109,49 +151,49 @@ class VPPUtil(object):
"""
# Modify the sources list
- sfile = '/etc/apt/sources.list.d/99fd.io.list'
+ sfile = "/etc/apt/sources.list.d/99fd.io.list"
# Backup the sources list
self._autoconfig_backup_file(sfile)
- reps = 'deb [trusted=yes] https://packagecloud.io/fdio/'
- reps += '{}/ubuntu {} main\n'.format(branch, ubuntu_version)
+ reps = "deb [trusted=yes] https://packagecloud.io/fdio/"
+ reps += "{}/ubuntu {} main\n".format(branch, ubuntu_version)
- with open(sfile, 'w') as sfd:
+ with open(sfile, "w") as sfd:
sfd.write(reps)
sfd.close()
# Add the key
- key = requests.get(
- 'https://packagecloud.io/fdio/{}/gpgkey'.format(branch))
+ key = requests.get("https://packagecloud.io/fdio/{}/gpgkey".format(branch))
cmd = 'echo "{}" | apt-key add -'.format(key.content.decode(key.encoding))
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {}'.format(
- cmd,
- node['host'],
- stderr))
+ raise RuntimeError(
+ "{} failed on node {} {}".format(cmd, node["host"], stderr)
+ )
# Install the package
- cmd = 'apt-get -y update'
+ cmd = "apt-get -y update"
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} apt-get update failed on node {} {}'.format(
- cmd,
- node['host'],
- stderr))
+ raise RuntimeError(
+ "{} apt-get update failed on node {} {}".format(
+ cmd, node["host"], stderr
+ )
+ )
# Get the package list
- pkgstr = ''
+ pkgstr = ""
for ps in ubuntu_pkgs[branch]:
- pkgstr += ps + ' '
+ pkgstr += ps + " "
- cmd = 'apt-get -y install {}'.format(pkgstr)
+ cmd = "apt-get -y install {}".format(pkgstr)
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.format(
- cmd, node['host'], stdout, stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
def _install_vpp_centos(self, node, branch):
"""
@@ -164,95 +206,82 @@ class VPPUtil(object):
"""
# Be sure the correct system packages are installed
- cmd = 'yum -y update'
+ cmd = "yum -y update"
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
- logging.debug('{} failed on node {} {}'.format(
- cmd,
- node['host'],
- stderr))
+ logging.debug("{} failed on node {} {}".format(cmd, node["host"], stderr))
- cmd = 'yum -y install pygpgme yum-utils'
+ cmd = "yum -y install pygpgme yum-utils"
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
- logging.debug('{} failed on node {} {}'.format(
- cmd,
- node['host'],
- stderr))
+ logging.debug("{} failed on node {} {}".format(cmd, node["host"], stderr))
# Modify the sources list
- sfile = '/etc/yum.repos.d/fdio-release.repo'
+ sfile = "/etc/yum.repos.d/fdio-release.repo"
# Backup the sources list
self._autoconfig_backup_file(sfile)
# Remove the current file
- cmd = 'rm {}'.format(sfile)
+ cmd = "rm {}".format(sfile)
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
- logging.debug('{} failed on node {} {}'.format(
- cmd,
- node['host'],
- stderr))
+ logging.debug("{} failed on node {} {}".format(cmd, node["host"], stderr))
# Get the file contents
- reps = '\n'.join([
- '[fdio_{}]'.format(branch),
- 'name=fdio_{}'.format(branch),
- 'baseurl=https://packagecloud.io/fdio/{}/el/7/$basearch'.format(
- branch),
- 'repo_gpgcheck=1',
- 'gpgcheck=0',
- 'enabled=1',
- 'gpgkey=https://packagecloud.io/fdio/{}/gpgkey'.format(branch),
- 'sslverify=1',
- 'sslcacert=/etc/pki/tls/certs/ca-bundle.crt',
- 'metadata_expire=300\n',
- '[fdio_{}-source]'.format(branch),
- 'name=fdio_release-{}'.format(branch),
- 'baseurl=https://packagecloud.io/fdio/{}/el/7/SRPMS'.format(
- branch),
- 'repo_gpgcheck=1',
- 'gpgcheck=0',
- 'enabled=1',
- 'gpgkey=https://packagecloud.io/fdio/{}/gpgkey'.format(branch),
- 'sslverify =1',
- 'sslcacert=/etc/pki/tls/certs/ca-bundle.crt',
- 'metadata_expire=300\n'
- ])
- with open(sfile, 'w') as sfd:
+ reps = "\n".join(
+ [
+ "[fdio_{}]".format(branch),
+ "name=fdio_{}".format(branch),
+ "baseurl=https://packagecloud.io/fdio/{}/el/7/$basearch".format(branch),
+ "repo_gpgcheck=1",
+ "gpgcheck=0",
+ "enabled=1",
+ "gpgkey=https://packagecloud.io/fdio/{}/gpgkey".format(branch),
+ "sslverify=1",
+ "sslcacert=/etc/pki/tls/certs/ca-bundle.crt",
+ "metadata_expire=300\n",
+ "[fdio_{}-source]".format(branch),
+ "name=fdio_release-{}".format(branch),
+ "baseurl=https://packagecloud.io/fdio/{}/el/7/SRPMS".format(branch),
+ "repo_gpgcheck=1",
+ "gpgcheck=0",
+ "enabled=1",
+ "gpgkey=https://packagecloud.io/fdio/{}/gpgkey".format(branch),
+ "sslverify =1",
+ "sslcacert=/etc/pki/tls/certs/ca-bundle.crt",
+ "metadata_expire=300\n",
+ ]
+ )
+ with open(sfile, "w") as sfd:
sfd.write(reps)
sfd.close()
# Update the fdio repo
- cmd = 'yum clean all'
+ cmd = "yum clean all"
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
- logging.debug('{} failed on node {} {}'.format(
- cmd,
- node['host'],
- stderr))
+ logging.debug("{} failed on node {} {}".format(cmd, node["host"], stderr))
- cmd = "yum -q makecache -y --disablerepo='*' " \
- "--enablerepo='fdio_{}'".format(branch)
+ cmd = "yum -q makecache -y --disablerepo='*' " "--enablerepo='fdio_{}'".format(
+ branch
+ )
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
- logging.debug('{} failed on node {} {}'.format(
- cmd,
- node['host'],
- stderr))
+ logging.debug("{} failed on node {} {}".format(cmd, node["host"], stderr))
# Get the package list
- pkgstr = ''
+ pkgstr = ""
for ps in centos_pkgs[branch]:
- pkgstr += ps + ' '
+ pkgstr += ps + " "
- cmd = 'yum -y install {}'.format(pkgstr)
+ cmd = "yum -y install {}".format(pkgstr)
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.format(
- cmd, node['host'], stdout, stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
def install_vpp(self, node, branch):
"""
@@ -266,10 +295,10 @@ class VPPUtil(object):
"""
distro = self.get_linux_distro()
logging.info(" {}".format(distro[0]))
- if distro[0] == 'Ubuntu':
+ if distro[0] == "Ubuntu":
logging.info("Install Ubuntu")
self._install_vpp_ubuntu(node, branch, ubuntu_version=distro[2])
- elif distro[0] == 'CentOS Linux':
+ elif distro[0] == "CentOS Linux":
logging.info("Install CentOS")
self._install_vpp_centos(node, branch)
else:
@@ -286,17 +315,18 @@ class VPPUtil(object):
"""
# get the package list
- pkgstr = ''
+ pkgstr = ""
pkgs = self.get_installed_vpp_pkgs()
for pkg in pkgs:
- pkgname = pkg['name']
- pkgstr += pkgname + ' '
+ pkgname = pkg["name"]
+ pkgstr += pkgname + " "
- cmd = 'dpkg --purge {}'.format(pkgstr)
+ cmd = "dpkg --purge {}".format(pkgstr)
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.format(
- cmd, node['host'], stdout, stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
def _uninstall_vpp_centos(self, node):
"""
@@ -306,18 +336,19 @@ class VPPUtil(object):
:type node: dict
"""
- pkgstr = ''
+ pkgstr = ""
pkgs = self.get_installed_vpp_pkgs()
for pkg in pkgs:
- pkgname = pkg['name']
- pkgstr += pkgname + ' '
+ pkgname = pkg["name"]
+ pkgstr += pkgname + " "
logging.info("Uninstalling {}".format(pkgstr))
- cmd = 'yum -y remove {}'.format(pkgstr)
+ cmd = "yum -y remove {}".format(pkgstr)
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.format(
- cmd, node['host'], stdout, stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
def uninstall_vpp(self, node):
"""
@@ -330,10 +361,10 @@ class VPPUtil(object):
# First stop VPP
self.stop(node)
distro = self.get_linux_distro()
- if distro[0] == 'Ubuntu':
+ if distro[0] == "Ubuntu":
logging.info("Uninstall Ubuntu")
self._uninstall_vpp_ubuntu(node)
- elif distro[0] == 'CentOS Linux':
+ elif distro[0] == "CentOS Linux":
logging.info("Uninstall CentOS")
self._uninstall_vpp_centos(node)
else:
@@ -352,21 +383,20 @@ class VPPUtil(object):
:type additional_cmds: tuple
"""
def_setting_tb_displayed = {
- 'IPv6 FIB': 'ip6 fib',
- 'IPv4 FIB': 'ip fib',
- 'Interface IP': 'int addr',
- 'Interfaces': 'int',
- 'ARP': 'ip arp',
- 'Errors': 'err'
+ "IPv6 FIB": "ip6 fib",
+ "IPv4 FIB": "ip fib",
+ "Interface IP": "int addr",
+ "Interfaces": "int",
+ "ARP": "ip arp",
+ "Errors": "err",
}
if additional_cmds:
for cmd in additional_cmds:
- def_setting_tb_displayed['Custom Setting: {}'.format(cmd)] \
- = cmd
+ def_setting_tb_displayed["Custom Setting: {}".format(cmd)] = cmd
for _, value in def_setting_tb_displayed.items():
- self.exec_command('vppctl sh {}'.format(value))
+ self.exec_command("vppctl sh {}".format(value))
@staticmethod
def get_vms(node):
@@ -397,32 +427,32 @@ class VPPUtil(object):
:rtype: dictionary
"""
interfaces = {}
- cmd = 'vppctl show int addr'
+ cmd = "vppctl show int addr"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
return interfaces
- lines = stdout.split('\n')
+ lines = stdout.split("\n")
if len(lines[0]) != 0:
- if lines[0].split(' ')[0] == 'FileNotFoundError':
+ if lines[0].split(" ")[0] == "FileNotFoundError":
return interfaces
- name = ''
+ name = ""
for line in lines:
if len(line) == 0:
continue
# If the first character is not whitespace
# create a new interface
- if len(re.findall(r'\s', line[0])) == 0:
+ if len(re.findall(r"\s", line[0])) == 0:
spl = line.split()
name = spl[0]
- if name == 'local0':
+ if name == "local0":
continue
interfaces[name] = {}
- interfaces[name]['state'] = spl[1].lstrip('(').rstrip('):\r')
+ interfaces[name]["state"] = spl[1].lstrip("(").rstrip("):\r")
else:
- interfaces[name]['address'] = line.lstrip(' ').rstrip('\r')
+ interfaces[name]["address"] = line.lstrip(" ").rstrip("\r")
return interfaces
@@ -439,14 +469,14 @@ class VPPUtil(object):
"""
interfaces = {}
- cmd = 'vppctl show hard'
+ cmd = "vppctl show hard"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
return interfaces
- lines = stdout.split('\n')
+ lines = stdout.split("\n")
if len(lines[0]) != 0:
- if lines[0].split(' ')[0] == 'FileNotFoundError':
+ if lines[0].split(" ")[0] == "FileNotFoundError":
return interfaces
for line in lines:
@@ -455,46 +485,46 @@ class VPPUtil(object):
# If the first character is not whitespace
# create a new interface
- if len(re.findall(r'\s', line[0])) == 0:
+ if len(re.findall(r"\s", line[0])) == 0:
spl = line.split()
name = spl[0]
interfaces[name] = {}
- interfaces[name]['index'] = spl[1]
- interfaces[name]['state'] = spl[2]
+ interfaces[name]["index"] = spl[1]
+ interfaces[name]["state"] = spl[2]
# Ethernet address
- rfall = re.findall(r'Ethernet address', line)
+ rfall = re.findall(r"Ethernet address", line)
if rfall:
spl = line.split()
- interfaces[name]['mac'] = spl[2]
+ interfaces[name]["mac"] = spl[2]
# Carrier
- rfall = re.findall(r'carrier', line)
+ rfall = re.findall(r"carrier", line)
if rfall:
- spl = line.split('carrier ')
- interfaces[name]['carrier'] = spl[1]
+ spl = line.split("carrier ")
+ interfaces[name]["carrier"] = spl[1]
# Socket
- spl = ''
- rfall = re.findall(r'numa \d+', line)
+ spl = ""
+ rfall = re.findall(r"numa \d+", line)
if rfall:
spl = rfall[0].split()
- interfaces[name]['numa'] = rfall[0].split()[1]
+ interfaces[name]["numa"] = rfall[0].split()[1]
# Queues and Descriptors
- rfall = re.findall(r'rx\: queues \d+', line)
+ rfall = re.findall(r"rx\: queues \d+", line)
if rfall:
- interfaces[name]['rx queues'] = rfall[0].split()[2]
- rdesc = re.findall(r'desc \d+', line)
+ interfaces[name]["rx queues"] = rfall[0].split()[2]
+ rdesc = re.findall(r"desc \d+", line)
if rdesc:
- interfaces[name]['rx descs'] = rdesc[0].split()[1]
+ interfaces[name]["rx descs"] = rdesc[0].split()[1]
- rfall = re.findall(r'tx\: queues \d+', line)
+ rfall = re.findall(r"tx\: queues \d+", line)
if rfall:
- interfaces[name]['tx queues'] = rfall[0].split()[2]
- rdesc = re.findall(r'desc \d+', line)
+ interfaces[name]["tx queues"] = rfall[0].split()[2]
+ rdesc = re.findall(r"desc \d+", line)
if rdesc:
- interfaces[name]['tx descs'] = rdesc[0].split()[1]
+ interfaces[name]["tx descs"] = rdesc[0].split()[1]
return interfaces
@@ -508,17 +538,17 @@ class VPPUtil(object):
"""
pkgs = []
- cmd = 'dpkg -l | grep vpp'
+ cmd = "dpkg -l | grep vpp"
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
return pkgs
- lines = stdout.split('\n')
+ lines = stdout.split("\n")
for line in lines:
items = line.split()
if len(items) < 2:
continue
- pkg = {'name': items[1], 'version': items[2]}
+ pkg = {"name": items[1], "version": items[2]}
pkgs.append(pkg)
return pkgs
@@ -533,21 +563,21 @@ class VPPUtil(object):
"""
pkgs = []
- cmd = 'rpm -qa | grep vpp'
+ cmd = "rpm -qa | grep vpp"
(ret, stdout, stderr) = self.exec_command(cmd)
if ret != 0:
return pkgs
- lines = stdout.split('\n')
+ lines = stdout.split("\n")
for line in lines:
if len(line) == 0:
continue
items = line.split()
if len(items) < 2:
- pkg = {'name': items[0]}
+ pkg = {"name": items[0]}
else:
- pkg = {'name': items[1], 'version': items[2]}
+ pkg = {"name": items[1], "version": items[2]}
pkgs.append(pkg)
@@ -563,9 +593,9 @@ class VPPUtil(object):
"""
distro = self.get_linux_distro()
- if distro[0] == 'Ubuntu':
+ if distro[0] == "Ubuntu":
pkgs = self._get_installed_vpp_pkgs_ubuntu()
- elif distro[0] == 'CentOS Linux':
+ elif distro[0] == "CentOS Linux":
pkgs = self._get_installed_vpp_pkgs_centos()
else:
pkgs = self._get_installed_vpp_pkgs_centos()
@@ -594,7 +624,7 @@ class VPPUtil(object):
numa_list = []
for if_key in iface_keys:
try:
- numa_list.append(node['interfaces'][if_key].get('numa_node'))
+ numa_list.append(node["interfaces"][if_key].get("numa_node"))
except KeyError:
pass
@@ -617,12 +647,12 @@ class VPPUtil(object):
:type node: dict
"""
- cmd = 'service vpp restart'
+ cmd = "service vpp restart"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.
- format(cmd, node['host'],
- stdout, stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
@staticmethod
def start(node):
@@ -634,12 +664,12 @@ class VPPUtil(object):
:type node: dict
"""
- cmd = 'service vpp start'
+ cmd = "service vpp start"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.
- format(cmd, node['host'],
- stdout, stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
@staticmethod
def stop(node):
@@ -651,12 +681,12 @@ class VPPUtil(object):
:type node: dict
"""
- cmd = 'service vpp stop'
+ cmd = "service vpp stop"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- logging.debug('{} failed on node {} {} {}'.
- format(cmd, node['host'],
- stdout, stderr))
+ logging.debug(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
# noinspection RegExpRedundantEscape
@staticmethod
@@ -676,11 +706,11 @@ class VPPUtil(object):
if len(pkgs) == 0:
return "Not Installed", errors
- cmd = 'service vpp status'
+ cmd = "service vpp status"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
# Get the active status
- state = re.findall(r'Active:[\w (\)]+', stdout)[0].split(' ')
+ state = re.findall(r"Active:[\w (\)]+", stdout)[0].split(" ")
if len(state) > 2:
statestr = "{} {}".format(state[1], state[2])
else:
@@ -707,13 +737,10 @@ class VPPUtil(object):
"""
dist = distro.linux_distribution()
- if dist[0] == 'Ubuntu' or \
- dist[0] == 'CentOS Linux' or \
- dist[:7] == 'Red Hat':
+ if dist[0] == "Ubuntu" or dist[0] == "CentOS Linux" or dist[:7] == "Red Hat":
return dist
else:
- raise RuntimeError(
- 'Linux Distribution {} is not supported'.format(dist[0]))
+ raise RuntimeError("Linux Distribution {} is not supported".format(dist[0]))
@staticmethod
def version():
@@ -726,21 +753,21 @@ class VPPUtil(object):
"""
version = {}
- cmd = 'vppctl show version verbose'
+ cmd = "vppctl show version verbose"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
return version
- lines = stdout.split('\n')
+ lines = stdout.split("\n")
if len(lines[0]) != 0:
- if lines[0].split(' ')[0] == 'FileNotFoundError':
+ if lines[0].split(" ")[0] == "FileNotFoundError":
return version
for line in lines:
if len(line) == 0:
continue
- dct = line.split(':')
- version[dct[0]] = dct[1].lstrip(' ')
+ dct = line.split(":")
+ version[dct[0]] = dct[1].lstrip(" ")
return version
@@ -755,38 +782,40 @@ class VPPUtil(object):
"""
ifaces = []
- cmd = 'vppctl show bridge'
+ cmd = "vppctl show bridge"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.
- format(cmd, node['host'],
- stdout, stderr))
- lines = stdout.split('\r\n')
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
+ lines = stdout.split("\r\n")
bridges = []
for line in lines:
- if line == 'no bridge-domains in use':
+ if line == "no bridge-domains in use":
print(line)
return ifaces
if len(line) == 0:
continue
- lspl = line.lstrip(' ').split()
- if lspl[0] != 'BD-ID':
+ lspl = line.lstrip(" ").split()
+ if lspl[0] != "BD-ID":
bridges.append(lspl[0])
for bridge in bridges:
- cmd = 'vppctl show bridge {} detail'.format(bridge)
+ cmd = "vppctl show bridge {} detail".format(bridge)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.
- format(cmd, node['host'],
- stdout, stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(
+ cmd, node["host"], stdout, stderr
+ )
+ )
- lines = stdout.split('\r\n')
+ lines = stdout.split("\r\n")
for line in lines:
- iface = re.findall(r'[a-zA-z]+\d+/\d+/\d+', line)
+ iface = re.findall(r"[a-zA-z]+\d+/\d+/\d+", line)
if len(iface):
- ifcidx = {'name': iface[0], 'index': line.split()[1]}
+ ifcidx = {"name": iface[0], "index": line.split()[1]}
ifaces.append(ifcidx)
print(stdout)
diff --git a/extras/vpp_config/vpplib/VppGrubUtil.py b/extras/vpp_config/vpplib/VppGrubUtil.py
index f17efd8a868..976b20019c4 100644
--- a/extras/vpp_config/vpplib/VppGrubUtil.py
+++ b/extras/vpp_config/vpplib/VppGrubUtil.py
@@ -17,11 +17,11 @@ import re
from vpplib.VPPUtil import VPPUtil
-__all__ = ['VppGrubUtil']
+__all__ = ["VppGrubUtil"]
class VppGrubUtil(object):
- """ VPP Grub Utilities."""
+ """VPP Grub Utilities."""
def _get_current_cmdline(self):
"""
@@ -32,14 +32,14 @@ class VppGrubUtil(object):
"""
# Get the memory information using /proc/meminfo
- cmd = 'sudo cat /proc/cmdline'
+ cmd = "sudo cat /proc/cmdline"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} on node {} {} {}'.
- format(cmd, self._node['host'],
- stdout, stderr))
+ raise RuntimeError(
+ "{} on node {} {} {}".format(cmd, self._node["host"], stdout, stderr)
+ )
- self._current_cmdline = stdout.strip('\n')
+ self._current_cmdline = stdout.strip("\n")
def _get_default_cmdline(self):
"""
@@ -50,21 +50,24 @@ class VppGrubUtil(object):
"""
# Get the default grub cmdline
- rootdir = self._node['rootdir']
- gfile = self._node['cpu']['grub_config_file']
- grubcmdline = self._node['cpu']['grubcmdline']
- cmd = 'cat {}'.format(rootdir + gfile)
+ rootdir = self._node["rootdir"]
+ gfile = self._node["cpu"]["grub_config_file"]
+ grubcmdline = self._node["cpu"]["grubcmdline"]
+ cmd = "cat {}".format(rootdir + gfile)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} Executing failed on node {} {}'.
- format(cmd, self._node['host'], stderr))
+ raise RuntimeError(
+ "{} Executing failed on node {} {}".format(
+ cmd, self._node["host"], stderr
+ )
+ )
# Get the Default Linux command line, ignoring commented lines
- lines = stdout.split('\n')
+ lines = stdout.split("\n")
for line in lines:
- if line == '' or line[0] == '#':
+ if line == "" or line[0] == "#":
continue
- ldefault = re.findall(r'{}=.+'.format(grubcmdline), line)
+ ldefault = re.findall(r"{}=.+".format(grubcmdline), line)
if ldefault:
self._default_cmdline = ldefault[0]
break
@@ -96,9 +99,9 @@ class VppGrubUtil(object):
:returns: The command line
:rtype: string
"""
- grubcmdline = self._node['cpu']['grubcmdline']
+ grubcmdline = self._node["cpu"]["grubcmdline"]
cmdline = self._default_cmdline
- value = cmdline.split('{}='.format(grubcmdline))[1]
+ value = cmdline.split("{}=".format(grubcmdline))[1]
value = value.rstrip('"').lstrip('"')
# jadfix intel_pstate=disable sometimes cause networks to
@@ -111,43 +114,43 @@ class VppGrubUtil(object):
# value = '{} intel_pstate=disable'.format(value)
# Replace isolcpus with ours
- isolcpus = re.findall(r'isolcpus=[\w+\-,]+', value)
+ isolcpus = re.findall(r"isolcpus=[\w+\-,]+", value)
if not isolcpus:
- if isolated_cpus != '':
+ if isolated_cpus != "":
value = "{} isolcpus={}".format(value, isolated_cpus)
else:
- if isolated_cpus != '':
- value = re.sub(r'isolcpus=[\w+\-,]+',
- 'isolcpus={}'.format(isolated_cpus),
- value)
+ if isolated_cpus != "":
+ value = re.sub(
+ r"isolcpus=[\w+\-,]+", "isolcpus={}".format(isolated_cpus), value
+ )
else:
- value = re.sub(r'isolcpus=[\w+\-,]+', '', value)
+ value = re.sub(r"isolcpus=[\w+\-,]+", "", value)
- nohz = re.findall(r'nohz_full=[\w+\-,]+', value)
+ nohz = re.findall(r"nohz_full=[\w+\-,]+", value)
if not nohz:
- if isolated_cpus != '':
+ if isolated_cpus != "":
value = "{} nohz_full={}".format(value, isolated_cpus)
else:
- if isolated_cpus != '':
- value = re.sub(r'nohz_full=[\w+\-,]+',
- 'nohz_full={}'.format(isolated_cpus),
- value)
+ if isolated_cpus != "":
+ value = re.sub(
+ r"nohz_full=[\w+\-,]+", "nohz_full={}".format(isolated_cpus), value
+ )
else:
- value = re.sub(r'nohz_full=[\w+\-,]+', '', value)
+ value = re.sub(r"nohz_full=[\w+\-,]+", "", value)
- rcu = re.findall(r'rcu_nocbs=[\w+\-,]+', value)
+ rcu = re.findall(r"rcu_nocbs=[\w+\-,]+", value)
if not rcu:
- if isolated_cpus != '':
+ if isolated_cpus != "":
value = "{} rcu_nocbs={}".format(value, isolated_cpus)
else:
- if isolated_cpus != '':
- value = re.sub(r'rcu_nocbs=[\w+\-,]+',
- 'rcu_nocbs={}'.format(isolated_cpus),
- value)
+ if isolated_cpus != "":
+ value = re.sub(
+ r"rcu_nocbs=[\w+\-,]+", "rcu_nocbs={}".format(isolated_cpus), value
+ )
else:
- value = re.sub(r'rcu_nocbs=[\w+\-,]+', '', value)
+ value = re.sub(r"rcu_nocbs=[\w+\-,]+", "", value)
- value = value.lstrip(' ').rstrip(' ')
+ value = value.lstrip(" ").rstrip(" ")
cmdline = '{}="{}"'.format(grubcmdline, value)
return cmdline
@@ -167,69 +170,68 @@ class VppGrubUtil(object):
if len(vpp_cmdline):
# Update grub
# Save the original file
- rootdir = node['rootdir']
- grubcmdline = node['cpu']['grubcmdline']
- ofilename = rootdir + node['cpu']['grub_config_file'] + '.orig'
- filename = rootdir + node['cpu']['grub_config_file']
+ rootdir = node["rootdir"]
+ grubcmdline = node["cpu"]["grubcmdline"]
+ ofilename = rootdir + node["cpu"]["grub_config_file"] + ".orig"
+ filename = rootdir + node["cpu"]["grub_config_file"]
# Write the output file
# Does a copy of the original file exist, if not create one
- (ret, stdout, stderr) = VPPUtil.exec_command(
- 'ls {}'.format(ofilename))
+ (ret, stdout, stderr) = VPPUtil.exec_command("ls {}".format(ofilename))
if ret != 0:
- if stdout.strip('\n') != ofilename:
- cmd = 'sudo cp {} {}'.format(filename, ofilename)
+ if stdout.strip("\n") != ofilename:
+ cmd = "sudo cp {} {}".format(filename, ofilename)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {}'.
- format(cmd, self._node['host'],
- stderr))
+ raise RuntimeError(
+ "{} failed on node {} {}".format(
+ cmd, self._node["host"], stderr
+ )
+ )
# Get the contents of the current grub config file
- cmd = 'cat {}'.format(filename)
+ cmd = "cat {}".format(filename)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {}'.format(
- cmd,
- self._node['host'],
- stderr))
+ raise RuntimeError(
+ "{} failed on node {} {}".format(cmd, self._node["host"], stderr)
+ )
# Write the new contents
# Get the Default Linux command line, ignoring commented lines
content = ""
- lines = stdout.split('\n')
+ lines = stdout.split("\n")
for line in lines:
- if line == '':
- content += line + '\n'
+ if line == "":
+ content += line + "\n"
continue
- if line[0] == '#':
- content += line + '\n'
+ if line[0] == "#":
+ content += line + "\n"
continue
- ldefault = re.findall(r'{}=.+'.format(grubcmdline), line)
+ ldefault = re.findall(r"{}=.+".format(grubcmdline), line)
if ldefault:
- content += vpp_cmdline + '\n'
+ content += vpp_cmdline + "\n"
else:
- content += line + '\n'
+ content += line + "\n"
content = content.replace(r"`", r"\`")
- content = content.rstrip('\n')
+ content = content.rstrip("\n")
cmd = "sudo cat > {0} << EOF\n{1}\n".format(filename, content)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {}'.format(
- cmd,
- self._node['host'],
- stderr))
+ raise RuntimeError(
+ "{} failed on node {} {}".format(cmd, self._node["host"], stderr)
+ )
return vpp_cmdline
def __init__(self, node):
distro = VPPUtil.get_linux_distro()
- if distro[0] == 'Ubuntu':
- node['cpu']['grubcmdline'] = 'GRUB_CMDLINE_LINUX_DEFAULT'
+ if distro[0] == "Ubuntu":
+ node["cpu"]["grubcmdline"] = "GRUB_CMDLINE_LINUX_DEFAULT"
else:
- node['cpu']['grubcmdline'] = 'GRUB_CMDLINE_LINUX'
+ node["cpu"]["grubcmdline"] = "GRUB_CMDLINE_LINUX"
self._node = node
self._current_cmdline = ""
diff --git a/extras/vpp_config/vpplib/VppHugePageUtil.py b/extras/vpp_config/vpplib/VppHugePageUtil.py
index 3a632828883..48991090f04 100644
--- a/extras/vpp_config/vpplib/VppHugePageUtil.py
+++ b/extras/vpp_config/vpplib/VppHugePageUtil.py
@@ -33,6 +33,7 @@ class VppHugePageUtil(object):
"""
Huge Page Utilities
"""
+
def hugepages_dryrun_apply(self):
"""
Apply the huge page configuration
@@ -40,23 +41,23 @@ class VppHugePageUtil(object):
"""
node = self._node
- hugepages = node['hugepages']
+ hugepages = node["hugepages"]
vpp_hugepage_config = VPP_HUGEPAGE_CONFIG.format(
- nr_hugepages=hugepages['total'],
- max_map_count=hugepages['max_map_count'],
- shmmax=hugepages['shmax'])
+ nr_hugepages=hugepages["total"],
+ max_map_count=hugepages["max_map_count"],
+ shmmax=hugepages["shmax"],
+ )
- rootdir = node['rootdir']
- filename = rootdir + node['hugepages']['hugepage_config_file']
+ rootdir = node["rootdir"]
+ filename = rootdir + node["hugepages"]["hugepage_config_file"]
- cmd = 'echo "{0}" | sudo tee {1}'.\
- format(vpp_hugepage_config, filename)
+ cmd = 'echo "{0}" | sudo tee {1}'.format(vpp_hugepage_config, filename)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.
- format(cmd, node['host'],
- stdout, stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
def get_actual_huge_pages(self):
"""
@@ -68,25 +69,26 @@ class VppHugePageUtil(object):
"""
# Get the memory information using /proc/meminfo
- cmd = 'sudo cat /proc/meminfo'
+ cmd = "sudo cat /proc/meminfo"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
raise RuntimeError(
- '{} failed on node {} {} {}'.format(
- cmd, self._node['host'],
- stdout, stderr))
-
- total = re.findall(r'HugePages_Total:\s+\w+', stdout)
- free = re.findall(r'HugePages_Free:\s+\w+', stdout)
- size = re.findall(r'Hugepagesize:\s+\w+\s+\w+', stdout)
- memtotal = re.findall(r'MemTotal:\s+\w+\s+\w+', stdout)
- memfree = re.findall(r'MemFree:\s+\w+\s+\w+', stdout)
-
- total = total[0].split(':')[1].lstrip()
- free = free[0].split(':')[1].lstrip()
- size = size[0].split(':')[1].lstrip()
- memtotal = memtotal[0].split(':')[1].lstrip()
- memfree = memfree[0].split(':')[1].lstrip()
+ "{} failed on node {} {} {}".format(
+ cmd, self._node["host"], stdout, stderr
+ )
+ )
+
+ total = re.findall(r"HugePages_Total:\s+\w+", stdout)
+ free = re.findall(r"HugePages_Free:\s+\w+", stdout)
+ size = re.findall(r"Hugepagesize:\s+\w+\s+\w+", stdout)
+ memtotal = re.findall(r"MemTotal:\s+\w+\s+\w+", stdout)
+ memfree = re.findall(r"MemFree:\s+\w+\s+\w+", stdout)
+
+ total = total[0].split(":")[1].lstrip()
+ free = free[0].split(":")[1].lstrip()
+ size = size[0].split(":")[1].lstrip()
+ memtotal = memtotal[0].split(":")[1].lstrip()
+ memfree = memfree[0].split(":")[1].lstrip()
return total, free, size, memtotal, memfree
def show_huge_pages(self):
@@ -96,17 +98,13 @@ class VppHugePageUtil(object):
"""
node = self._node
- hugepages = node['hugepages']
- print (" {:30}: {}".format("Total System Memory",
- hugepages['memtotal']))
- print (" {:30}: {}".format("Total Free Memory",
- hugepages['memfree']))
- print (" {:30}: {}".format("Actual Huge Page Total",
- hugepages['actual_total']))
- print (" {:30}: {}".format("Configured Huge Page Total",
- hugepages['total']))
- print (" {:30}: {}".format("Huge Pages Free", hugepages['free']))
- print (" {:30}: {}".format("Huge Page Size", hugepages['size']))
+ hugepages = node["hugepages"]
+ print(" {:30}: {}".format("Total System Memory", hugepages["memtotal"]))
+ print(" {:30}: {}".format("Total Free Memory", hugepages["memfree"]))
+ print(" {:30}: {}".format("Actual Huge Page Total", hugepages["actual_total"]))
+ print(" {:30}: {}".format("Configured Huge Page Total", hugepages["total"]))
+ print(" {:30}: {}".format("Huge Pages Free", hugepages["free"]))
+ print(" {:30}: {}".format("Huge Page Size", hugepages["size"]))
def get_huge_page_config(self):
"""
@@ -115,7 +113,7 @@ class VppHugePageUtil(object):
:returns: The map max count and shmmax
"""
- total = self._node['hugepages']['total']
+ total = self._node["hugepages"]["total"]
max_map_count = int(total) * 2 + 1024
shmmax = int(total) * 2 * 1024 * 1024
return max_map_count, shmmax
diff --git a/extras/vpp_config/vpplib/VppPCIUtil.py b/extras/vpp_config/vpplib/VppPCIUtil.py
index ceda46f97b9..032a262c21c 100644
--- a/extras/vpp_config/vpplib/VppPCIUtil.py
+++ b/extras/vpp_config/vpplib/VppPCIUtil.py
@@ -23,7 +23,7 @@ from vpplib.VPPUtil import VPPUtil
DPDK_SCRIPT = "/vpp/vpp-config/scripts/dpdk-devbind.py"
# PCI Device id regular expresssion
-PCI_DEV_ID_REGEX = '[0-9A-Fa-f]+:[0-9A-Fa-f]+:[0-9A-Fa-f]+.[0-9A-Fa-f]+'
+PCI_DEV_ID_REGEX = "[0-9A-Fa-f]+:[0-9A-Fa-f]+:[0-9A-Fa-f]+.[0-9A-Fa-f]+"
class VppPCIUtil(object):
@@ -45,51 +45,47 @@ class VppPCIUtil(object):
devices = {}
ids = re.findall(PCI_DEV_ID_REGEX, device_string)
- descriptions = re.findall(r'\'([\s\S]*?)\'', device_string)
- unused = re.findall(r'unused=\w+|unused=', device_string)
+ descriptions = re.findall(r"\'([\s\S]*?)\'", device_string)
+ unused = re.findall(r"unused=\w+|unused=", device_string)
for i, j in enumerate(ids):
- device = {'description': descriptions[i]}
+ device = {"description": descriptions[i]}
if unused:
- device['unused'] = unused[i].split('=')[1].split(',')
+ device["unused"] = unused[i].split("=")[1].split(",")
- cmd = 'ls /sys/bus/pci/devices/{}/driver/module/drivers'. \
- format(ids[i])
+ cmd = "ls /sys/bus/pci/devices/{}/driver/module/drivers".format(ids[i])
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret == 0:
- device['driver'] = stdout.split(':')[1].rstrip('\n')
+ device["driver"] = stdout.split(":")[1].rstrip("\n")
- cmd = 'cat /sys/bus/pci/devices/{}/numa_node'.format(ids[i])
+ cmd = "cat /sys/bus/pci/devices/{}/numa_node".format(ids[i])
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed {} {}'.
- format(cmd, stderr, stdout))
- numa_node = stdout.rstrip('\n')
- if numa_node == '-1':
- device['numa_node'] = '0'
+ raise RuntimeError("{} failed {} {}".format(cmd, stderr, stdout))
+ numa_node = stdout.rstrip("\n")
+ if numa_node == "-1":
+ device["numa_node"] = "0"
else:
- device['numa_node'] = numa_node
+ device["numa_node"] = numa_node
interfaces = []
- device['interfaces'] = []
- cmd = 'ls /sys/bus/pci/devices/{}/net'.format(ids[i])
+ device["interfaces"] = []
+ cmd = "ls /sys/bus/pci/devices/{}/net".format(ids[i])
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret == 0:
- interfaces = stdout.rstrip('\n').split()
- device['interfaces'] = interfaces
+ interfaces = stdout.rstrip("\n").split()
+ device["interfaces"] = interfaces
l2_addrs = []
for intf in interfaces:
- cmd = 'cat /sys/bus/pci/devices/{}/net/{}/address'.format(
- ids[i], intf)
+ cmd = "cat /sys/bus/pci/devices/{}/net/{}/address".format(ids[i], intf)
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed {} {}'.
- format(cmd, stderr, stdout))
+ raise RuntimeError("{} failed {} {}".format(cmd, stderr, stdout))
- l2_addrs.append(stdout.rstrip('\n'))
+ l2_addrs.append(stdout.rstrip("\n"))
- device['l2addr'] = l2_addrs
+ device["l2addr"] = l2_addrs
devices[ids[i]] = device
@@ -112,66 +108,62 @@ class VppPCIUtil(object):
"""
node = self._node
- rootdir = node['rootdir']
+ rootdir = node["rootdir"]
dpdk_script = rootdir + DPDK_SCRIPT
- cmd = dpdk_script + ' --status'
+ cmd = dpdk_script + " --status"
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {}'.format(
- cmd,
- node['host'],
- stderr))
+ raise RuntimeError(
+ "{} failed on node {} {}".format(cmd, node["host"], stderr)
+ )
# Get the network devices using the DPDK
# First get everything after using DPDK
- stda = stdout.split('Network devices using DPDK-compatible driver')[1]
+ stda = stdout.split("Network devices using DPDK-compatible driver")[1]
# Then get everything before using kernel driver
- using_dpdk = stda.split('Network devices using kernel driver')[0]
+ using_dpdk = stda.split("Network devices using kernel driver")[0]
self._dpdk_devices = self._create_device_list(using_dpdk)
# Get the network devices using the kernel
- stda = stdout.split('Network devices using kernel driver')[1]
- using_kernel = stda.split('Other network devices')[0]
+ stda = stdout.split("Network devices using kernel driver")[1]
+ using_kernel = stda.split("Other network devices")[0]
self._kernel_devices = self._create_device_list(using_kernel)
# Get the other network devices
- stda = stdout.split('Other network devices')[1]
- other = stda.split('Crypto devices using DPDK-compatible driver')[0]
+ stda = stdout.split("Other network devices")[1]
+ other = stda.split("Crypto devices using DPDK-compatible driver")[0]
self._other_devices = self._create_device_list(other)
# Get the crypto devices using the DPDK
- stda = stdout.split('Crypto devices using DPDK-compatible driver')[1]
- crypto_using_dpdk = stda.split('Crypto devices using kernel driver')[0]
- self._crypto_dpdk_devices = self._create_device_list(
- crypto_using_dpdk)
+ stda = stdout.split("Crypto devices using DPDK-compatible driver")[1]
+ crypto_using_dpdk = stda.split("Crypto devices using kernel driver")[0]
+ self._crypto_dpdk_devices = self._create_device_list(crypto_using_dpdk)
# Get the network devices using the kernel
- stda = stdout.split('Crypto devices using kernel driver')[1]
- crypto_using_kernel = stda.split('Other crypto devices')[0]
- self._crypto_kernel_devices = self._create_device_list(
- crypto_using_kernel)
+ stda = stdout.split("Crypto devices using kernel driver")[1]
+ crypto_using_kernel = stda.split("Other crypto devices")[0]
+ self._crypto_kernel_devices = self._create_device_list(crypto_using_kernel)
# Get the other network devices
- crypto_other = stdout.split('Other crypto devices')[1]
+ crypto_other = stdout.split("Other crypto devices")[1]
self._crypto_other_devices = self._create_device_list(crypto_other)
# Get the devices used by the kernel
for devk in self._kernel_devices.items():
dvid = devk[0]
device = devk[1]
- for i in device['interfaces']:
+ for i in device["interfaces"]:
cmd = "ip addr show " + i
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {}'.format(
- cmd,
- node['host'],
- stderr))
- lstate = re.findall(r'state \w+', stdout)[0].split(' ')[1]
+ raise RuntimeError(
+ "{} failed on node {} {}".format(cmd, node["host"], stderr)
+ )
+ lstate = re.findall(r"state \w+", stdout)[0].split(" ")[1]
# Take care of the links that are UP
- if lstate == 'UP':
- device['linkup'] = True
+ if lstate == "UP":
+ device["linkup"] = True
self._link_up_devices[dvid] = device
for devl in self._link_up_devices.items():
@@ -234,18 +226,18 @@ class VppPCIUtil(object):
"""
- name = 'port' + str(len(interfaces))
+ name = "port" + str(len(interfaces))
interfaces[name] = {}
- interfaces[name]['pci_address'] = device_id
- interfaces[name]['numa_node'] = device['numa_node']
- if 'l2addr' in device:
- l2_addrs = device['l2addr']
+ interfaces[name]["pci_address"] = device_id
+ interfaces[name]["numa_node"] = device["numa_node"]
+ if "l2addr" in device:
+ l2_addrs = device["l2addr"]
for i, j in enumerate(l2_addrs):
if i > 0:
- mname = 'mac_address' + str(i + 1)
+ mname = "mac_address" + str(i + 1)
interfaces[name][mname] = l2_addrs[i]
else:
- interfaces[name]['mac_address'] = l2_addrs[i]
+ interfaces[name]["mac_address"] = l2_addrs[i]
@staticmethod
def show_vpp_devices(devices, show_interfaces=True, show_header=True):
@@ -261,34 +253,33 @@ class VppPCIUtil(object):
"""
if show_interfaces:
- header = "{:15} {:25} {:50}".format("PCI ID",
- "Kernel Interface(s)",
- "Description")
+ header = "{:15} {:25} {:50}".format(
+ "PCI ID", "Kernel Interface(s)", "Description"
+ )
else:
- header = "{:15} {:50}".format("PCI ID",
- "Description")
- dashseparator = ("-" * (len(header) - 2))
+ header = "{:15} {:50}".format("PCI ID", "Description")
+ dashseparator = "-" * (len(header) - 2)
if show_header is True:
- print (header)
- print (dashseparator)
+ print(header)
+ print(dashseparator)
for dit in devices.items():
dvid = dit[0]
device = dit[1]
if show_interfaces:
- interfaces = device['interfaces']
- interface = ''
+ interfaces = device["interfaces"]
+ interface = ""
for i, j in enumerate(interfaces):
if i > 0:
- interface += ',' + interfaces[i]
+ interface += "," + interfaces[i]
else:
interface = interfaces[i]
- print ("{:15} {:25} {:50}".format(
- dvid, interface, device['description']))
+ print(
+ "{:15} {:25} {:50}".format(dvid, interface, device["description"])
+ )
else:
- print ("{:15} {:50}".format(
- dvid, device['description']))
+ print("{:15} {:50}".format(dvid, device["description"]))
@staticmethod
def unbind_vpp_device(node, device_id):
@@ -301,14 +292,14 @@ class VppPCIUtil(object):
:type device_id: string
"""
- rootdir = node['rootdir']
+ rootdir = node["rootdir"]
dpdk_script = rootdir + DPDK_SCRIPT
- cmd = dpdk_script + ' -u ' + ' ' + device_id
+ cmd = dpdk_script + " -u " + " " + device_id
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- raise RuntimeError('{} failed on node {} {} {}'.format(
- cmd, node['host'],
- stdout, stderr))
+ raise RuntimeError(
+ "{} failed on node {} {} {}".format(cmd, node["host"], stdout, stderr)
+ )
@staticmethod
def bind_vpp_device(node, driver, device_id):
@@ -324,14 +315,14 @@ class VppPCIUtil(object):
:returns ret: Command return code
"""
- rootdir = node['rootdir']
+ rootdir = node["rootdir"]
dpdk_script = rootdir + DPDK_SCRIPT
- cmd = dpdk_script + ' -b ' + driver + ' ' + device_id
+ cmd = dpdk_script + " -b " + driver + " " + device_id
(ret, stdout, stderr) = VPPUtil.exec_command(cmd)
if ret != 0:
- logging.error('{} failed on node {}'.format(
- cmd, node['host'], stdout, stderr))
- logging.error('{} {}'.format(
- stdout, stderr))
+ logging.error(
+ "{} failed on node {}".format(cmd, node["host"], stdout, stderr)
+ )
+ logging.error("{} {}".format(stdout, stderr))
return ret
diff --git a/extras/vpp_config/vpplib/constants.py b/extras/vpp_config/vpplib/constants.py
index 051a21cf023..63428b0c4d4 100644
--- a/extras/vpp_config/vpplib/constants.py
+++ b/extras/vpp_config/vpplib/constants.py
@@ -18,31 +18,31 @@ class Constants(object):
"""Constants used in CSIT."""
# OpenVPP testing directory location at topology nodes
- REMOTE_FW_DIR = '/tmp/openvpp-testing'
+ REMOTE_FW_DIR = "/tmp/openvpp-testing"
# shell scripts location
- RESOURCES_LIB_SH = 'resources/libraries/bash'
+ RESOURCES_LIB_SH = "resources/libraries/bash"
# vat templates location
- RESOURCES_TPL_VAT = 'resources/templates/vat'
+ RESOURCES_TPL_VAT = "resources/templates/vat"
# OpenVPP VAT binary name
- VAT_BIN_NAME = 'vpp_api_test'
+ VAT_BIN_NAME = "vpp_api_test"
# QEMU version to install
- QEMU_INSTALL_VERSION = 'qemu-2.5.0'
+ QEMU_INSTALL_VERSION = "qemu-2.5.0"
# QEMU install directory
- QEMU_INSTALL_DIR = '/opt/qemu-2.5.0'
+ QEMU_INSTALL_DIR = "/opt/qemu-2.5.0"
# Honeycomb directory location at topology nodes:
- REMOTE_HC_DIR = '/opt/honeycomb'
+ REMOTE_HC_DIR = "/opt/honeycomb"
# Honeycomb persistence files location
- REMOTE_HC_PERSIST = '/var/lib/honeycomb/persist'
+ REMOTE_HC_PERSIST = "/var/lib/honeycomb/persist"
# Honeycomb templates location
- RESOURCES_TPL_HC = 'resources/templates/honeycomb'
+ RESOURCES_TPL_HC = "resources/templates/honeycomb"
# ODL Client Restconf listener port
ODL_PORT = 8181
diff --git a/src/plugins/map/examples/gen-rules.py b/src/plugins/map/examples/gen-rules.py
index 7964aa9a359..d22d4633ef6 100755
--- a/src/plugins/map/examples/gen-rules.py
+++ b/src/plugins/map/examples/gen-rules.py
@@ -20,38 +20,63 @@ import sys
# map add domain ip4-pfx <pfx> ip6-pfx ::/0 ip6-src <ip6-src> ea-bits-len 0 psid-offset 6 psid-len 6
# map add rule index <0> psid <psid> ip6-dst <ip6-dst>
-def_ip4_pfx = '192.0.2.0/24'
-def_ip6_pfx = '2001:db8::/32'
-def_ip6_src = '2001:db8::1'
+def_ip4_pfx = "192.0.2.0/24"
+def_ip6_pfx = "2001:db8::/32"
+def_ip6_src = "2001:db8::1"
def_psid_offset = 6
def_psid_len = 6
def_ea_bits_len = 0
-parser = argparse.ArgumentParser(description='MAP VPP configuration generator')
-parser.add_argument('-t', action="store", dest="mapmode")
-parser.add_argument('-f', action="store", dest="format", default="vpp")
-parser.add_argument('--ip4-prefix', action="store", dest="ip4_pfx", default=def_ip4_pfx)
-parser.add_argument('--ip6-prefix', action="store", dest="ip6_pfx", default=def_ip6_pfx)
-parser.add_argument('--ip6-src', action="store", dest="ip6_src", default=def_ip6_src)
-parser.add_argument('--psid-len', action="store", dest="psid_len", default=def_psid_len)
-parser.add_argument('--psid-offset', action="store", dest="psid_offset", default=def_psid_offset)
-parser.add_argument('--ea-bits-len', action="store", dest="ea_bits_len", default=def_ea_bits_len)
+parser = argparse.ArgumentParser(description="MAP VPP configuration generator")
+parser.add_argument("-t", action="store", dest="mapmode")
+parser.add_argument("-f", action="store", dest="format", default="vpp")
+parser.add_argument("--ip4-prefix", action="store", dest="ip4_pfx", default=def_ip4_pfx)
+parser.add_argument("--ip6-prefix", action="store", dest="ip6_pfx", default=def_ip6_pfx)
+parser.add_argument("--ip6-src", action="store", dest="ip6_src", default=def_ip6_src)
+parser.add_argument("--psid-len", action="store", dest="psid_len", default=def_psid_len)
+parser.add_argument(
+ "--psid-offset", action="store", dest="psid_offset", default=def_psid_offset
+)
+parser.add_argument(
+ "--ea-bits-len", action="store", dest="ea_bits_len", default=def_ea_bits_len
+)
args = parser.parse_args()
#
# Print domain
#
def domain_print(i, ip4_pfx, ip6_pfx, ip6_src, eabits_len, psid_offset, psid_len):
- if format == 'vpp':
- print("map add domain ip4-pfx " + ip4_pfx + " ip6-pfx", ip6_pfx, "ip6-src " + ip6_src +
- " ea-bits-len", eabits_len, "psid-offset", psid_offset, "psid-len", psid_len)
- if format == 'confd':
- print("vpp softwire softwire-instances softwire-instance", i, "br-ipv6 " + ip6_src +
- " ipv6-prefix " + ip6_pfx + " ipv4-prefix " + ip4_pfx +
- " ea-bits-len", eabits_len, "psid-offset", psid_offset, "psid-len", psid_len)
- if format == 'xml':
+ if format == "vpp":
+ print(
+ "map add domain ip4-pfx " + ip4_pfx + " ip6-pfx",
+ ip6_pfx,
+ "ip6-src " + ip6_src + " ea-bits-len",
+ eabits_len,
+ "psid-offset",
+ psid_offset,
+ "psid-len",
+ psid_len,
+ )
+ if format == "confd":
+ print(
+ "vpp softwire softwire-instances softwire-instance",
+ i,
+ "br-ipv6 "
+ + ip6_src
+ + " ipv6-prefix "
+ + ip6_pfx
+ + " ipv4-prefix "
+ + ip4_pfx
+ + " ea-bits-len",
+ eabits_len,
+ "psid-offset",
+ psid_offset,
+ "psid-len",
+ psid_len,
+ )
+ if format == "xml":
print("<softwire-instance>")
- print("<id>", i, "</id>");
+ print("<id>", i, "</id>")
print(" <br-ipv6>" + ip6_src + "</br-ipv6>")
print(" <ipv6-prefix>" + ip6_pfx + "</ipv6-prefix>")
print(" <ipv4-prefix>" + ip4_pfx + "</ipv4-prefix>")
@@ -59,32 +84,54 @@ def domain_print(i, ip4_pfx, ip6_pfx, ip6_src, eabits_len, psid_offset, psid_len
print(" <psid-len>", psid_len, "</psid-len>")
print(" <psid-offset>", psid_offset, "</psid-offset>")
+
def domain_print_end():
- if format == 'xml':
+ if format == "xml":
print("</softwire-instance>")
+
def rule_print(i, psid, dst):
- if format == 'vpp':
+ if format == "vpp":
print("map add rule index", i, "psid", psid, "ip6-dst", dst)
- if format == 'confd':
+ if format == "confd":
print("binding", psid, "ipv6-addr", dst)
- if format == 'xml':
+ if format == "xml":
print(" <binding>")
print(" <psid>", psid, "</psid>")
print(" <ipv6-addr>", dst, "</ipv6-addr>")
print(" </binding>")
+
#
# Algorithmic mapping Shared IPv4 address
#
-def algo(ip4_pfx_str, ip6_pfx_str, ip6_src_str, ea_bits_len, psid_offset, psid_len, ip6_src_ecmp = False):
- domain_print(0, ip4_pfx_str, ip6_pfx_str, ip6_src_str, ea_bits_len, psid_offset, psid_len)
+def algo(
+ ip4_pfx_str,
+ ip6_pfx_str,
+ ip6_src_str,
+ ea_bits_len,
+ psid_offset,
+ psid_len,
+ ip6_src_ecmp=False,
+):
+ domain_print(
+ 0, ip4_pfx_str, ip6_pfx_str, ip6_src_str, ea_bits_len, psid_offset, psid_len
+ )
domain_print_end()
+
#
# 1:1 Full IPv4 address
#
-def lw46(ip4_pfx_str, ip6_pfx_str, ip6_src_str, ea_bits_len, psid_offset, psid_len, ip6_src_ecmp = False):
+def lw46(
+ ip4_pfx_str,
+ ip6_pfx_str,
+ ip6_src_str,
+ ea_bits_len,
+ psid_offset,
+ psid_len,
+ ip6_src_ecmp=False,
+):
ip4_pfx = ipaddress.ip_network(ip4_pfx_str)
ip6_src = ipaddress.ip_address(ip6_src_str)
ip6_dst = ipaddress.ip_network(ip6_pfx_str)
@@ -92,15 +139,26 @@ def lw46(ip4_pfx_str, ip6_pfx_str, ip6_src_str, ea_bits_len, psid_offset, psid_l
mod = ip4_pfx.num_addresses / 1024
for i in range(ip4_pfx.num_addresses):
- domain_print(i, str(ip4_pfx[i]) + "/32", str(ip6_dst[i]) + "/128", str(ip6_src), 0, 0, 0)
+ domain_print(
+ i, str(ip4_pfx[i]) + "/32", str(ip6_dst[i]) + "/128", str(ip6_src), 0, 0, 0
+ )
domain_print_end()
if ip6_src_ecmp and not i % mod:
ip6_src = ip6_src + 1
+
#
# 1:1 Shared IPv4 address, shared BR (16) VPP CLI
#
-def lw46_shared(ip4_pfx_str, ip6_pfx_str, ip6_src_str, ea_bits_len, psid_offset, psid_len, ip6_src_ecmp = False):
+def lw46_shared(
+ ip4_pfx_str,
+ ip6_pfx_str,
+ ip6_src_str,
+ ea_bits_len,
+ psid_offset,
+ psid_len,
+ ip6_src_ecmp=False,
+):
ip4_pfx = ipaddress.ip_network(ip4_pfx_str)
ip6_src = ipaddress.ip_address(ip6_src_str)
ip6_dst = ipaddress.ip_network(ip6_pfx_str)
@@ -109,7 +167,7 @@ def lw46_shared(ip4_pfx_str, ip6_pfx_str, ip6_src_str, ea_bits_len, psid_offset,
for i in range(ip4_pfx.num_addresses):
domain_print(i, str(ip4_pfx[i]) + "/32", "::/0", str(ip6_src), 0, 0, psid_len)
for psid in range(0x1 << int(psid_len)):
- rule_print(i, psid, str(ip6_dst[(i * (0x1<<int(psid_len))) + psid]))
+ rule_print(i, psid, str(ip6_dst[(i * (0x1 << int(psid_len))) + psid]))
domain_print_end()
if ip6_src_ecmp and not i % mod:
ip6_src = ip6_src + 1
@@ -118,7 +176,15 @@ def lw46_shared(ip4_pfx_str, ip6_pfx_str, ip6_src_str, ea_bits_len, psid_offset,
#
# 1:1 Shared IPv4 address, shared BR
#
-def lw46_shared_b(ip4_pfx_str, ip6_pfx_str, ip6_src_str, ea_bits_len, psid_offset, psid_len, ip6_src_ecmp = False):
+def lw46_shared_b(
+ ip4_pfx_str,
+ ip6_pfx_str,
+ ip6_src_str,
+ ea_bits_len,
+ psid_offset,
+ psid_len,
+ ip6_src_ecmp=False,
+):
ip4_pfx = ipaddress.ip_network(ip4_pfx_str)
ip6_src = ipaddress.ip_address(ip6_src_str)
ip6_dst = list(ipaddress.ip_network(ip6_pfx_str).subnets(new_prefix=56))
@@ -127,15 +193,16 @@ def lw46_shared_b(ip4_pfx_str, ip6_pfx_str, ip6_src_str, ea_bits_len, psid_offse
for i in range(ip4_pfx.num_addresses):
domain_print(i, str(ip4_pfx[i]) + "/32", "::/0", str(ip6_src), 0, 0, psid_len)
for psid in range(0x1 << psid_len):
- enduserprefix = list(ip6_dst.pop(0).subnets(new_prefix=64))[255-1]
- rule_print(i, psid, enduserprefix[(i * (0x1<<psid_len)) + psid])
+ enduserprefix = list(ip6_dst.pop(0).subnets(new_prefix=64))[255 - 1]
+ rule_print(i, psid, enduserprefix[(i * (0x1 << psid_len)) + psid])
domain_print_end()
if ip6_src_ecmp and not i % mod:
ip6_src = ip6_src + 1
def xml_header_print():
- print('''
+ print(
+ """
<?xml version="1.0" encoding="UTF-8"?>
<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<capabilities>
@@ -156,10 +223,13 @@ def xml_header_print():
<softwire>
<softwire-instances>
- ''')
+ """
+ )
+
def xml_footer_print():
- print('''
+ print(
+ """
</softwire-instances>
</softwire>
</vpp>
@@ -175,12 +245,20 @@ def xml_footer_print():
</rpc>
]]>]]>
- ''')
+ """
+ )
format = args.format
-if format == 'xml':
+if format == "xml":
xml_header_print()
-globals()[args.mapmode](args.ip4_pfx, args.ip6_pfx, args.ip6_src, args.ea_bits_len, args.psid_offset, args.psid_len)
-if format == 'xml':
+globals()[args.mapmode](
+ args.ip4_pfx,
+ args.ip6_pfx,
+ args.ip6_src,
+ args.ea_bits_len,
+ args.psid_offset,
+ args.psid_len,
+)
+if format == "xml":
xml_footer_print()
diff --git a/src/plugins/map/examples/test_map.py b/src/plugins/map/examples/test_map.py
index 7a48964b3f2..02df64015a2 100755
--- a/src/plugins/map/examples/test_map.py
+++ b/src/plugins/map/examples/test_map.py
@@ -1,10 +1,10 @@
#!/usr/bin/env python3
-import time,argparse,sys,cmd, unittest
+import time, argparse, sys, cmd, unittest
from ipaddress import *
-parser = argparse.ArgumentParser(description='VPP MAP test')
-parser.add_argument('-i', nargs='*', action="store", dest="inputdir")
+parser = argparse.ArgumentParser(description="VPP MAP test")
+parser.add_argument("-i", nargs="*", action="store", dest="inputdir")
args = parser.parse_args()
for dir in args.inputdir:
@@ -14,115 +14,150 @@ from vpp_papi import *
#
# 1:1 Shared IPv4 address, shared BR (16) VPP CLI
#
-def lw46_shared(ip4_pfx_str, ip6_pfx_str, ip6_src_str, ea_bits_len, psid_offset, psid_len, ip6_src_ecmp = False):
+def lw46_shared(
+ ip4_pfx_str,
+ ip6_pfx_str,
+ ip6_src_str,
+ ea_bits_len,
+ psid_offset,
+ psid_len,
+ ip6_src_ecmp=False,
+):
ip4_pfx = ip_network(ip4_pfx_str)
ip6_src = ip_address(ip6_src_str)
ip6_dst = ip_network(ip6_pfx_str)
- ip6_nul = IPv6Address(u'0::0')
+ ip6_nul = IPv6Address("0::0")
mod = ip4_pfx.num_addresses / 1024
for i in range(ip4_pfx.num_addresses):
a = time.clock()
- t = map_add_domain(0, ip6_nul.packed, ip4_pfx[i].packed, ip6_src.packed, 0, 32, 128, ea_bits_len, psid_offset, psid_len, 0, 0)
- #print "Return from map_add_domain", t
+ t = map_add_domain(
+ 0,
+ ip6_nul.packed,
+ ip4_pfx[i].packed,
+ ip6_src.packed,
+ 0,
+ 32,
+ 128,
+ ea_bits_len,
+ psid_offset,
+ psid_len,
+ 0,
+ 0,
+ )
+ # print "Return from map_add_domain", t
if t == None:
- print "map_add_domain failed"
+ print("map_add_domain failed")
continue
if t.retval != 0:
- print "map_add_domain failed", t
+ print(f"map_add_domain failed, {t}")
continue
for psid in range(0x1 << int(psid_len)):
- r = map_add_del_rule(0, t.index, 1, (ip6_dst[(i * (0x1<<int(psid_len))) + psid]).packed, psid)
- #print "Return from map_add_del_rule", r
+ r = map_add_del_rule(
+ 0,
+ t.index,
+ 1,
+ (ip6_dst[(i * (0x1 << int(psid_len))) + psid]).packed,
+ psid,
+ )
+ # print "Return from map_add_del_rule", r
if ip6_src_ecmp and not i % mod:
ip6_src = ip6_src + 1
- print "Running time:", time.clock() - a
+ print(f"Running time: {time.clock() - a}")
+
class TestMAP(unittest.TestCase):
- '''
+ """
def test_delete_all(self):
t = map_domain_dump(0)
self.assertNotEqual(t, None)
- print "Number of domains configured: ", len(t)
+ print(f"Number of domains configured: {len(t)}")
for d in t:
ts = map_del_domain(0, d.domainindex)
self.assertNotEqual(ts, None)
t = map_domain_dump(0)
self.assertNotEqual(t, None)
- print "Number of domains configured: ", len(t)
- self.assertEqual(len(t), 0)
+ print(f"Number of domains configured: {len(t)}")
+ self.assertEqual(len(t), 0)/
- '''
+ """
def test_a_million_rules(self):
- ip4_pfx = u'192.0.2.0/24'
- ip6_pfx = u'2001:db8::/32'
- ip6_src = u'2001:db8::1'
+ ip4_pfx = "192.0.2.0/24"
+ ip6_pfx = "2001:db8::/32"
+ ip6_src = "2001:db8::1"
psid_offset = 6
psid_len = 6
ea_bits_len = 0
lw46_shared(ip4_pfx, ip6_pfx, ip6_src, ea_bits_len, psid_offset, psid_len)
+
#
# RX thread, that should sit on blocking vpe_api_read()
-#
+#
#
#
#
import threading
-class RXThread (threading.Thread):
+
+
+class RXThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
- print "Starting "
+ print("Starting ")
i = 0
while True:
msg = vpe_api_read()
if msg:
- #print msg
- id = unpack('>H', msg[0:2])
- size = unpack('>H', msg[2:4])
- print "Received", id, "of size", size
+ # print msg
+ id = unpack(">H", msg[0:2])
+ size = unpack(">H", msg[2:4])
+ print(f"Received {id} of size {size}")
i += 1
- #del msg
+ # del msg
continue
- #time.sleep(0.001)
+ # time.sleep(0.001)
return
+
# Create RX thread
rxthread = RXThread()
rxthread.setDaemon(True)
-
-print "Connect", connect_to_vpe("client124")
+
+print(f"Connect {connect_to_vpe('client124')}")
import timeit
+
rxthread.start()
-print "After thread started"
+print("After thread started")
-#pneum_kill_thread()
-print "After thread killed"
+# pneum_kill_thread()
+print("After thread killed")
-#t = show_version(0)
-#print "Result from show version", t
+# t = show_version(0)
+# print "Result from show version", t
-print timeit.timeit('t = show_version(0)', number=1000, setup="from __main__ import show_version")
+print(
+ f"{timeit.timeit('t = show_version(0)', number=1000, setup='from __main__ import show_version')}"
+)
time.sleep(10)
-#print timeit.timeit('control_ping(0)', number=10, setup="from __main__ import control_ping")
+# print timeit.timeit('control_ping(0)', number=10, setup="from __main__ import control_ping")
disconnect_from_vpe()
sys.exit()
-print t.program, t.version,t.builddate,t.builddirectory
+print(f"{t.program} {t.version}{t.builddate}{t.builddirectory}")
-'''
+"""
t = map_domain_dump(0)
if not t:
@@ -131,11 +166,9 @@ if not t:
for d in t:
print("IP6 prefix:",str(IPv6Address(d.ip6prefix)))
print( "IP4 prefix:",str(IPv4Address(d.ip4prefix)))
-'''
+"""
suite = unittest.TestLoader().loadTestsFromTestCase(TestMAP)
unittest.TextTestRunner(verbosity=2).run(suite)
disconnect_from_vpe()
-
-
diff --git a/src/plugins/map/gen-rules.py b/src/plugins/map/gen-rules.py
index e43b8e155be..7e74f14ad6f 100755
--- a/src/plugins/map/gen-rules.py
+++ b/src/plugins/map/gen-rules.py
@@ -21,87 +21,142 @@ import sys
# map add domain ip4-pfx <pfx> ip6-pfx ::/0 ip6-src <ip6-src> ea-bits-len 0 psid-offset 6 psid-len 6
# map add rule index <0> psid <psid> ip6-dst <ip6-dst>
-parser = argparse.ArgumentParser(description='MAP VPP configuration generator')
-parser.add_argument('-t', action="store", dest="mapmode")
+parser = argparse.ArgumentParser(description="MAP VPP configuration generator")
+parser.add_argument("-t", action="store", dest="mapmode")
args = parser.parse_args()
#
# 1:1 Shared IPv4 address, shared BR
#
def shared11br():
- ip4_pfx = ipaddress.ip_network('20.0.0.0/16')
- ip6_dst = ipaddress.ip_network('bbbb::/32')
+ ip4_pfx = ipaddress.ip_network("20.0.0.0/16")
+ ip6_dst = ipaddress.ip_network("bbbb::/32")
psid_len = 6
for i in range(ip4_pfx.num_addresses):
- print("map add domain ip4-pfx " + str(ip4_pfx[i]) + "/32 ip6-pfx ::/0 ip6-shared-src cccc:bbbb::1",
- "ea-bits-len 0 psid-offset 6 psid-len", psid_len)
+ print(
+ "map add domain ip4-pfx "
+ + str(ip4_pfx[i])
+ + "/32 ip6-pfx ::/0 ip6-shared-src cccc:bbbb::1",
+ "ea-bits-len 0 psid-offset 6 psid-len",
+ psid_len,
+ )
for psid in range(0x1 << psid_len):
- print("map add rule index", i, "psid", psid, "ip6-dst", ip6_dst[(i * (0x1<<psid_len)) + psid])
+ print(
+ "map add rule index",
+ i,
+ "psid",
+ psid,
+ "ip6-dst",
+ ip6_dst[(i * (0x1 << psid_len)) + psid],
+ )
#
# 1:1 Shared IPv4 address
#
def shared11():
- ip4_pfx = ipaddress.ip_network('20.0.0.0/16')
- ip6_src = ipaddress.ip_network('cccc:bbbb::/64')
- ip6_dst = ipaddress.ip_network('bbbb::/32')
+ ip4_pfx = ipaddress.ip_network("20.0.0.0/16")
+ ip6_src = ipaddress.ip_network("cccc:bbbb::/64")
+ ip6_dst = ipaddress.ip_network("bbbb::/32")
psid_len = 6
for i in range(ip4_pfx.num_addresses):
- print("map add domain ip4-pfx " + str(ip4_pfx[i]) + "/32 ip6-pfx ::/0 ip6-src", ip6_src[i],
- "ea-bits-len 0 psid-offset 6 psid-len", psid_len)
+ print(
+ "map add domain ip4-pfx " + str(ip4_pfx[i]) + "/32 ip6-pfx ::/0 ip6-src",
+ ip6_src[i],
+ "ea-bits-len 0 psid-offset 6 psid-len",
+ psid_len,
+ )
for psid in range(0x1 << psid_len):
- print("map add rule index", i, "psid", psid, "ip6-dst", ip6_dst[(i * (0x1<<psid_len)) + psid])
+ print(
+ "map add rule index",
+ i,
+ "psid",
+ psid,
+ "ip6-dst",
+ ip6_dst[(i * (0x1 << psid_len)) + psid],
+ )
+
#
# 1:1 Shared IPv4 address small
#
def smallshared11():
- ip4_pfx = ipaddress.ip_network('20.0.0.0/24')
- ip6_src = ipaddress.ip_network('cccc:bbbb::/64')
- ip6_dst = ipaddress.ip_network('bbbb::/32')
+ ip4_pfx = ipaddress.ip_network("20.0.0.0/24")
+ ip6_src = ipaddress.ip_network("cccc:bbbb::/64")
+ ip6_dst = ipaddress.ip_network("bbbb::/32")
psid_len = 6
for i in range(ip4_pfx.num_addresses):
- print("map add domain ip4-pfx " + str(ip4_pfx[i]) + "/32 ip6-pfx ::/0 ip6-src", ip6_src[i],
- "ea-bits-len 0 psid-offset 6 psid-len", psid_len)
+ print(
+ "map add domain ip4-pfx " + str(ip4_pfx[i]) + "/32 ip6-pfx ::/0 ip6-src",
+ ip6_src[i],
+ "ea-bits-len 0 psid-offset 6 psid-len",
+ psid_len,
+ )
for psid in range(0x1 << psid_len):
- print("map add rule index", i, "psid", psid, "ip6-dst", ip6_dst[(i * (0x1<<psid_len)) + psid])
+ print(
+ "map add rule index",
+ i,
+ "psid",
+ psid,
+ "ip6-dst",
+ ip6_dst[(i * (0x1 << psid_len)) + psid],
+ )
+
#
# 1:1 Full IPv4 address
#
def full11():
- ip4_pfx = ipaddress.ip_network('20.0.0.0/16')
- ip6_src = ipaddress.ip_network('cccc:bbbb::/64')
- ip6_dst = ipaddress.ip_network('bbbb::/32')
+ ip4_pfx = ipaddress.ip_network("20.0.0.0/16")
+ ip6_src = ipaddress.ip_network("cccc:bbbb::/64")
+ ip6_dst = ipaddress.ip_network("bbbb::/32")
psid_len = 0
for i in range(ip4_pfx.num_addresses):
- print("map add domain ip4-pfx " + str(ip4_pfx[i]) + "/32 ip6-pfx " + str(ip6_dst[i]) + "/128 ip6-src", ip6_src[i],
- "ea-bits-len 0 psid-offset 0 psid-len 0")
+ print(
+ "map add domain ip4-pfx "
+ + str(ip4_pfx[i])
+ + "/32 ip6-pfx "
+ + str(ip6_dst[i])
+ + "/128 ip6-src",
+ ip6_src[i],
+ "ea-bits-len 0 psid-offset 0 psid-len 0",
+ )
+
+
def full11br():
- ip4_pfx = ipaddress.ip_network('20.0.0.0/16')
- ip6_dst = ipaddress.ip_network('bbbb::/32')
+ ip4_pfx = ipaddress.ip_network("20.0.0.0/16")
+ ip6_dst = ipaddress.ip_network("bbbb::/32")
psid_len = 0
for i in range(ip4_pfx.num_addresses):
- print("map add domain ip4-pfx " + str(ip4_pfx[i]) + "/32 ip6-pfx " + str(ip6_dst[i]) + "/128 ip6-shared-src cccc:bbbb::1",
- "ea-bits-len 0 psid-offset 0 psid-len 0")
+ print(
+ "map add domain ip4-pfx "
+ + str(ip4_pfx[i])
+ + "/32 ip6-pfx "
+ + str(ip6_dst[i])
+ + "/128 ip6-shared-src cccc:bbbb::1",
+ "ea-bits-len 0 psid-offset 0 psid-len 0",
+ )
+
#
# Algorithmic mapping Shared IPv4 address
#
def algo():
- print("map add domain ip4-pfx 20.0.0.0/24 ip6-pfx bbbb::/32 ip6-src cccc:bbbb::1 ea-bits-len 16 psid-offset 6 psid-len 8")
- print("map add domain ip4-pfx 20.0.1.0/24 ip6-pfx bbbb:1::/32 ip6-src cccc:bbbb::2 ea-bits-len 8 psid-offset 0 psid-len 0")
+ print(
+ "map add domain ip4-pfx 20.0.0.0/24 ip6-pfx bbbb::/32 ip6-src cccc:bbbb::1 ea-bits-len 16 psid-offset 6 psid-len 8"
+ )
+ print(
+ "map add domain ip4-pfx 20.0.1.0/24 ip6-pfx bbbb:1::/32 ip6-src cccc:bbbb::2 ea-bits-len 8 psid-offset 0 psid-len 0"
+ )
+
#
# IP4 forwarding
#
def ip4():
- ip4_pfx = ipaddress.ip_network('20.0.0.0/16')
+ ip4_pfx = ipaddress.ip_network("20.0.0.0/16")
for i in range(ip4_pfx.num_addresses):
- print("ip route add " + str(ip4_pfx[i]) + "/32 via 172.16.0.2")
+ print("ip route add " + str(ip4_pfx[i]) + "/32 via 172.16.0.2")
globals()[args.mapmode]()
-
-
diff --git a/src/plugins/nat/extras/nat_100ks.py b/src/plugins/nat/extras/nat_100ks.py
index c85a4591cd3..4e8dc2486d6 100644
--- a/src/plugins/nat/extras/nat_100ks.py
+++ b/src/plugins/nat/extras/nat_100ks.py
@@ -1,35 +1,39 @@
from trex_stl_lib.api import *
-class STLS1:
- def create_stream (self):
- base_pkt = Ether()/IP(dst="2.2.0.1")/UDP(dport=12)
+class STLS1:
+ def create_stream(self):
+ base_pkt = Ether() / IP(dst="2.2.0.1") / UDP(dport=12)
pad = Padding()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
- pad.load = '\x00' * pad_len
+ pad.load = "\x00" * pad_len
vm = STLVM()
- vm.tuple_var(name="tuple", ip_min="10.0.0.3", ip_max="10.0.3.234", port_min=1025, port_max=1124, limit_flows = 100000)
+ vm.tuple_var(
+ name="tuple",
+ ip_min="10.0.0.3",
+ ip_max="10.0.3.234",
+ port_min=1025,
+ port_max=1124,
+ limit_flows=100000,
+ )
vm.write(fv_name="tuple.ip", pkt_offset="IP.src")
vm.fix_chksum()
vm.write(fv_name="tuple.port", pkt_offset="UDP.sport")
- pkt = STLPktBuilder(pkt=base_pkt/pad, vm=vm)
+ pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)
return STLStream(packet=pkt, mode=STLTXCont())
- def get_streams (self, direction = 0, **kwargs):
+ def get_streams(self, direction=0, **kwargs):
return [self.create_stream()]
# dynamic load - used for trex console or simulator
def register():
return STLS1()
-
-
-
diff --git a/src/plugins/nat/extras/nat_10Ms.py b/src/plugins/nat/extras/nat_10Ms.py
index 6ce62a0b5e7..96a18ec018a 100644
--- a/src/plugins/nat/extras/nat_10Ms.py
+++ b/src/plugins/nat/extras/nat_10Ms.py
@@ -1,35 +1,39 @@
from trex_stl_lib.api import *
-class STLS1:
- def create_stream (self):
- base_pkt = Ether()/IP(dst="2.2.0.1")/UDP(dport=12)
+class STLS1:
+ def create_stream(self):
+ base_pkt = Ether() / IP(dst="2.2.0.1") / UDP(dport=12)
pad = Padding()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
- pad.load = '\x00' * pad_len
+ pad.load = "\x00" * pad_len
vm = STLVM()
- vm.tuple_var(name="tuple", ip_min="10.0.0.3", ip_max="10.1.134.162", port_min=1025, port_max=1124, limit_flows=10000000)
+ vm.tuple_var(
+ name="tuple",
+ ip_min="10.0.0.3",
+ ip_max="10.1.134.162",
+ port_min=1025,
+ port_max=1124,
+ limit_flows=10000000,
+ )
vm.write(fv_name="tuple.ip", pkt_offset="IP.src")
vm.fix_chksum()
vm.write(fv_name="tuple.port", pkt_offset="UDP.sport")
- pkt = STLPktBuilder(pkt=base_pkt/pad, vm=vm)
+ pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)
return STLStream(packet=pkt, mode=STLTXCont())
- def get_streams (self, direction = 0, **kwargs):
+ def get_streams(self, direction=0, **kwargs):
return [self.create_stream()]
# dynamic load - used for trex console or simulator
def register():
return STLS1()
-
-
-
diff --git a/src/plugins/nat/extras/nat_10ks.py b/src/plugins/nat/extras/nat_10ks.py
index 33c7196eb9e..c210d5e81d8 100644
--- a/src/plugins/nat/extras/nat_10ks.py
+++ b/src/plugins/nat/extras/nat_10ks.py
@@ -1,35 +1,39 @@
from trex_stl_lib.api import *
-class STLS1:
- def create_stream (self):
- base_pkt = Ether()/IP(dst="2.2.0.1")/UDP(dport=12)
+class STLS1:
+ def create_stream(self):
+ base_pkt = Ether() / IP(dst="2.2.0.1") / UDP(dport=12)
pad = Padding()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
- pad.load = '\x00' * pad_len
+ pad.load = "\x00" * pad_len
vm = STLVM()
- vm.tuple_var(name="tuple", ip_min="10.0.0.3", ip_max="10.0.0.102", port_min=1025, port_max=1124, limit_flows = 10000)
+ vm.tuple_var(
+ name="tuple",
+ ip_min="10.0.0.3",
+ ip_max="10.0.0.102",
+ port_min=1025,
+ port_max=1124,
+ limit_flows=10000,
+ )
vm.write(fv_name="tuple.ip", pkt_offset="IP.src")
vm.fix_chksum()
vm.write(fv_name="tuple.port", pkt_offset="UDP.sport")
- pkt = STLPktBuilder(pkt=base_pkt/pad, vm=vm)
+ pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)
return STLStream(packet=pkt, mode=STLTXCont())
- def get_streams (self, direction = 0, **kwargs):
+ def get_streams(self, direction=0, **kwargs):
return [self.create_stream()]
# dynamic load - used for trex console or simulator
def register():
return STLS1()
-
-
-
diff --git a/src/plugins/nat/extras/nat_1Ms.py b/src/plugins/nat/extras/nat_1Ms.py
index 73a91a70985..7271cf73781 100644
--- a/src/plugins/nat/extras/nat_1Ms.py
+++ b/src/plugins/nat/extras/nat_1Ms.py
@@ -1,35 +1,39 @@
from trex_stl_lib.api import *
-class STLS1:
- def create_stream (self):
- base_pkt = Ether()/IP(dst="2.2.0.1")/UDP(dport=12)
+class STLS1:
+ def create_stream(self):
+ base_pkt = Ether() / IP(dst="2.2.0.1") / UDP(dport=12)
pad = Padding()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
- pad.load = '\x00' * pad_len
+ pad.load = "\x00" * pad_len
vm = STLVM()
- vm.tuple_var(name="tuple", ip_min="10.0.0.3", ip_max="10.0.39.18", port_min=1025, port_max=1124, limit_flows = 1000000)
+ vm.tuple_var(
+ name="tuple",
+ ip_min="10.0.0.3",
+ ip_max="10.0.39.18",
+ port_min=1025,
+ port_max=1124,
+ limit_flows=1000000,
+ )
vm.write(fv_name="tuple.ip", pkt_offset="IP.src")
vm.fix_chksum()
vm.write(fv_name="tuple.port", pkt_offset="UDP.sport")
- pkt = STLPktBuilder(pkt=base_pkt/pad, vm=vm)
+ pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)
return STLStream(packet=pkt, mode=STLTXCont())
- def get_streams (self, direction = 0, **kwargs):
+ def get_streams(self, direction=0, **kwargs):
return [self.create_stream()]
# dynamic load - used for trex console or simulator
def register():
return STLS1()
-
-
-
diff --git a/src/plugins/nat/extras/nat_out2in_100ks.py b/src/plugins/nat/extras/nat_out2in_100ks.py
index 55ab5d42ee1..911f2cefda4 100644
--- a/src/plugins/nat/extras/nat_out2in_100ks.py
+++ b/src/plugins/nat/extras/nat_out2in_100ks.py
@@ -1,35 +1,39 @@
from trex_stl_lib.api import *
-class STLS1:
- def create_stream (self):
- base_pkt = Ether()/IP(src="2.2.0.1")/UDP(sport=12)
+class STLS1:
+ def create_stream(self):
+ base_pkt = Ether() / IP(src="2.2.0.1") / UDP(sport=12)
pad = Padding()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
- pad.load = '\x00' * pad_len
+ pad.load = "\x00" * pad_len
vm = STLVM()
- vm.tuple_var(name="tuple", ip_min="173.16.1.3", ip_max="173.16.4.234", port_min=1025, port_max=1124, limit_flows = 100000)
+ vm.tuple_var(
+ name="tuple",
+ ip_min="173.16.1.3",
+ ip_max="173.16.4.234",
+ port_min=1025,
+ port_max=1124,
+ limit_flows=100000,
+ )
vm.write(fv_name="tuple.ip", pkt_offset="IP.dst")
vm.fix_chksum()
vm.write(fv_name="tuple.port", pkt_offset="UDP.dport")
- pkt = STLPktBuilder(pkt=base_pkt/pad, vm=vm)
+ pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)
return STLStream(packet=pkt, mode=STLTXCont())
- def get_streams (self, direction = 0, **kwargs):
+ def get_streams(self, direction=0, **kwargs):
return [self.create_stream()]
# dynamic load - used for trex console or simulator
def register():
return STLS1()
-
-
-
diff --git a/src/plugins/nat/extras/nat_out2in_10Ms.py b/src/plugins/nat/extras/nat_out2in_10Ms.py
index 48d3d199080..b3493641ea0 100644
--- a/src/plugins/nat/extras/nat_out2in_10Ms.py
+++ b/src/plugins/nat/extras/nat_out2in_10Ms.py
@@ -1,35 +1,39 @@
from trex_stl_lib.api import *
-class STLS1:
- def create_stream (self):
- base_pkt = Ether()/IP(src="2.2.0.1")/UDP(sport=12)
+class STLS1:
+ def create_stream(self):
+ base_pkt = Ether() / IP(src="2.2.0.1") / UDP(sport=12)
pad = Padding()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
- pad.load = '\x00' * pad_len
+ pad.load = "\x00" * pad_len
vm = STLVM()
- vm.tuple_var(name="tuple", ip_min="173.16.1.3", ip_max="173.17.135.162", port_min=1025, port_max=1124, limit_flows = 10000000)
+ vm.tuple_var(
+ name="tuple",
+ ip_min="173.16.1.3",
+ ip_max="173.17.135.162",
+ port_min=1025,
+ port_max=1124,
+ limit_flows=10000000,
+ )
vm.write(fv_name="tuple.ip", pkt_offset="IP.dst")
vm.fix_chksum()
vm.write(fv_name="tuple.port", pkt_offset="UDP.dport")
- pkt = STLPktBuilder(pkt=base_pkt/pad, vm=vm)
+ pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)
return STLStream(packet=pkt, mode=STLTXCont())
- def get_streams (self, direction = 0, **kwargs):
+ def get_streams(self, direction=0, **kwargs):
return [self.create_stream()]
# dynamic load - used for trex console or simulator
def register():
return STLS1()
-
-
-
diff --git a/src/plugins/nat/extras/nat_out2in_10ks.py b/src/plugins/nat/extras/nat_out2in_10ks.py
index e961504fcf9..abd82ce320d 100644
--- a/src/plugins/nat/extras/nat_out2in_10ks.py
+++ b/src/plugins/nat/extras/nat_out2in_10ks.py
@@ -1,35 +1,39 @@
from trex_stl_lib.api import *
-class STLS1:
- def create_stream (self):
- base_pkt = Ether()/IP(src="2.2.0.1")/UDP(sport=12)
+class STLS1:
+ def create_stream(self):
+ base_pkt = Ether() / IP(src="2.2.0.1") / UDP(sport=12)
pad = Padding()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
- pad.load = '\x00' * pad_len
+ pad.load = "\x00" * pad_len
vm = STLVM()
- vm.tuple_var(name="tuple", ip_min="173.16.1.3", ip_max="173.16.1.102", port_min=1025, port_max=1124, limit_flows = 100000)
+ vm.tuple_var(
+ name="tuple",
+ ip_min="173.16.1.3",
+ ip_max="173.16.1.102",
+ port_min=1025,
+ port_max=1124,
+ limit_flows=100000,
+ )
vm.write(fv_name="tuple.ip", pkt_offset="IP.dst")
vm.fix_chksum()
vm.write(fv_name="tuple.port", pkt_offset="UDP.dport")
- pkt = STLPktBuilder(pkt=base_pkt/pad, vm=vm)
+ pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)
return STLStream(packet=pkt, mode=STLTXCont())
- def get_streams (self, direction = 0, **kwargs):
+ def get_streams(self, direction=0, **kwargs):
return [self.create_stream()]
# dynamic load - used for trex console or simulator
def register():
return STLS1()
-
-
-
diff --git a/src/plugins/nat/extras/nat_out2in_1Ms.py b/src/plugins/nat/extras/nat_out2in_1Ms.py
index d2cb0810263..c08ef191e6c 100644
--- a/src/plugins/nat/extras/nat_out2in_1Ms.py
+++ b/src/plugins/nat/extras/nat_out2in_1Ms.py
@@ -1,35 +1,39 @@
from trex_stl_lib.api import *
-class STLS1:
- def create_stream (self):
- base_pkt = Ether()/IP(src="2.2.0.1")/UDP(sport=12)
+class STLS1:
+ def create_stream(self):
+ base_pkt = Ether() / IP(src="2.2.0.1") / UDP(sport=12)
pad = Padding()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
- pad.load = '\x00' * pad_len
+ pad.load = "\x00" * pad_len
vm = STLVM()
- vm.tuple_var(name="tuple", ip_min="173.16.1.3", ip_max="173.16.40.18", port_min=1025, port_max=1124, limit_flows = 1000000)
+ vm.tuple_var(
+ name="tuple",
+ ip_min="173.16.1.3",
+ ip_max="173.16.40.18",
+ port_min=1025,
+ port_max=1124,
+ limit_flows=1000000,
+ )
vm.write(fv_name="tuple.ip", pkt_offset="IP.dst")
vm.fix_chksum()
vm.write(fv_name="tuple.port", pkt_offset="UDP.dport")
- pkt = STLPktBuilder(pkt=base_pkt/pad, vm=vm)
+ pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)
return STLStream(packet=pkt, mode=STLTXCont())
- def get_streams (self, direction = 0, **kwargs):
+ def get_streams(self, direction=0, **kwargs):
return [self.create_stream()]
# dynamic load - used for trex console or simulator
def register():
return STLS1()
-
-
-
diff --git a/src/plugins/nat/extras/nat_ses_open.py b/src/plugins/nat/extras/nat_ses_open.py
index d614d4e7356..a267a6b67fb 100644
--- a/src/plugins/nat/extras/nat_ses_open.py
+++ b/src/plugins/nat/extras/nat_ses_open.py
@@ -1,44 +1,72 @@
from trex_stl_lib.api import *
-class STLS1:
- def __init__ (self):
- self.ip_range = {'local': {'start': "10.0.0.3", 'end': "10.1.255.255"},
- 'external': {'start': "172.16.1.3", 'end': "172.16.1.3"},
- 'remote': {'start': "2.2.0.1", 'end': "2.2.0.1"}}
- self.port_range = {'local': {'start': 1025, 'end': 65535},
- 'remote': {'start': 12, 'end': 12}}
+class STLS1:
+ def __init__(self):
+ self.ip_range = {
+ "local": {"start": "10.0.0.3", "end": "10.1.255.255"},
+ "external": {"start": "172.16.1.3", "end": "172.16.1.3"},
+ "remote": {"start": "2.2.0.1", "end": "2.2.0.1"},
+ }
+ self.port_range = {
+ "local": {"start": 1025, "end": 65535},
+ "remote": {"start": 12, "end": 12},
+ }
- def create_stream (self, vm):
- base_pkt = Ether()/IP()/UDP()
+ def create_stream(self, vm):
+ base_pkt = Ether() / IP() / UDP()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
pad = Padding()
- pad.load = '\x00' * pad_len
- base_pkt = base_pkt/pad
-
+ pad.load = "\x00" * pad_len
+ base_pkt = base_pkt / pad
+
pkt = STLPktBuilder(pkt=base_pkt, vm=vm)
return STLStream(packet=pkt, mode=STLTXCont())
- def get_streams (self, direction = 0, **kwargs):
+ def get_streams(self, direction=0, **kwargs):
if direction == 0:
- ip_src = self.ip_range['remote']
- ip_dst = self.ip_range['external']
- src_port = self.port_range['remote']
- dst_port = self.port_range['local']
+ ip_src = self.ip_range["remote"]
+ ip_dst = self.ip_range["external"]
+ src_port = self.port_range["remote"]
+ dst_port = self.port_range["local"]
else:
- ip_src = self.ip_range['local']
- ip_dst = self.ip_range['remote']
- src_port = self.port_range['local']
- dst_port = self.port_range['remote']
+ ip_src = self.ip_range["local"]
+ ip_dst = self.ip_range["remote"]
+ src_port = self.port_range["local"]
+ dst_port = self.port_range["remote"]
vm = STLVM()
- vm.var(name="ip_src", min_value=ip_src['start'], max_value=ip_src['end'], size=4, op="random")
- vm.var(name="ip_dst", min_value=ip_dst['start'], max_value=ip_dst['end'], size=4, op="random")
- vm.var(name="src_port", min_value=src_port['start'], max_value=src_port['end'], size=2, op="random")
- vm.var(name="dst_port", min_value=dst_port['start'], max_value=dst_port['end'], size=2, op="random")
+ vm.var(
+ name="ip_src",
+ min_value=ip_src["start"],
+ max_value=ip_src["end"],
+ size=4,
+ op="random",
+ )
+ vm.var(
+ name="ip_dst",
+ min_value=ip_dst["start"],
+ max_value=ip_dst["end"],
+ size=4,
+ op="random",
+ )
+ vm.var(
+ name="src_port",
+ min_value=src_port["start"],
+ max_value=src_port["end"],
+ size=2,
+ op="random",
+ )
+ vm.var(
+ name="dst_port",
+ min_value=dst_port["start"],
+ max_value=dst_port["end"],
+ size=2,
+ op="random",
+ )
vm.write(fv_name="ip_src", pkt_offset="IP.src")
vm.write(fv_name="ip_dst", pkt_offset="IP.dst")
@@ -47,12 +75,9 @@ class STLS1:
vm.fix_chksum()
- return [ self.create_stream(vm) ]
+ return [self.create_stream(vm)]
# dynamic load - used for trex console or simulator
def register():
return STLS1()
-
-
-
diff --git a/src/plugins/nat/extras/nat_static_gen_cfg.py b/src/plugins/nat/extras/nat_static_gen_cfg.py
index 9e59bbfc0c2..009cf099582 100755
--- a/src/plugins/nat/extras/nat_static_gen_cfg.py
+++ b/src/plugins/nat/extras/nat_static_gen_cfg.py
@@ -2,24 +2,24 @@
import ipaddress
import argparse
-parser = argparse.ArgumentParser(description='Generate NAT plugin config.')
-parser.add_argument('static_map_num', metavar='N', type=int, nargs=1,
- help='number of static mappings')
+parser = argparse.ArgumentParser(description="Generate NAT plugin config.")
+parser.add_argument(
+ "static_map_num", metavar="N", type=int, nargs=1, help="number of static mappings"
+)
args = parser.parse_args()
-file_name = 'nat_static_%s' % (args.static_map_num[0])
-outfile = open(file_name, 'w')
+file_name = "nat_static_%s" % (args.static_map_num[0])
+outfile = open(file_name, "w")
-outfile.write('set int ip address TenGigabitEthernet4/0/0 172.16.2.1/24\n')
-outfile.write('set int ip address TenGigabitEthernet4/0/1 173.16.1.1/24\n')
-outfile.write('set int state TenGigabitEthernet4/0/0 up\n')
-outfile.write('set int state TenGigabitEthernet4/0/1 up\n')
-outfile.write('ip route add 2.2.0.0/16 via 173.16.1.2 TenGigabitEthernet4/0/1\n')
-outfile.write('ip route add 10.0.0.0/24 via 172.16.2.2 TenGigabitEthernet4/0/0\n')
-outfile.write('set int nat44 in TenGigabitEthernet4/0/0 out TenGigabitEthernet4/0/1\n')
-
-for i in range (0, args.static_map_num[0]):
- local = str(ipaddress.IPv4Address(u'10.0.0.3') + i)
- external = str(ipaddress.IPv4Address(u'173.16.1.3') + i)
- outfile.write('nat44 add static mapping local %s external %s\n' % (local, external))
+outfile.write("set int ip address TenGigabitEthernet4/0/0 172.16.2.1/24\n")
+outfile.write("set int ip address TenGigabitEthernet4/0/1 173.16.1.1/24\n")
+outfile.write("set int state TenGigabitEthernet4/0/0 up\n")
+outfile.write("set int state TenGigabitEthernet4/0/1 up\n")
+outfile.write("ip route add 2.2.0.0/16 via 173.16.1.2 TenGigabitEthernet4/0/1\n")
+outfile.write("ip route add 10.0.0.0/24 via 172.16.2.2 TenGigabitEthernet4/0/0\n")
+outfile.write("set int nat44 in TenGigabitEthernet4/0/0 out TenGigabitEthernet4/0/1\n")
+for i in range(0, args.static_map_num[0]):
+ local = str(ipaddress.IPv4Address("10.0.0.3") + i)
+ external = str(ipaddress.IPv4Address("173.16.1.3") + i)
+ outfile.write("nat44 add static mapping local %s external %s\n" % (local, external))
diff --git a/src/plugins/nat/extras/nat_test_fast_path.py b/src/plugins/nat/extras/nat_test_fast_path.py
index e869d40872a..fb880fb9e96 100644
--- a/src/plugins/nat/extras/nat_test_fast_path.py
+++ b/src/plugins/nat/extras/nat_test_fast_path.py
@@ -2,7 +2,6 @@ from trex_stl_lib.api import *
class STLS1:
-
def create_stream(self):
# base_pkt = Ether()/IP(dst="2.2.0.1")/UDP(dport=12)
@@ -24,37 +23,46 @@ class STLS1:
# return STLStream(packet=pkt, mode=STLTXCont())
- vm = STLScVmRaw([STLVmTupleGen(ip_min="10.0.0.1", ip_max="10.255.255.254",
- port_min=1025, port_max=65535,
- # name="stuple", limit_flows=10000),
- name="stuple", limit_flows=100),
- STLVmTupleGen(ip_min="2.0.0.1", ip_max="2.255.255.254",
- port_min=1025, port_max=65535,
- # name="dtuple", limit_flows=100000000),
- name="dtuple", limit_flows=100),
-
- # write ip to packet IP.src
- STLVmWrFlowVar(fv_name="stuple.ip",
- pkt_offset="IP.src"),
- STLVmWrFlowVar(fv_name="dtuple.ip",
- pkt_offset="IP.dst"),
- # fix checksum
- STLVmFixIpv4(offset="IP"),
- # write udp.port
- STLVmWrFlowVar(fv_name="stuple.port",
- pkt_offset="UDP.sport"),
- STLVmWrFlowVar(fv_name="dtuple.port",
- pkt_offset="UDP.dport"),
- ]
- )
-
- base_pkt = Ether()/IP(src="16.0.0.1", dst="2.0.0.1")/UDP(dport=12, sport=1025)
+ vm = STLScVmRaw(
+ [
+ STLVmTupleGen(
+ ip_min="10.0.0.1",
+ ip_max="10.255.255.254",
+ port_min=1025,
+ port_max=65535,
+ # name="stuple", limit_flows=10000),
+ name="stuple",
+ limit_flows=100,
+ ),
+ STLVmTupleGen(
+ ip_min="2.0.0.1",
+ ip_max="2.255.255.254",
+ port_min=1025,
+ port_max=65535,
+ # name="dtuple", limit_flows=100000000),
+ name="dtuple",
+ limit_flows=100,
+ ),
+ # write ip to packet IP.src
+ STLVmWrFlowVar(fv_name="stuple.ip", pkt_offset="IP.src"),
+ STLVmWrFlowVar(fv_name="dtuple.ip", pkt_offset="IP.dst"),
+ # fix checksum
+ STLVmFixIpv4(offset="IP"),
+ # write udp.port
+ STLVmWrFlowVar(fv_name="stuple.port", pkt_offset="UDP.sport"),
+ STLVmWrFlowVar(fv_name="dtuple.port", pkt_offset="UDP.dport"),
+ ]
+ )
+
+ base_pkt = (
+ Ether() / IP(src="16.0.0.1", dst="2.0.0.1") / UDP(dport=12, sport=1025)
+ )
pad = Padding()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
- pad.load = '\x00' * pad_len
+ pad.load = "\x00" * pad_len
- pkt = STLPktBuilder(pkt=base_pkt/pad, vm=vm)
+ pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)
return STLStream(packet=pkt, mode=STLTXCont())
diff --git a/src/plugins/nat/extras/nat_test_slow_path.py b/src/plugins/nat/extras/nat_test_slow_path.py
index a6351b98adf..3145a2c6a59 100644
--- a/src/plugins/nat/extras/nat_test_slow_path.py
+++ b/src/plugins/nat/extras/nat_test_slow_path.py
@@ -2,7 +2,6 @@ from trex_stl_lib.api import *
class STLS1:
-
def create_stream(self):
# base_pkt = Ether()/IP(dst="2.2.0.1")/UDP(dport=12)
@@ -24,35 +23,44 @@ class STLS1:
# return STLStream(packet=pkt, mode=STLTXCont())
- vm = STLScVmRaw([STLVmTupleGen(ip_min="10.0.0.1", ip_max="10.255.255.254",
- port_min=1025, port_max=65535,
- name="stuple", limit_flows=10000),
- STLVmTupleGen(ip_min="2.0.0.1", ip_max="2.255.255.254",
- port_min=1025, port_max=65535,
- name="dtuple", limit_flows=100000000),
-
- # write ip to packet IP.src
- STLVmWrFlowVar(fv_name="stuple.ip",
- pkt_offset="IP.src"),
- STLVmWrFlowVar(fv_name="dtuple.ip",
- pkt_offset="IP.dst"),
- # fix checksum
- STLVmFixIpv4(offset="IP"),
- # write udp.port
- STLVmWrFlowVar(fv_name="stuple.port",
- pkt_offset="UDP.sport"),
- STLVmWrFlowVar(fv_name="dtuple.port",
- pkt_offset="UDP.dport"),
- ]
- )
-
- base_pkt = Ether()/IP(src="16.0.0.1", dst="2.0.0.1")/UDP(dport=12, sport=1025)
+ vm = STLScVmRaw(
+ [
+ STLVmTupleGen(
+ ip_min="10.0.0.1",
+ ip_max="10.255.255.254",
+ port_min=1025,
+ port_max=65535,
+ name="stuple",
+ limit_flows=10000,
+ ),
+ STLVmTupleGen(
+ ip_min="2.0.0.1",
+ ip_max="2.255.255.254",
+ port_min=1025,
+ port_max=65535,
+ name="dtuple",
+ limit_flows=100000000,
+ ),
+ # write ip to packet IP.src
+ STLVmWrFlowVar(fv_name="stuple.ip", pkt_offset="IP.src"),
+ STLVmWrFlowVar(fv_name="dtuple.ip", pkt_offset="IP.dst"),
+ # fix checksum
+ STLVmFixIpv4(offset="IP"),
+ # write udp.port
+ STLVmWrFlowVar(fv_name="stuple.port", pkt_offset="UDP.sport"),
+ STLVmWrFlowVar(fv_name="dtuple.port", pkt_offset="UDP.dport"),
+ ]
+ )
+
+ base_pkt = (
+ Ether() / IP(src="16.0.0.1", dst="2.0.0.1") / UDP(dport=12, sport=1025)
+ )
pad = Padding()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
- pad.load = '\x00' * pad_len
+ pad.load = "\x00" * pad_len
- pkt = STLPktBuilder(pkt=base_pkt/pad, vm=vm)
+ pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)
return STLStream(packet=pkt, mode=STLTXCont())
diff --git a/src/plugins/nat/extras/nat_test_slow_path_with_latency.py b/src/plugins/nat/extras/nat_test_slow_path_with_latency.py
index 6c7663434c5..0c08e7a5e80 100644
--- a/src/plugins/nat/extras/nat_test_slow_path_with_latency.py
+++ b/src/plugins/nat/extras/nat_test_slow_path_with_latency.py
@@ -2,7 +2,6 @@ from trex_stl_lib.api import *
class STLS1:
-
def create_stream(self, port_id):
# base_pkt = Ether()/IP(dst="2.2.0.1")/UDP(dport=12)
@@ -24,49 +23,61 @@ class STLS1:
# return STLStream(packet=pkt, mode=STLTXCont())
- vm = STLScVmRaw([STLVmTupleGen(ip_min="10.0.0.1", ip_max="10.255.255.254",
- port_min=1025, port_max=65535,
- name="stuple", limit_flows=10000),
- STLVmTupleGen(ip_min="2.0.0.1", ip_max="2.255.255.254",
- port_min=1025, port_max=65535,
- name="dtuple", limit_flows=100000000),
-
- # write ip to packet IP.src
- STLVmWrFlowVar(fv_name="stuple.ip",
- pkt_offset="IP.src"),
- STLVmWrFlowVar(fv_name="dtuple.ip",
- pkt_offset="IP.dst"),
- # fix checksum
- STLVmFixIpv4(offset="IP"),
- # write udp.port
- STLVmWrFlowVar(fv_name="stuple.port",
- pkt_offset="UDP.sport"),
- STLVmWrFlowVar(fv_name="dtuple.port",
- pkt_offset="UDP.dport"),
- ]
- )
-
- base_pkt = Ether()/IP(src="16.0.0.1", dst="2.0.0.1")/UDP(dport=12, sport=1025)
+ vm = STLScVmRaw(
+ [
+ STLVmTupleGen(
+ ip_min="10.0.0.1",
+ ip_max="10.255.255.254",
+ port_min=1025,
+ port_max=65535,
+ name="stuple",
+ limit_flows=10000,
+ ),
+ STLVmTupleGen(
+ ip_min="2.0.0.1",
+ ip_max="2.255.255.254",
+ port_min=1025,
+ port_max=65535,
+ name="dtuple",
+ limit_flows=100000000,
+ ),
+ # write ip to packet IP.src
+ STLVmWrFlowVar(fv_name="stuple.ip", pkt_offset="IP.src"),
+ STLVmWrFlowVar(fv_name="dtuple.ip", pkt_offset="IP.dst"),
+ # fix checksum
+ STLVmFixIpv4(offset="IP"),
+ # write udp.port
+ STLVmWrFlowVar(fv_name="stuple.port", pkt_offset="UDP.sport"),
+ STLVmWrFlowVar(fv_name="dtuple.port", pkt_offset="UDP.dport"),
+ ]
+ )
+
+ base_pkt = (
+ Ether() / IP(src="16.0.0.1", dst="2.0.0.1") / UDP(dport=12, sport=1025)
+ )
pad = Padding()
if len(base_pkt) < 64:
pad_len = 64 - len(base_pkt)
- pad.load = '\x00' * pad_len
+ pad.load = "\x00" * pad_len
- pad = max(0, 64 - len(base_pkt)) * 'x'
- pad_latency = max(0, (64-4) - len(base_pkt)) * 'x'
+ pad = max(0, 64 - len(base_pkt)) * "x"
+ pad_latency = max(0, (64 - 4) - len(base_pkt)) * "x"
- pkt = STLPktBuilder(pkt=base_pkt/pad, vm=vm)
+ pkt = STLPktBuilder(pkt=base_pkt / pad, vm=vm)
- return [STLStream(packet=pkt, mode=STLTXCont()),
- # latency stream
- STLStream(packet = STLPktBuilder(pkt = base_pkt/pad_latency),
- mode = STLTXCont(pps=1000),
- flow_stats = STLFlowLatencyStats(pg_id = 12+port_id))
- ]
+ return [
+ STLStream(packet=pkt, mode=STLTXCont()),
+ # latency stream
+ STLStream(
+ packet=STLPktBuilder(pkt=base_pkt / pad_latency),
+ mode=STLTXCont(pps=1000),
+ flow_stats=STLFlowLatencyStats(pg_id=12 + port_id),
+ ),
+ ]
def get_streams(self, direction=0, **kwargs):
# return [self.create_stream()]
- return self.create_stream(kwargs['port_id'])
+ return self.create_stream(kwargs["port_id"])
# dynamic load - used for trex console or simulator
diff --git a/src/plugins/nat/pnat/tests/test_genpackets.py b/src/plugins/nat/pnat/tests/test_genpackets.py
index 9d32d3e3656..40867317078 100755
--- a/src/plugins/nat/pnat/tests/test_genpackets.py
+++ b/src/plugins/nat/pnat/tests/test_genpackets.py
@@ -6,33 +6,35 @@ from importlib.machinery import SourceFileLoader
from scapy.all import *
from scapy.contrib.geneve import GENEVE
+
def hexstring(p):
s = bytes(p.__class__(p))
return ",".join("0x{:02x}".format(c) for c in s)
+
def output_test(filename, tests):
(name, ext) = os.path.basename(filename).split(".")
- print('/* DO NOT EDIT: automatically generated by test_genpackets.py */')
- print('/* clang-format off */')
- print('test_t tests_{}[] = {{'.format(name))
+ print("/* DO NOT EDIT: automatically generated by test_genpackets.py */")
+ print("/* clang-format off */")
+ print("test_t tests_{}[] = {{".format(name))
for t in tests:
- print(' {')
+ print(" {")
print(' .name = "{}",'.format(t[0]))
- print(' .nsend = {},'.format(len(t[1])))
- print(' .send = (char []){{{}}},'.format(hexstring(t[1])))
- print(' .nexpect = {},'.format(len(t[2])))
- print(' .expect = (char []){{{}}},'.format(hexstring(t[2])))
- print(' .expect_next_index = {}'.format(t[3]))
- print(' },')
- print('};')
- print('/* clang-format on */')
+ print(" .nsend = {},".format(len(t[1])))
+ print(" .send = (char []){{{}}},".format(hexstring(t[1])))
+ print(" .nexpect = {},".format(len(t[2])))
+ print(" .expect = (char []){{{}}},".format(hexstring(t[2])))
+ print(" .expect_next_index = {}".format(t[3]))
+ print(" },")
+ print("};")
+ print("/* clang-format on */")
+
# Read tests from file
for filename in sys.argv[1:]:
with open(filename) as f:
- content = f.read().replace('\n', '')
+ content = f.read().replace("\n", "")
tests = eval(content)
output_test(filename, tests)
-
diff --git a/src/plugins/srv6-mobile/extra/runner.py b/src/plugins/srv6-mobile/extra/runner.py
index b18fdc32766..eee89d7d41a 100755
--- a/src/plugins/srv6-mobile/extra/runner.py
+++ b/src/plugins/srv6-mobile/extra/runner.py
@@ -1,10 +1,8 @@
#!/usr/bin/env python3
-from os.path import dirname, realpath, split,\
- join, isdir, exists
+from os.path import dirname, realpath, split, join, isdir, exists
from os import remove, system, mkdir
-from logging import getLogger, basicConfig,\
- DEBUG, INFO, ERROR
+from logging import getLogger, basicConfig, DEBUG, INFO, ERROR
from argparse import ArgumentParser
from atexit import register
from shutil import rmtree
@@ -18,10 +16,7 @@ from scapy.contrib.gtp import *
from scapy.all import *
-verbose_levels = {
- 'error': ERROR,
- 'debug': DEBUG,
- 'info': INFO}
+verbose_levels = {"error": ERROR, "debug": DEBUG, "info": INFO}
class ContainerStartupError(Exception):
@@ -87,10 +82,8 @@ class Container(object):
image=image,
name=name,
privileged=True,
- volumes={
- temp: {
- 'bind': '/mnt',
- 'mode': 'rw'}})
+ volumes={temp: {"bind": "/mnt", "mode": "rw"}},
+ )
obj = cls.get(client, name)
if not obj:
@@ -119,7 +112,7 @@ class Container(object):
def vppctl_exec(self, cmd):
ec, resp = self._ref.exec_run(cmd="{} {}".format(self.cmd, cmd))
- assert(ec == 0)
+ assert ec == 0
return resp
def setup_host_interface(self, name, ip):
@@ -134,8 +127,7 @@ class Container(object):
self.vppctl_exec("create packet-generator interface pg0")
self.vppctl_exec("set int mac address pg0 {}".format(local_mac))
self.vppctl_exec("set int ip addr pg0 {}".format(local_ip))
- self.vppctl_exec(
- "set ip neighbor pg0 {} {}".format(remote_ip, remote_mac))
+ self.vppctl_exec("set ip neighbor pg0 {} {}".format(remote_ip, remote_mac))
self.vppctl_exec("set int state pg0 up")
def pg_create_interface4(self, local_ip, remote_ip, local_mac, remote_mac):
@@ -158,24 +150,32 @@ class Container(object):
self.vppctl_exec("set ip neighbor pg0 {} {}".format(remote_ip, remote_mac))
self.vppctl_exec("set int state pg0 up")
- def pg_create_interface4_name(self, ifname, local_ip, remote_ip, local_mac, remote_mac):
+ def pg_create_interface4_name(
+ self, ifname, local_ip, remote_ip, local_mac, remote_mac
+ ):
# remote_ip can't have subnet mask
time.sleep(2)
self.vppctl_exec("create packet-generator interface {}".format(ifname))
self.vppctl_exec("set int mac address {} {}".format(ifname, local_mac))
self.vppctl_exec("set int ip addr {} {}".format(ifname, local_ip))
- self.vppctl_exec("set ip neighbor {} {} {}".format(ifname, remote_ip, remote_mac))
+ self.vppctl_exec(
+ "set ip neighbor {} {} {}".format(ifname, remote_ip, remote_mac)
+ )
self.vppctl_exec("set int state {} up".format(ifname))
- def pg_create_interface6_name(self, ifname, local_ip, remote_ip, local_mac, remote_mac):
+ def pg_create_interface6_name(
+ self, ifname, local_ip, remote_ip, local_mac, remote_mac
+ ):
# remote_ip can't have subnet mask
time.sleep(2)
self.vppctl_exec("create packet-generator interface {}".format(ifname))
self.vppctl_exec("set int mac address {} {}".format(ifname, local_mac))
self.vppctl_exec("set int ip addr {} {}".format(ifname, local_ip))
- self.vppctl_exec("set ip neighbor {} {} {}".format(ifname, remote_ip, remote_mac))
+ self.vppctl_exec(
+ "set ip neighbor {} {} {}".format(ifname, remote_ip, remote_mac)
+ )
self.vppctl_exec("set int state {} up".format(ifname))
def pg_enable(self):
@@ -186,55 +186,56 @@ class Container(object):
wrpcap(self.pg_input_file, stream)
self.vppctl_exec(
"packet-generator new name pg-stream "
- "node ethernet-input pcap {}".format(
- self.pg_input_file_in))
+ "node ethernet-input pcap {}".format(self.pg_input_file_in)
+ )
def pg_start_capture(self):
if exists(self.pg_output_file):
remove(self.pg_output_file)
self.vppctl_exec(
- "packet-generator capture pg0 pcap {}".format(
- self.pg_output_file_in))
+ "packet-generator capture pg0 pcap {}".format(self.pg_output_file_in)
+ )
def pg_start_capture_name(self, ifname):
if exists(self.pg_output_file):
remove(self.pg_output_file)
self.vppctl_exec(
- "packet-generator capture {} pcap {}".format(
- ifname, self.pg_output_file_in))
+ "packet-generator capture {} pcap {}".format(ifname, self.pg_output_file_in)
+ )
def pg_read_packets(self):
return rdpcap(self.pg_output_file)
def set_ipv6_route(self, out_if_name, next_hop_ip, subnet):
self.vppctl_exec(
- "ip route add {} via host-{} {}".format(
- subnet, out_if_name, next_hop_ip))
+ "ip route add {} via host-{} {}".format(subnet, out_if_name, next_hop_ip)
+ )
def set_ipv6_route2(self, out_if_name, next_hop_ip, subnet):
self.vppctl_exec(
- "ip route add {} via {} {}".format(
- subnet, out_if_name, next_hop_ip))
+ "ip route add {} via {} {}".format(subnet, out_if_name, next_hop_ip)
+ )
def set_ip_pgroute(self, out_if_name, next_hop_ip, subnet):
- self.vppctl_exec("ip route add {} via {} {}".format(
- subnet, out_if_name, next_hop_ip))
+ self.vppctl_exec(
+ "ip route add {} via {} {}".format(subnet, out_if_name, next_hop_ip)
+ )
def set_ipv6_pgroute(self, out_if_name, next_hop_ip, subnet):
- self.vppctl_exec("ip route add {} via {} {}".format(
- subnet, out_if_name, next_hop_ip))
+ self.vppctl_exec(
+ "ip route add {} via {} {}".format(subnet, out_if_name, next_hop_ip)
+ )
def set_ipv6_default_route(self, out_if_name, next_hop_ip):
self.vppctl_exec(
- "ip route add ::/0 via host-{} {}".format(
- out_if_name, next_hop_ip))
+ "ip route add ::/0 via host-{} {}".format(out_if_name, next_hop_ip)
+ )
def enable_trace(self, count):
self.vppctl_exec("trace add af-packet-input {}".format(count))
class Containers(object):
-
def __init__(self, client, image):
self.client = client
self.image = image
@@ -247,37 +248,45 @@ class Containers(object):
register(lambda: remove(path))
def build(self, path, vpp_path):
- env = Environment(loader=FileSystemLoader(path),
- autoescape=True,
- trim_blocks=True)
-
- self.tmp_render(join(vpp_path, "Dockerfile"),
- env.get_template("Dockerfile.j2"),
- {'vpp_path': vpp_path})
-
- self.tmp_render(join(vpp_path, "startup.conf"),
- env.get_template("startup.conf.j2"),
- {'vpp_path': vpp_path})
-
- ref, _ = self.client.images.build(path=vpp_path,
- tag=self.image, rm=True)
+ env = Environment(
+ loader=FileSystemLoader(path), autoescape=True, trim_blocks=True
+ )
+
+ self.tmp_render(
+ join(vpp_path, "Dockerfile"),
+ env.get_template("Dockerfile.j2"),
+ {"vpp_path": vpp_path},
+ )
+
+ self.tmp_render(
+ join(vpp_path, "startup.conf"),
+ env.get_template("startup.conf.j2"),
+ {"vpp_path": vpp_path},
+ )
+
+ ref, _ = self.client.images.build(path=vpp_path, tag=self.image, rm=True)
return ref
def release(self, path, vpp_path):
- env = Environment(loader=FileSystemLoader(path),
- autoescape=True,
- trim_blocks=True)
-
- self.tmp_render(join(vpp_path, "Dockerfile"),
- env.get_template("Dockerfile.j2.release"),
- {'vpp_path': vpp_path})
-
- self.tmp_render(join(vpp_path, "startup.conf"),
- env.get_template("startup.conf.j2"),
- {'vpp_path': vpp_path})
-
- ref, _ = self.client.images.build(path=vpp_path,
- tag="srv6m-release-image", rm=True)
+ env = Environment(
+ loader=FileSystemLoader(path), autoescape=True, trim_blocks=True
+ )
+
+ self.tmp_render(
+ join(vpp_path, "Dockerfile"),
+ env.get_template("Dockerfile.j2.release"),
+ {"vpp_path": vpp_path},
+ )
+
+ self.tmp_render(
+ join(vpp_path, "startup.conf"),
+ env.get_template("startup.conf.j2"),
+ {"vpp_path": vpp_path},
+ )
+
+ ref, _ = self.client.images.build(
+ path=vpp_path, tag="srv6m-release-image", rm=True
+ )
return ref
def new(self, name):
@@ -299,7 +308,6 @@ class Containers(object):
class Network(object):
-
def __init__(self, ref, name):
self._name = name
self._ref = ref
@@ -310,8 +318,7 @@ class Network(object):
@classmethod
def new(cls, client, name):
- ref = client.networks.create(name, driver="bridge",
- check_duplicate=True)
+ ref = client.networks.create(name, driver="bridge", check_duplicate=True)
return cls(ref, name)
@classmethod
@@ -331,7 +338,6 @@ class Network(object):
class Networks(object):
-
def __init__(self, client):
self.client = client
@@ -352,14 +358,9 @@ class Program(object):
# for exmaple what the vpp is supposed to be
# in our topoloty overview
- instance_names = ["vpp-1",
- "vpp-2",
- "vpp-3",
- "vpp-4"]
+ instance_names = ["vpp-1", "vpp-2", "vpp-3", "vpp-4"]
- network_names = ["net-1",
- "net-2",
- "net-3"]
+ network_names = ["net-1", "net-2", "net-3"]
def __init__(self, image=None, prefix=None):
self.path = dirname(realpath(__file__))
@@ -469,15 +470,20 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface(
local_ip="B::1/120",
remote_ip="B::2",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="B::2") / ICMPv6EchoRequest())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="B::2")
+ / ICMPv6EchoRequest()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -516,16 +522,17 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface(
local_ip="B::1/120",
remote_ip="B::2",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr D1::")
- c1.vppctl_exec(
- "sr policy add bsid D1::999:1 next D2:: next D3:: next D4::")
+ c1.vppctl_exec("sr policy add bsid D1::999:1 next D2:: next D3:: next D4::")
c1.vppctl_exec("sr steer l3 B::/120 via bsid D1::999:1")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -539,8 +546,11 @@ class Program(object):
c3.set_ipv6_route("eth2", "A3::2", "D4::/128")
c3.set_ipv6_route("eth1", "A2::1", "C::/120")
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="B::2") / ICMPv6EchoRequest())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="B::2")
+ / ICMPv6EchoRequest()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -561,7 +571,7 @@ class Program(object):
for p in c4.pg_read_packets():
p.show2()
- ''' T.Map is obsolete
+ """ T.Map is obsolete
def test_tmap(self):
# TESTS:
# trace add af-packet-input 10
@@ -844,7 +854,7 @@ class Program(object):
print("Receiving packet on {}:".format(c4.name))
for p in c4.pg_read_packets():
p.show2()
- '''
+ """
def test_gtp4(self):
# TESTS:
@@ -863,16 +873,20 @@ class Program(object):
local_ip="172.16.0.1/30",
remote_ip="172.16.0.2/30",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface4(
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec("sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4")
+ c1.vppctl_exec(
+ "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4"
+ )
c1.vppctl_exec("sr steer l3 172.20.0.1/32 via bsid D5::")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -880,8 +894,8 @@ class Program(object):
c3.vppctl_exec("sr localsid address D3:: behavior end")
c4.vppctl_exec(
- "sr localsid prefix D4::/32 "
- "behavior end.m.gtp4.e v4src_position 64")
+ "sr localsid prefix D4::/32 " "behavior end.m.gtp4.e v4src_position 64"
+ )
c2.set_ipv6_route("eth2", "A2::2", "D3::/128")
c2.set_ipv6_route("eth1", "A1::1", "C::/120")
@@ -889,17 +903,19 @@ class Program(object):
c3.set_ipv6_route("eth1", "A2::1", "C::/120")
c4.set_ip_pgroute("pg0", "1.0.0.1", "172.20.0.1/32")
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IP(src="172.20.0.2", dst="172.20.0.1") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- IP(src="172.99.0.1", dst="172.99.0.2") /
- ICMP())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IP(src="172.20.0.2", dst="172.20.0.1")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / IP(src="172.99.0.1", dst="172.99.0.2")
+ / ICMP()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
- time.sleep(10)
+ time.sleep(10)
c1.enable_trace(10)
c4.enable_trace(10)
@@ -933,16 +949,20 @@ class Program(object):
local_ip="172.16.0.1/30",
remote_ip="172.16.0.2/30",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface4(
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:1111:aaaa:bbbb::")
- c1.vppctl_exec("sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4")
+ c1.vppctl_exec(
+ "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4"
+ )
c1.vppctl_exec("sr steer l3 172.20.0.1/32 via bsid D5::")
c2.vppctl_exec("sr localsid prefix D2:1111:aaaa::/48 behavior end usid 16")
@@ -950,8 +970,8 @@ class Program(object):
c3.vppctl_exec("sr localsid prefix D2:1111:bbbb::/48 behavior end usid 16")
c4.vppctl_exec(
- "sr localsid prefix D4::/32 "
- "behavior end.m.gtp4.e v4src_position 64")
+ "sr localsid prefix D4::/32 " "behavior end.m.gtp4.e v4src_position 64"
+ )
c2.set_ipv6_route("eth2", "A2::2", "D2:1111:bbbb::/48")
c2.set_ipv6_route("eth1", "A1::1", "C::/120")
@@ -959,17 +979,19 @@ class Program(object):
c3.set_ipv6_route("eth1", "A2::1", "C::/120")
c4.set_ip_pgroute("pg0", "1.0.0.1", "172.20.0.1/32")
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IP(src="172.20.0.2", dst="172.20.0.1") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- IP(src="172.99.0.1", dst="172.99.0.2") /
- ICMP())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IP(src="172.20.0.2", dst="172.20.0.1")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / IP(src="172.99.0.1", dst="172.99.0.2")
+ / ICMP()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
- time.sleep(10)
+ time.sleep(10)
c1.enable_trace(10)
c4.enable_trace(10)
@@ -1003,16 +1025,20 @@ class Program(object):
local_ip="172.16.0.1/30",
remote_ip="172.16.0.2/30",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface4(
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec("sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4")
+ c1.vppctl_exec(
+ "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4"
+ )
c1.vppctl_exec("sr steer l3 172.20.0.1/32 via bsid D5::")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1020,8 +1046,8 @@ class Program(object):
c3.vppctl_exec("sr localsid address D3:: behavior end")
c4.vppctl_exec(
- "sr localsid prefix D4::/32 "
- "behavior end.m.gtp4.e v4src_position 64")
+ "sr localsid prefix D4::/32 " "behavior end.m.gtp4.e v4src_position 64"
+ )
c2.set_ipv6_route("eth2", "A2::2", "D3::/128")
c2.set_ipv6_route("eth1", "A1::1", "C::/120")
@@ -1029,13 +1055,15 @@ class Program(object):
c3.set_ipv6_route("eth1", "A2::1", "C::/120")
c4.set_ip_pgroute("pg0", "1.0.0.1", "172.20.0.1/32")
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IP(src="172.20.0.2", dst="172.20.0.1") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- GTPPDUSessionContainer(type=1, R=1, QFI=3) /
- IP(src="172.99.0.1", dst="172.99.0.2") /
- ICMP())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IP(src="172.20.0.2", dst="172.20.0.1")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / GTPPDUSessionContainer(type=1, R=1, QFI=3)
+ / IP(src="172.99.0.1", dst="172.99.0.2")
+ / ICMP()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1073,16 +1101,20 @@ class Program(object):
local_ip="172.16.0.1/30",
remote_ip="172.16.0.2/30",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface4(
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec("sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4")
+ c1.vppctl_exec(
+ "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4"
+ )
c1.vppctl_exec("sr steer l3 172.20.0.1/32 via bsid D5::")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1090,8 +1122,8 @@ class Program(object):
c3.vppctl_exec("sr localsid address D3:: behavior end")
c4.vppctl_exec(
- "sr localsid prefix D4::/32 "
- "behavior end.m.gtp4.e v4src_position 64")
+ "sr localsid prefix D4::/32 " "behavior end.m.gtp4.e v4src_position 64"
+ )
c2.set_ipv6_route("eth2", "A2::2", "D3::/128")
c2.set_ipv6_route("eth1", "A1::1", "C::/120")
@@ -1099,10 +1131,12 @@ class Program(object):
c3.set_ipv6_route("eth1", "A2::1", "C::/120")
c4.set_ip_pgroute("pg0", "1.0.0.1", "172.20.0.1/32")
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IP(src="172.20.0.2", dst="172.20.0.1") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="echo_request", S=1, teid=200, seq=200))
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IP(src="172.20.0.2", dst="172.20.0.1")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="echo_request", S=1, teid=200, seq=200)
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1140,16 +1174,20 @@ class Program(object):
local_ip="172.16.0.1/30",
remote_ip="172.16.0.2/30",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface4(
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec("sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4")
+ c1.vppctl_exec(
+ "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4"
+ )
c1.vppctl_exec("sr steer l3 172.20.0.1/32 via bsid D5::")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1157,8 +1195,8 @@ class Program(object):
c3.vppctl_exec("sr localsid address D3:: behavior end")
c4.vppctl_exec(
- "sr localsid prefix D4::/32 "
- "behavior end.m.gtp4.e v4src_position 64")
+ "sr localsid prefix D4::/32 " "behavior end.m.gtp4.e v4src_position 64"
+ )
c2.set_ipv6_route("eth2", "A2::2", "D3::/128")
c2.set_ipv6_route("eth1", "A1::1", "C::/120")
@@ -1166,10 +1204,12 @@ class Program(object):
c3.set_ipv6_route("eth1", "A2::1", "C::/120")
c4.set_ip_pgroute("pg0", "1.0.0.1", "172.20.0.1/32")
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IP(src="172.20.0.2", dst="172.20.0.1") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="echo_response", S=1, teid=200, seq=200))
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IP(src="172.20.0.2", dst="172.20.0.1")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="echo_response", S=1, teid=200, seq=200)
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1207,16 +1247,20 @@ class Program(object):
local_ip="172.16.0.1/30",
remote_ip="172.16.0.2/30",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface4(
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec("sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4")
+ c1.vppctl_exec(
+ "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64 nhtype ipv4"
+ )
c1.vppctl_exec("sr steer l3 172.20.0.1/32 via bsid D5::")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1224,8 +1268,8 @@ class Program(object):
c3.vppctl_exec("sr localsid address D3:: behavior end")
c4.vppctl_exec(
- "sr localsid prefix D4::/32 "
- "behavior end.m.gtp4.e v4src_position 64")
+ "sr localsid prefix D4::/32 " "behavior end.m.gtp4.e v4src_position 64"
+ )
c2.set_ipv6_route("eth2", "A2::2", "D3::/128")
c2.set_ipv6_route("eth1", "A1::1", "C::/120")
@@ -1233,12 +1277,15 @@ class Program(object):
c3.set_ipv6_route("eth1", "A2::1", "C::/120")
c4.set_ip_pgroute("pg0", "1.0.0.1", "172.20.0.1/32")
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IP(src="172.20.0.2", dst="172.20.0.1") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="error_indication", S=1, teid=200, seq=200)/
- IE_TEIDI(TEIDI=65535)/IE_GSNAddress(address="1.1.1.1")/
- IE_PrivateExtension(extention_value="z"))
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IP(src="172.20.0.2", dst="172.20.0.1")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="error_indication", S=1, teid=200, seq=200)
+ / IE_TEIDI(TEIDI=65535)
+ / IE_GSNAddress(address="1.1.1.1")
+ / IE_PrivateExtension(extention_value="z")
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1276,16 +1323,20 @@ class Program(object):
local_ip="172.16.0.1/30",
remote_ip="172.16.0.2/30",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface4(
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec("sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64")
+ c1.vppctl_exec(
+ "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64"
+ )
c1.vppctl_exec("sr steer l3 172.20.0.1/32 via bsid D5::")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1293,8 +1344,8 @@ class Program(object):
c3.vppctl_exec("sr localsid address D3:: behavior end")
c4.vppctl_exec(
- "sr localsid prefix D4::/32 "
- "behavior end.m.gtp4.e v4src_position 64")
+ "sr localsid prefix D4::/32 " "behavior end.m.gtp4.e v4src_position 64"
+ )
c2.set_ipv6_route("eth2", "A2::2", "D3::/128")
c2.set_ipv6_route("eth1", "A1::1", "C::/120")
@@ -1302,12 +1353,14 @@ class Program(object):
c3.set_ipv6_route("eth1", "A2::1", "C::/120")
c4.set_ip_pgroute("pg0", "1.0.0.1", "172.20.0.1/32")
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IP(src="172.20.0.2", dst="172.20.0.1") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- IPv6(src="2001::1", dst="2002::1") /
- ICMPv6EchoRequest())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IP(src="172.20.0.2", dst="172.20.0.1")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / IPv6(src="2001::1", dst="2002::1")
+ / ICMPv6EchoRequest()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1345,16 +1398,20 @@ class Program(object):
local_ip="172.16.0.1/30",
remote_ip="172.16.0.2/30",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface4(
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec("sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64")
+ c1.vppctl_exec(
+ "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 v6src_prefix C1::/64"
+ )
c1.vppctl_exec("sr steer l3 172.20.0.1/32 via bsid D5::")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1362,8 +1419,8 @@ class Program(object):
c3.vppctl_exec("sr localsid address D3:: behavior end")
c4.vppctl_exec(
- "sr localsid prefix D4::/32 "
- "behavior end.m.gtp4.e v4src_position 64")
+ "sr localsid prefix D4::/32 " "behavior end.m.gtp4.e v4src_position 64"
+ )
c2.set_ipv6_route("eth2", "A2::2", "D3::/128")
c2.set_ipv6_route("eth1", "A1::1", "C::/120")
@@ -1371,13 +1428,15 @@ class Program(object):
c3.set_ipv6_route("eth1", "A2::1", "C::/120")
c4.set_ip_pgroute("pg0", "1.0.0.1", "172.20.0.1/32")
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IP(src="172.20.0.2", dst="172.20.0.1") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- GTPPDUSessionContainer(R=1, QFI=3) /
- IPv6(src="2001::1", dst="2002::1") /
- ICMPv6EchoRequest())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IP(src="172.20.0.2", dst="172.20.0.1")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / GTPPDUSessionContainer(R=1, QFI=3)
+ / IPv6(src="2001::1", dst="2002::1")
+ / ICMPv6EchoRequest()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1419,18 +1478,19 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface(
local_ip="B::1/120",
remote_ip="B::2",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
+ c1.vppctl_exec("sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1447,12 +1507,14 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- IP(src="172.99.0.1", dst="172.99.0.2") /
- ICMP())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / IP(src="172.99.0.1", dst="172.99.0.2")
+ / ICMP()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1494,18 +1556,19 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface(
local_ip="B::1/120",
remote_ip="B::2",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
+ c1.vppctl_exec("sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1522,13 +1585,15 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- GTPPDUSessionContainer(type=1, R=1, QFI=3) /
- IP(src="172.99.0.1", dst="172.99.0.2") /
- ICMP())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / GTPPDUSessionContainer(type=1, R=1, QFI=3)
+ / IP(src="172.99.0.1", dst="172.99.0.2")
+ / ICMP()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1570,18 +1635,19 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface(
local_ip="B::1/120",
remote_ip="B::2",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
+ c1.vppctl_exec("sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1598,10 +1664,12 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="echo_request", S=1, teid=200, seq=300))
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="echo_request", S=1, teid=200, seq=300)
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1643,18 +1711,19 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface(
local_ip="B::1/120",
remote_ip="B::2",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
+ c1.vppctl_exec("sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1671,10 +1740,12 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="echo_response", S=1, teid=200, seq=300))
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="echo_response", S=1, teid=200, seq=300)
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1716,18 +1787,19 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface(
local_ip="B::1/120",
remote_ip="B::2",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
+ c1.vppctl_exec("sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1744,12 +1816,15 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="error_indication", S=1, teid=200, seq=300)/
- IE_TEIDI(TEIDI=65535)/IE_GSNAddress(address="1.1.1.1")/
- IE_PrivateExtension(extention_value="z"))
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="error_indication", S=1, teid=200, seq=300)
+ / IE_TEIDI(TEIDI=65535)
+ / IE_GSNAddress(address="1.1.1.1")
+ / IE_PrivateExtension(extention_value="z")
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1791,18 +1866,19 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface(
local_ip="B::1/120",
remote_ip="B::2",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
+ c1.vppctl_exec("sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1819,12 +1895,14 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- IPv6(src="2001::1", dst="2002::1") /
- ICMPv6EchoRequest())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / IPv6(src="2001::1", dst="2002::1")
+ / ICMPv6EchoRequest()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1866,18 +1944,19 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface(
local_ip="B::1/120",
remote_ip="B::2",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
+ c1.vppctl_exec("sr localsid prefix D::/64 behavior end.m.gtp6.d.di D4::/64")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1894,13 +1973,15 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- GTPPDUSessionContainer(R=1, QFI=3) /
- IPv6(src="2001::1", dst="2002::1") /
- ICMPv6EchoRequest())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / GTPPDUSessionContainer(R=1, QFI=3)
+ / IPv6(src="2001::1", dst="2002::1")
+ / ICMPv6EchoRequest()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -1942,18 +2023,19 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface4(
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.d D4::/64")
+ c1.vppctl_exec("sr localsid prefix D::/64 behavior end.m.gtp6.d D4::/64")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -1971,12 +2053,14 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- IP(src="172.100.0.1", dst="172.200.0.1") /
- ICMP())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / IP(src="172.100.0.1", dst="172.200.0.1")
+ / ICMP()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -2018,18 +2102,19 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface4(
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.d D4::/64")
+ c1.vppctl_exec("sr localsid prefix D::/64 behavior end.m.gtp6.d D4::/64")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -2047,13 +2132,15 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- GTPPDUSessionContainer(R=1, QFI=3) /
- IP(src="172.100.0.1", dst="172.200.0.1") /
- ICMP())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / GTPPDUSessionContainer(R=1, QFI=3)
+ / IP(src="172.100.0.1", dst="172.200.0.1")
+ / ICMP()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -2095,18 +2182,19 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface(
local_ip="B::1/120",
remote_ip="B::2",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.d D4::/64")
+ c1.vppctl_exec("sr localsid prefix D::/64 behavior end.m.gtp6.d D4::/64")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -2124,12 +2212,14 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- IPv6(src="2001::1", dst="2002::1") /
- ICMPv6EchoRequest())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / IPv6(src="2001::1", dst="2002::1")
+ / ICMPv6EchoRequest()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -2171,18 +2261,19 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c4.pg_create_interface(
local_ip="B::1/120",
remote_ip="B::2",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D4:: next D2:: next D3::")
- c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.d D4::/64")
+ c1.vppctl_exec("sr localsid prefix D::/64 behavior end.m.gtp6.d D4::/64")
c2.vppctl_exec("sr localsid address D2:: behavior end")
@@ -2200,13 +2291,15 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- GTPPDUSessionContainer(R=1, QFI=3) /
- IPv6(src="2001::1", dst="2002::1") /
- ICMPv6EchoRequest())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / GTPPDUSessionContainer(R=1, QFI=3)
+ / IPv6(src="2001::1", dst="2002::1")
+ / ICMPv6EchoRequest()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -2246,19 +2339,22 @@ class Program(object):
local_ip="C::1/120",
remote_ip="C::2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c1.pg_create_interface4_name(
ifname="pg1",
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec(
- "sr localsid prefix D::/64 behavior end.m.gtp6.dt46 fib-table 0 local-fib-table 0")
+ "sr localsid prefix D::/64 behavior end.m.gtp6.dt46 fib-table 0 local-fib-table 0"
+ )
c1.vppctl_exec("set ip neighbor pg1 1.0.0.1 aa:bb:cc:dd:ee:22")
c1.set_ip_pgroute("pg1", "1.0.0.1", "172.200.0.1/32")
@@ -2266,12 +2362,14 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IPv6(src="C::2", dst="D::2") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- IP(src="172.100.0.1", dst="172.200.0.1") /
- ICMP())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IPv6(src="C::2", dst="D::2")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / IP(src="172.100.0.1", dst="172.200.0.1")
+ / ICMP()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -2310,14 +2408,16 @@ class Program(object):
local_ip="172.16.0.1/30",
remote_ip="172.16.0.2",
local_mac="aa:bb:cc:dd:ee:01",
- remote_mac="aa:bb:cc:dd:ee:02")
+ remote_mac="aa:bb:cc:dd:ee:02",
+ )
c1.pg_create_interface4_name(
ifname="pg1",
local_ip="1.0.0.2/30",
remote_ip="1.0.0.1",
local_mac="aa:bb:cc:dd:ee:11",
- remote_mac="aa:bb:cc:dd:ee:22")
+ remote_mac="aa:bb:cc:dd:ee:22",
+ )
c1.vppctl_exec("set sr encaps source addr A1::1")
c1.vppctl_exec("sr policy add bsid D5:: behavior t.m.gtp4.dt4 fib-table 0")
@@ -2329,12 +2429,14 @@ class Program(object):
print("Waiting...")
time.sleep(30)
- p = (Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01") /
- IP(src="172.20.0.2", dst="172.20.0.1") /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- IP(src="172.100.0.1", dst="172.200.0.1") /
- ICMP())
+ p = (
+ Ether(src="aa:bb:cc:dd:ee:02", dst="aa:bb:cc:dd:ee:01")
+ / IP(src="172.20.0.2", dst="172.20.0.1")
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / IP(src="172.100.0.1", dst="172.200.0.1")
+ / ICMP()
+ )
print("Sending packet on {}:".format(c1.name))
p.show2()
@@ -2360,17 +2462,21 @@ class Program(object):
for i, name in enumerate(self.instance_names):
name = self.get_name(name)
- print("\t[{}] {} - {}".format(
- i, name,
- "running" if self.containers.get(name) else "missing"))
+ print(
+ "\t[{}] {} - {}".format(
+ i, name, "running" if self.containers.get(name) else "missing"
+ )
+ )
print("Networks:")
for i, name in enumerate(self.network_names):
name = self.get_name(name)
- print("\t[{}] {} - {}".format(
- i, name,
- "running" if self.networks.get(name) else "missing"))
+ print(
+ "\t[{}] {} - {}".format(
+ i, name, "running" if self.networks.get(name) else "missing"
+ )
+ )
def build_image(self):
print("VPP Path (build): {}".format(self.vpp_path))
@@ -2382,7 +2488,9 @@ class Program(object):
system(
"docker cp release-build:{}/vpp-package.tgz {}/".format(
- self.vpp_path, self.vpp_path))
+ self.vpp_path, self.vpp_path
+ )
+ )
instance.rem()
@@ -2408,39 +2516,30 @@ class Program(object):
def get_args():
parser = ArgumentParser()
- parser.add_argument("--verbose", choices=['error', 'debug', 'info'])
+ parser.add_argument("--verbose", choices=["error", "debug", "info"])
- parser.add_argument('--image', choices=['debug', 'release'])
+ parser.add_argument("--image", choices=["debug", "release"])
subparsers = parser.add_subparsers()
- p1 = subparsers.add_parser(
- "infra", help="Infrastructure related commands.")
+ p1 = subparsers.add_parser("infra", help="Infrastructure related commands.")
p1.add_argument(
- "op",
- choices=[
- 'stop',
- 'start',
- 'status',
- 'restart',
- 'build',
- 'release'])
+ "op", choices=["stop", "start", "status", "restart", "build", "release"]
+ )
p1.add_argument("--prefix")
p1.add_argument("--image")
p2 = subparsers.add_parser("cmd", help="Instance related commands.")
- p2.add_argument("op", choices=['vppctl', 'bash'])
+ p2.add_argument("op", choices=["vppctl", "bash"])
p2.add_argument(
- "index",
- type=int,
- help="Container instance index. (./runner.py infra status)")
+ "index", type=int, help="Container instance index. (./runner.py infra status)"
+ )
- p2.add_argument(
- "--command", help="Only vppctl supports this optional argument.")
+ p2.add_argument("--command", help="Only vppctl supports this optional argument.")
p3 = subparsers.add_parser("test", help="Test related commands.")
@@ -2473,7 +2572,9 @@ def get_args():
"gtp6_ipv6",
"gtp6_ipv6_5g",
"gtp6_dt",
- "gtp4_dt"])
+ "gtp4_dt",
+ ],
+ )
args = parser.parse_args()
if not hasattr(args, "op") or not args.op:
@@ -2483,15 +2584,14 @@ def get_args():
return vars(args)
-def main(op=None, prefix=None, verbose=None,
- image=None, index=None, command=None):
+def main(op=None, prefix=None, verbose=None, image=None, index=None, command=None):
if verbose:
basicConfig(level=verbose_levels[verbose])
- if image == 'release':
+ if image == "release":
image = "srv6m-release-image"
- elif image == 'debug':
+ elif image == "debug":
image = "srv6m-image"
else:
image = "srv6m-image"
@@ -2501,23 +2601,23 @@ def main(op=None, prefix=None, verbose=None,
program = Program(image, prefix)
try:
- if op == 'build':
+ if op == "build":
program.build_image()
- elif op == 'release':
+ elif op == "release":
program.release_image()
- elif op == 'stop':
+ elif op == "stop":
program.stop_containers()
- elif op == 'start':
+ elif op == "start":
program.start_containers()
- elif op == 'status':
+ elif op == "status":
program.status_containers()
- elif op == 'vppctl':
+ elif op == "vppctl":
program.vppctl(index, command)
- elif op == 'bash':
+ elif op == "bash":
program.bash(index)
- elif op == 'ping':
+ elif op == "ping":
program.test_ping()
- elif op == 'srv6':
+ elif op == "srv6":
program.test_srv6()
# elif op == 'tmap':
# program.test_tmap()
@@ -2527,47 +2627,47 @@ def main(op=None, prefix=None, verbose=None,
# program.test_tmap_ipv6()
# elif op == 'tmap_ipv6_5g':
# program.test_tmap_ipv6_5g()
- elif op == 'gtp4':
+ elif op == "gtp4":
program.test_gtp4()
- elif op == 'gtp4_usid':
+ elif op == "gtp4_usid":
program.test_gtp4_usid()
- elif op == 'gtp4_5g':
+ elif op == "gtp4_5g":
program.test_gtp4_5g()
- elif op == 'gtp4_echo':
+ elif op == "gtp4_echo":
program.test_gtp4_echo()
- elif op == 'gtp4_reply':
+ elif op == "gtp4_reply":
program.test_gtp4_reply()
- elif op == 'gtp4_error':
+ elif op == "gtp4_error":
program.test_gtp4_error()
- elif op == 'gtp4_ipv6':
+ elif op == "gtp4_ipv6":
program.test_gtp4_ipv6()
- elif op == 'gtp4_ipv6_5g':
+ elif op == "gtp4_ipv6_5g":
program.test_gtp4_ipv6_5g()
- elif op == 'gtp6_drop_in':
+ elif op == "gtp6_drop_in":
program.test_gtp6_drop_in()
- elif op == 'gtp6_drop_in_5g':
+ elif op == "gtp6_drop_in_5g":
program.test_gtp6_drop_in_5g()
- elif op == 'gtp6_drop_in_echo':
+ elif op == "gtp6_drop_in_echo":
program.test_gtp6_drop_in_echo()
- elif op == 'gtp6_drop_in_reply':
+ elif op == "gtp6_drop_in_reply":
program.test_gtp6_drop_in_reply()
- elif op == 'gtp6_drop_in_error':
+ elif op == "gtp6_drop_in_error":
program.test_gtp6_drop_in_error()
- elif op == 'gtp6_drop_in_ipv6':
+ elif op == "gtp6_drop_in_ipv6":
program.test_gtp6_drop_in_ipv6()
- elif op == 'gtp6_drop_in_ipv6_5g':
+ elif op == "gtp6_drop_in_ipv6_5g":
program.test_gtp6_drop_in_ipv6_5g()
- elif op == 'gtp6':
+ elif op == "gtp6":
program.test_gtp6()
- elif op == 'gtp6_5g':
+ elif op == "gtp6_5g":
program.test_gtp6_5g()
- elif op == 'gtp6_ipv6':
+ elif op == "gtp6_ipv6":
program.test_gtp6_ipv6()
- elif op == 'gtp6_ipv6_5g':
+ elif op == "gtp6_ipv6_5g":
program.test_gtp6_ipv6_5g()
- elif op == 'gtp6_dt':
+ elif op == "gtp6_dt":
program.test_gtp6_dt()
- elif op == 'gtp4_dt':
+ elif op == "gtp4_dt":
program.test_gtp4_dt()
except Exception:
diff --git a/src/scripts/fts.py b/src/scripts/fts.py
index f2b877fb2c7..e8ff477c788 100755
--- a/src/scripts/fts.py
+++ b/src/scripts/fts.py
@@ -21,25 +21,28 @@ schema = {
"name": {"type": "string"},
"description": {"type": "string"},
"maintainer": {"$ref": "#/definitions/maintainers"},
- "state": {"type": "string",
- "enum": ["production", "experimental", "development"]},
+ "state": {
+ "type": "string",
+ "enum": ["production", "experimental", "development"],
+ },
"features": {"$ref": "#/definitions/features"},
"missing": {"$ref": "#/definitions/features"},
- "properties": {"type": "array",
- "items": {"type": "string",
- "enum": ["API", "CLI", "STATS",
- "MULTITHREAD"]},
- },
+ "properties": {
+ "type": "array",
+ "items": {"type": "string", "enum": ["API", "CLI", "STATS", "MULTITHREAD"]},
+ },
},
"additionalProperties": False,
"definitions": {
"maintainers": {
- "anyof": [{
- "type": "array",
- "items": {"type": "string"},
- "minItems": 1,
- },
- {"type": "string"}],
+ "anyof": [
+ {
+ "type": "array",
+ "items": {"type": "string"},
+ "minItems": 1,
+ },
+ {"type": "string"},
+ ],
},
"featureobject": {
"type": "object",
@@ -49,9 +52,12 @@ schema = {
},
"features": {
"type": "array",
- "items": {"anyOf": [{"$ref": "#/definitions/featureobject"},
- {"type": "string"},
- ]},
+ "items": {
+ "anyOf": [
+ {"$ref": "#/definitions/featureobject"},
+ {"type": "string"},
+ ]
+ },
"minItems": 1,
},
},
@@ -59,14 +65,15 @@ schema = {
DEFAULT_REPO_LINK = "https://github.com/FDio/vpp/blob/master/"
+
def filelist_from_git_status():
filelist = []
- git_status = 'git status --porcelain */FEATURE*.yaml'
+ git_status = "git status --porcelain */FEATURE*.yaml"
rv = run(git_status.split(), stdout=PIPE, stderr=PIPE)
if rv.returncode != 0:
sys.exit(rv.returncode)
- for l in rv.stdout.decode('ascii').split('\n'):
+ for l in rv.stdout.decode("ascii").split("\n"):
if len(l):
filelist.append(l.split()[1])
return filelist
@@ -74,24 +81,26 @@ def filelist_from_git_status():
def filelist_from_git_ls():
filelist = []
- git_ls = 'git ls-files :(top)*/FEATURE*.yaml'
+ git_ls = "git ls-files :(top)*/FEATURE*.yaml"
rv = run(git_ls.split(), stdout=PIPE, stderr=PIPE)
if rv.returncode != 0:
sys.exit(rv.returncode)
- for l in rv.stdout.decode('ascii').split('\n'):
+ for l in rv.stdout.decode("ascii").split("\n"):
if len(l):
filelist.append(l)
return filelist
+
def version_from_git():
- git_describe = 'git describe'
+ git_describe = "git describe"
rv = run(git_describe.split(), stdout=PIPE, stderr=PIPE)
if rv.returncode != 0:
sys.exit(rv.returncode)
- return rv.stdout.decode('ascii').split('\n')[0]
+ return rv.stdout.decode("ascii").split("\n")[0]
+
-class MarkDown():
+class MarkDown:
_dispatch = {}
def __init__(self, stream):
@@ -101,102 +110,115 @@ class MarkDown():
def print_maintainer(self, o):
write = self.stream.write
if type(o) is list:
- write('Maintainers: ' +
- ', '.join('{m}'.format(m=m) for m in
- o) + ' \n')
+ write("Maintainers: " + ", ".join("{m}".format(m=m) for m in o) + " \n")
else:
- write('Maintainer: {o} \n'.format(o=o))
+ write("Maintainer: {o} \n".format(o=o))
- _dispatch['maintainer'] = print_maintainer
+ _dispatch["maintainer"] = print_maintainer
def print_features(self, o, indent=0):
write = self.stream.write
for f in o:
- indentstr = ' ' * indent
+ indentstr = " " * indent
if type(f) is dict:
for k, v in f.items():
- write('{indentstr}- {k}\n'.format(indentstr=indentstr, k=k))
+ write("{indentstr}- {k}\n".format(indentstr=indentstr, k=k))
self.print_features(v, indent + 2)
else:
- write('{indentstr}- {f}\n'.format(indentstr=indentstr, f=f))
- write('\n')
- _dispatch['features'] = print_features
+ write("{indentstr}- {f}\n".format(indentstr=indentstr, f=f))
+ write("\n")
+
+ _dispatch["features"] = print_features
def print_markdown_header(self, o):
write = self.stream.write
- write('## {o}\n'.format(o=o))
- _dispatch['markdown_header'] = print_markdown_header
+ write("## {o}\n".format(o=o))
+
+ _dispatch["markdown_header"] = print_markdown_header
def print_name(self, o):
write = self.stream.write
- write('### {o}\n'.format(o=o))
+ write("### {o}\n".format(o=o))
self.toc.append(o)
- _dispatch['name'] = print_name
+
+ _dispatch["name"] = print_name
def print_description(self, o):
write = self.stream.write
- write('\n{o}\n\n'.format(o=o))
- _dispatch['description'] = print_description
+ write("\n{o}\n\n".format(o=o))
+
+ _dispatch["description"] = print_description
def print_state(self, o):
write = self.stream.write
- write('Feature maturity level: {o} \n'.format(o=o))
- _dispatch['state'] = print_state
+ write("Feature maturity level: {o} \n".format(o=o))
+
+ _dispatch["state"] = print_state
def print_properties(self, o):
write = self.stream.write
- write('Supports: {s} \n'.format(s=" ".join(o)))
- _dispatch['properties'] = print_properties
+ write("Supports: {s} \n".format(s=" ".join(o)))
+
+ _dispatch["properties"] = print_properties
def print_missing(self, o):
write = self.stream.write
- write('\nNot yet implemented: \n')
+ write("\nNot yet implemented: \n")
self.print_features(o)
- _dispatch['missing'] = print_missing
+
+ _dispatch["missing"] = print_missing
def print_code(self, o):
write = self.stream.write
- write('Source Code: [{o}]({o}) \n'.format(o=o))
- _dispatch['code'] = print_code
+ write("Source Code: [{o}]({o}) \n".format(o=o))
+
+ _dispatch["code"] = print_code
def print(self, t, o):
write = self.stream.write
if t in self._dispatch:
- self._dispatch[t](self, o,)
+ self._dispatch[t](
+ self,
+ o,
+ )
else:
- write('NOT IMPLEMENTED: {t}\n')
+ write("NOT IMPLEMENTED: {t}\n")
+
def output_toc(toc, stream):
write = stream.write
- write('# VPP Supported Features\n')
+ write("# VPP Supported Features\n")
for t in toc:
- ref = t.lower().replace(' ', '-')
- write('[{t}](#{ref}) \n'.format(t=t, ref=ref))
+ ref = t.lower().replace(" ", "-")
+ write("[{t}](#{ref}) \n".format(t=t, ref=ref))
+
def featuresort(k):
- return k[1]['name']
+ return k[1]["name"]
+
def featurelistsort(k):
orderedfields = {
- 'name': 0,
- 'maintainer': 1,
- 'description': 2,
- 'features': 3,
- 'state': 4,
- 'properties': 5,
- 'missing': 6,
- 'code': 7,
+ "name": 0,
+ "maintainer": 1,
+ "description": 2,
+ "features": 3,
+ "state": 4,
+ "properties": 5,
+ "missing": 6,
+ "code": 7,
}
return orderedfields[k[0]]
+
def output_markdown(features, fields, notfields, repository_url):
stream = StringIO()
m = MarkDown(stream)
- m.print('markdown_header', 'Feature Details:')
+ m.print("markdown_header", "Feature Details:")
for path, featuredef in sorted(features.items(), key=featuresort):
codeurl = urllib.parse.urljoin(repository_url, os.path.dirname(path))
- featuredef['code'] = codeurl
+ featuredef["code"] = codeurl
for k, v in sorted(featuredef.items(), key=featurelistsort):
if notfields:
if k not in notfields:
@@ -211,24 +233,45 @@ def output_markdown(features, fields, notfields, repository_url):
output_toc(m.toc, tocstream)
return tocstream, stream
+
def main():
- parser = argparse.ArgumentParser(description='VPP Feature List.')
- parser.add_argument('--validate', dest='validate', action='store_true',
- help='validate the FEATURE.yaml file')
- parser.add_argument("--repolink", metavar="repolink", default=DEFAULT_REPO_LINK,
- help="Link to public repository [%s]" %
- DEFAULT_REPO_LINK)
- parser.add_argument('--git-status', dest='git_status', action='store_true',
- help='Get filelist from git status')
- parser.add_argument('--all', dest='all', action='store_true',
- help='Validate all files in repository')
- parser.add_argument('--markdown', dest='markdown', action='store_true',
- help='Output feature table in markdown')
- parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
- default=sys.stdin)
+ parser = argparse.ArgumentParser(description="VPP Feature List.")
+ parser.add_argument(
+ "--validate",
+ dest="validate",
+ action="store_true",
+ help="validate the FEATURE.yaml file",
+ )
+ parser.add_argument(
+ "--repolink",
+ metavar="repolink",
+ default=DEFAULT_REPO_LINK,
+ help="Link to public repository [%s]" % DEFAULT_REPO_LINK,
+ )
+ parser.add_argument(
+ "--git-status",
+ dest="git_status",
+ action="store_true",
+ help="Get filelist from git status",
+ )
+ parser.add_argument(
+ "--all",
+ dest="all",
+ action="store_true",
+ help="Validate all files in repository",
+ )
+ parser.add_argument(
+ "--markdown",
+ dest="markdown",
+ action="store_true",
+ help="Output feature table in markdown",
+ )
+ parser.add_argument(
+ "infile", nargs="?", type=argparse.FileType("r"), default=sys.stdin
+ )
group = parser.add_mutually_exclusive_group()
- group.add_argument('--include', help='List of fields to include')
- group.add_argument('--exclude', help='List of fields to exclude')
+ group.add_argument("--include", help="List of fields to include")
+ group.add_argument("--exclude", help="List of fields to exclude")
args = parser.parse_args()
features = {}
@@ -240,11 +283,11 @@ def main():
filelist = args.infile
if args.include:
- fields = args.include.split(',')
+ fields = args.include.split(",")
else:
fields = []
if args.exclude:
- notfields = args.exclude.split(',')
+ notfields = args.exclude.split(",")
else:
notfields = []
@@ -252,13 +295,15 @@ def main():
featurefile = featurefile.rstrip()
# Load configuration file
- with open(featurefile, encoding='utf-8') as f:
+ with open(featurefile, encoding="utf-8") as f:
cfg = yaml.load(f, Loader=yaml.SafeLoader)
try:
validate(instance=cfg, schema=schema)
except exceptions.ValidationError:
- print('File does not validate: {featurefile}' \
- .format(featurefile=featurefile), file=sys.stderr)
+ print(
+ "File does not validate: {featurefile}".format(featurefile=featurefile),
+ file=sys.stderr,
+ )
raise
features[featurefile] = cfg
@@ -270,5 +315,5 @@ def main():
stream.close()
-if __name__ == '__main__':
+if __name__ == "__main__":
main()
diff --git a/src/scripts/host-stack/cc_plots.py b/src/scripts/host-stack/cc_plots.py
index 20f5bd6a3f1..f0296af7223 100755
--- a/src/scripts/host-stack/cc_plots.py
+++ b/src/scripts/host-stack/cc_plots.py
@@ -6,214 +6,242 @@ import argparse
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
-class Point():
+
+class Point:
"CC event"
+
def __init__(self, x, y):
self.x = x
self.y = y
+
def listx(points):
- return list(map(lambda pt: pt.x, points))
+ return list(map(lambda pt: pt.x, points))
+
def listy(points):
- return list(map(lambda pt: pt.y, points))
+ return list(map(lambda pt: pt.y, points))
+
def plot_data(d):
- plt.figure(1)
-
- cwndx = listx(d["cwnd"])
- cwndy = listy(d["cwnd"])
- congx = listx(d["congestion"])
- congy = listy(d["congestion"])
- rcvrdx = listx(d["recovered"])
- rcvrdy = listy(d["recovered"])
- rxttx = listx(d["rxtTimeout"])
- rxtty = listy(d["rxtTimeout"])
-
- # cwnd/ssthresh/cc events
- plt.subplot(311)
- plt.title("cwnd/ssthresh")
- pcwnd = plt.plot(cwndx, cwndy, 'r')
- psst = plt.plot(cwndx, d["ssthresh"], 'y-')
- pcong = plt.plot(congx, congy,'yo')
- precov = plt.plot(rcvrdx, rcvrdy,'co')
- prxtt = plt.plot(rxttx, rxtty,'mo')
-
- marker1 = Line2D(range(1), range(1), color="r")
- marker2 = Line2D(range(1), range(1), color="y")
- marker3 = Line2D(range(1), range(1), color="w", marker="o", markerfacecolor="y")
- marker4 = Line2D(range(1), range(1), color="w", marker="o", markerfacecolor="c")
- marker5 = Line2D(range(1), range(1), color="w", marker="o", markerfacecolor="m")
- plt.legend((marker1, marker2, marker3, marker4, marker5),
- ('cwnd', 'ssthresh', 'congestion', 'recovered', 'rxt-timeout'),
- loc=4)
- axes = plt.gca()
- axes.set_ylim([-20e4, max(cwndy) + 20e4])
-
- # snd variables
- plt.subplot(312)
- plt.title("cc variables")
- plt.plot(cwndx, d["space"], 'g-', markersize=1)
- plt.plot(cwndx, d["flight"], 'b-', markersize=1)
- plt.plot(cwndx, d["sacked"], 'm:', markersize=1)
- plt.plot(cwndx, d["lost"], 'y:', markersize=1)
- plt.plot(cwndx, d["cc-space"], 'k:', markersize=1)
- plt.plot(cwndx, cwndy, 'ro', markersize=2)
-
- plt.plot(congx, congy, 'y^', markersize=10, markerfacecolor="y")
- plt.plot(rcvrdx, rcvrdy, 'c^', markersize=10, markerfacecolor="c")
- plt.plot(rxttx, rxtty, 'm^', markersize=10, markerfacecolor="m")
-
- #plt.plot(cwndx, d["snd_wnd"], 'ko', markersize=1)
- plt.legend(("snd-space", "flight", "sacked", "lost", "cc-space", "cwnd",
- "congestion", "recovered", "rxt-timeout"),
- loc=1)
-
- # rto/srrt/rttvar
- plt.subplot(313)
- plt.title("rtt")
- plt.plot(cwndx, d["srtt"], 'g-')
- plt.plot(cwndx, [x/1000 for x in d["mrtt-us"]], 'r-')
- plt.plot(cwndx, d["rttvar"], 'b-')
- plt.legend(["srtt", "mrtt-us", "rttvar"])
- axes = plt.gca()
- #plt.plot(cwndx, rto, 'r-')
- #axes.set_ylim([0, int(max(rto[2:len(rto)])) + 50])
-
- # show
- plt.show()
-
-def find_pattern(file_path,session_idx):
+ plt.figure(1)
+
+ cwndx = listx(d["cwnd"])
+ cwndy = listy(d["cwnd"])
+ congx = listx(d["congestion"])
+ congy = listy(d["congestion"])
+ rcvrdx = listx(d["recovered"])
+ rcvrdy = listy(d["recovered"])
+ rxttx = listx(d["rxtTimeout"])
+ rxtty = listy(d["rxtTimeout"])
+
+ # cwnd/ssthresh/cc events
+ plt.subplot(311)
+ plt.title("cwnd/ssthresh")
+ pcwnd = plt.plot(cwndx, cwndy, "r")
+ psst = plt.plot(cwndx, d["ssthresh"], "y-")
+ pcong = plt.plot(congx, congy, "yo")
+ precov = plt.plot(rcvrdx, rcvrdy, "co")
+ prxtt = plt.plot(rxttx, rxtty, "mo")
+
+ marker1 = Line2D(range(1), range(1), color="r")
+ marker2 = Line2D(range(1), range(1), color="y")
+ marker3 = Line2D(range(1), range(1), color="w", marker="o", markerfacecolor="y")
+ marker4 = Line2D(range(1), range(1), color="w", marker="o", markerfacecolor="c")
+ marker5 = Line2D(range(1), range(1), color="w", marker="o", markerfacecolor="m")
+ plt.legend(
+ (marker1, marker2, marker3, marker4, marker5),
+ ("cwnd", "ssthresh", "congestion", "recovered", "rxt-timeout"),
+ loc=4,
+ )
+ axes = plt.gca()
+ axes.set_ylim([-20e4, max(cwndy) + 20e4])
+
+ # snd variables
+ plt.subplot(312)
+ plt.title("cc variables")
+ plt.plot(cwndx, d["space"], "g-", markersize=1)
+ plt.plot(cwndx, d["flight"], "b-", markersize=1)
+ plt.plot(cwndx, d["sacked"], "m:", markersize=1)
+ plt.plot(cwndx, d["lost"], "y:", markersize=1)
+ plt.plot(cwndx, d["cc-space"], "k:", markersize=1)
+ plt.plot(cwndx, cwndy, "ro", markersize=2)
+
+ plt.plot(congx, congy, "y^", markersize=10, markerfacecolor="y")
+ plt.plot(rcvrdx, rcvrdy, "c^", markersize=10, markerfacecolor="c")
+ plt.plot(rxttx, rxtty, "m^", markersize=10, markerfacecolor="m")
+
+ # plt.plot(cwndx, d["snd_wnd"], 'ko', markersize=1)
+ plt.legend(
+ (
+ "snd-space",
+ "flight",
+ "sacked",
+ "lost",
+ "cc-space",
+ "cwnd",
+ "congestion",
+ "recovered",
+ "rxt-timeout",
+ ),
+ loc=1,
+ )
+
+ # rto/srrt/rttvar
+ plt.subplot(313)
+ plt.title("rtt")
+ plt.plot(cwndx, d["srtt"], "g-")
+ plt.plot(cwndx, [x / 1000 for x in d["mrtt-us"]], "r-")
+ plt.plot(cwndx, d["rttvar"], "b-")
+ plt.legend(["srtt", "mrtt-us", "rttvar"])
+ axes = plt.gca()
+ # plt.plot(cwndx, rto, 'r-')
+ # axes.set_ylim([0, int(max(rto[2:len(rto)])) + 50])
+
+ # show
+ plt.show()
+
+
+def find_pattern(file_path, session_idx):
is_active_open = 1
listener_pattern = "l\[\d\]"
- if (is_active_open):
- initial_pattern = "\[\d\](\.\d+:\d+\->\.\d+:\d+)\s+open:\s"
+ if is_active_open:
+ initial_pattern = "\[\d\](\.\d+:\d+\->\.\d+:\d+)\s+open:\s"
else:
- initial_pattern = "\[\d\](\.\d+:\d+\->\.\d+:\d+)\s"
+ initial_pattern = "\[\d\](\.\d+:\d+\->\.\d+:\d+)\s"
idx = 0
- f = open(file_path, 'r')
+ f = open(file_path, "r")
for line in f:
- # skip listener lines (server)
- if (re.search(listener_pattern, line) != None):
- continue
- match = re.search(initial_pattern, line)
- if (match == None):
- continue
- if (idx < session_idx):
- idx += 1
- continue
- filter_pattern = str(match.group(1)) + "\s+(.+)"
- print ("pattern is %s" % filter_pattern)
- f.close()
- return filter_pattern
- raise Exception ("Could not find initial pattern")
+ # skip listener lines (server)
+ if re.search(listener_pattern, line) != None:
+ continue
+ match = re.search(initial_pattern, line)
+ if match == None:
+ continue
+ if idx < session_idx:
+ idx += 1
+ continue
+ filter_pattern = str(match.group(1)) + "\s+(.+)"
+ print("pattern is %s" % filter_pattern)
+ f.close()
+ return filter_pattern
+ raise Exception("Could not find initial pattern")
+
def compute_time(min, sec, msec):
- return int(min)*60 + int(sec) + int(msec)/1000.0
+ return int(min) * 60 + int(sec) + int(msec) / 1000.0
+
def run(file_path, session_idx):
filter_sessions = 1
filter_pattern = ""
patterns = {
- "time" : "^\d+:(\d+):(\d+):(\d+):\d+",
- "listener" : "l\[\d\]",
- "cc" : "cwnd (\d+) flight (\d+) space (\d+) ssthresh (\d+) snd_wnd (\d+)",
- "cc-snd" : "cc_space (\d+) sacked (\d+) lost (\d+)",
- "rtt" : "rto (\d+) srtt (\d+) mrtt-us (\d+) rttvar (\d+)",
- "rxtt" : "rxt-timeout",
- "congestion": "congestion",
- "recovered" : "recovered",
+ "time": "^\d+:(\d+):(\d+):(\d+):\d+",
+ "listener": "l\[\d\]",
+ "cc": "cwnd (\d+) flight (\d+) space (\d+) ssthresh (\d+) snd_wnd (\d+)",
+ "cc-snd": "cc_space (\d+) sacked (\d+) lost (\d+)",
+ "rtt": "rto (\d+) srtt (\d+) mrtt-us (\d+) rttvar (\d+)",
+ "rxtt": "rxt-timeout",
+ "congestion": "congestion",
+ "recovered": "recovered",
}
d = {
- "cwnd" : [],
- "space" : [],
- "flight" : [],
- "ssthresh" : [],
- "snd_wnd" : [],
- "cc-space" : [],
- "lost" : [],
- "sacked" : [],
- "rto" : [],
- "srtt" : [],
- "mrtt-us" : [],
- "rttvar" : [],
- "rxtTimeout" : [],
- "congestion" : [],
- "recovered" : [],
+ "cwnd": [],
+ "space": [],
+ "flight": [],
+ "ssthresh": [],
+ "snd_wnd": [],
+ "cc-space": [],
+ "lost": [],
+ "sacked": [],
+ "rto": [],
+ "srtt": [],
+ "mrtt-us": [],
+ "rttvar": [],
+ "rxtTimeout": [],
+ "congestion": [],
+ "recovered": [],
}
- if (filter_sessions):
+ if filter_sessions:
filter_pattern = find_pattern(file_path, session_idx)
- f = open(file_path, 'r')
+ f = open(file_path, "r")
stats_index = 0
start_time = 0
for line in f:
# skip listener lines (server)
- if (re.search(patterns["listener"], line) != None):
+ if re.search(patterns["listener"], line) != None:
continue
# filter sessions
- if (filter_sessions):
+ if filter_sessions:
match = re.search(filter_pattern, line)
- if (match == None):
+ if match == None:
continue
original_line = line
line = match.group(1)
- match = re.search (patterns["time"], original_line)
- if (match == None):
- print "something went wrong! no time!"
- continue
- time = compute_time (match.group(1), match.group(2), match.group(3))
- if (start_time == 0):
- start_time = time
+ match = re.search(patterns["time"], original_line)
+ if match == None:
+ print("something went wrong! no time!")
+ continue
+ time = compute_time(match.group(1), match.group(2), match.group(3))
+ if start_time == 0:
+ start_time = time
time = time - start_time
match = re.search(patterns["cc"], line)
- if (match != None):
- d["cwnd"].append(Point(time, int(match.group(1))))
- d["flight"].append(int(match.group(2)))
- d["space"].append(int(match.group(3)))
- d["ssthresh"].append(int(match.group(4)))
- d["snd_wnd"].append(int(match.group(5)))
- stats_index += 1
- continue
+ if match != None:
+ d["cwnd"].append(Point(time, int(match.group(1))))
+ d["flight"].append(int(match.group(2)))
+ d["space"].append(int(match.group(3)))
+ d["ssthresh"].append(int(match.group(4)))
+ d["snd_wnd"].append(int(match.group(5)))
+ stats_index += 1
+ continue
match = re.search(patterns["cc-snd"], line)
- if (match != None):
- d["cc-space"].append(int(match.group(1)))
- d["sacked"].append(int(match.group(2)))
- d["lost"].append(int(match.group(3)))
+ if match != None:
+ d["cc-space"].append(int(match.group(1)))
+ d["sacked"].append(int(match.group(2)))
+ d["lost"].append(int(match.group(3)))
match = re.search(patterns["rtt"], line)
- if (match != None):
- d["rto"].append(int(match.group(1)))
- d["srtt"].append(int(match.group(2)))
- d["mrtt-us"].append(int(match.group(3)))
- d["rttvar"].append(int(match.group(4)))
- if (stats_index == 0):
- continue
+ if match != None:
+ d["rto"].append(int(match.group(1)))
+ d["srtt"].append(int(match.group(2)))
+ d["mrtt-us"].append(int(match.group(3)))
+ d["rttvar"].append(int(match.group(4)))
+ if stats_index == 0:
+ continue
match = re.search(patterns["rxtt"], line)
- if (match != None):
- d["rxtTimeout"].append(Point(time, d["cwnd"][stats_index - 1].y + 1e4))
- continue
+ if match != None:
+ d["rxtTimeout"].append(Point(time, d["cwnd"][stats_index - 1].y + 1e4))
+ continue
match = re.search(patterns["congestion"], line)
- if (match != None):
- d["congestion"].append(Point(time, d["cwnd"][stats_index - 1].y - 1e4))
- continue
+ if match != None:
+ d["congestion"].append(Point(time, d["cwnd"][stats_index - 1].y - 1e4))
+ continue
match = re.search(patterns["recovered"], line)
- if (match != None):
- d["recovered"].append(Point(time, d["cwnd"][stats_index - 1].y))
- continue
+ if match != None:
+ d["recovered"].append(Point(time, d["cwnd"][stats_index - 1].y))
+ continue
plot_data(d)
+
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Plot tcp cc logs")
- parser.add_argument('-f', action='store', dest='file', required=True,
- help="elog file in txt format")
- parser.add_argument('-s', action='store', dest='session_index', default=0,
- help="session index for which to plot cc logs" )
+ parser.add_argument(
+ "-f", action="store", dest="file", required=True, help="elog file in txt format"
+ )
+ parser.add_argument(
+ "-s",
+ action="store",
+ dest="session_index",
+ default=0,
+ help="session index for which to plot cc logs",
+ )
results = parser.parse_args()
run(results.file, int(results.session_index))
diff --git a/src/scripts/vnet/uri/dummy_app.py b/src/scripts/vnet/uri/dummy_app.py
index d96a378a193..7fab2d766ad 100755
--- a/src/scripts/vnet/uri/dummy_app.py
+++ b/src/scripts/vnet/uri/dummy_app.py
@@ -5,34 +5,41 @@ import sys
import time
import argparse
-# action can be reflect or drop
+# action can be reflect or drop
action = "drop"
test = 0
-def test_data (data, n_rcvd):
- n_read = len (data);
+
+def test_data(data, n_rcvd):
+ n_read = len(data)
for i in range(n_read):
- expected = (n_rcvd + i) & 0xff
- byte_got = ord (data[i])
- if (byte_got != expected):
- print("Difference at byte {}. Expected {} got {}"
- .format(n_rcvd + i, expected, byte_got))
+ expected = (n_rcvd + i) & 0xFF
+ byte_got = ord(data[i])
+ if byte_got != expected:
+ print(
+ "Difference at byte {}. Expected {} got {}".format(
+ n_rcvd + i, expected, byte_got
+ )
+ )
return n_read
-def handle_connection (connection, client_address):
+
+def handle_connection(connection, client_address):
print("Received connection from {}".format(repr(client_address)))
n_rcvd = 0
try:
while True:
data = connection.recv(4096)
if not data:
- break;
- if (test == 1):
- n_rcvd += test_data (data, n_rcvd)
- if (action != "drop"):
+ break
+ if test == 1:
+ n_rcvd += test_data(data, n_rcvd)
+ if action != "drop":
connection.sendall(data)
finally:
connection.close()
+
+
def run_tcp_server(ip, port):
print("Starting TCP server {}:{}".format(repr(ip), repr(port)))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -42,7 +49,9 @@ def run_tcp_server(ip, port):
sock.listen(1)
while True:
connection, client_address = sock.accept()
- handle_connection (connection, client_address)
+ handle_connection(connection, client_address)
+
+
def run_udp_server(ip, port):
print("Starting UDP server {}:{}".format(repr(ip), repr(port)))
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
@@ -51,22 +60,25 @@ def run_udp_server(ip, port):
sock.bind(server_address)
while True:
data, addr = sock.recvfrom(4096)
- if (action != "drop"):
- #snd_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- sock.sendto (data, addr)
+ if action != "drop":
+ # snd_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ sock.sendto(data, addr)
+
def run_server(ip, port, proto):
- if (proto == "tcp"):
+ if proto == "tcp":
run_tcp_server(ip, port)
- elif (proto == "udp"):
+ elif proto == "udp":
run_udp_server(ip, port)
+
def prepare_data(power):
buf = []
- for i in range (0, pow(2, power)):
- buf.append(i & 0xff)
+ for i in range(0, pow(2, power)):
+ buf.append(i & 0xFF)
return bytearray(buf)
+
def run_tcp_client(ip, port):
print("Starting TCP client {}:{}".format(repr(ip), repr(port)))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -75,28 +87,33 @@ def run_tcp_client(ip, port):
data = prepare_data(16)
n_rcvd = 0
- n_sent = len (data)
+ n_sent = len(data)
try:
sock.sendall(data)
timeout = time.time() + 2
while n_rcvd < n_sent and time.time() < timeout:
tmp = sock.recv(1500)
- tmp = bytearray (tmp)
+ tmp = bytearray(tmp)
n_read = len(tmp)
for i in range(n_read):
- if (data[n_rcvd + i] != tmp[i]):
- print("Difference at byte {}. Sent {} got {}"
- .format(n_rcvd + i, data[n_rcvd + i], tmp[i]))
+ if data[n_rcvd + i] != tmp[i]:
+ print(
+ "Difference at byte {}. Sent {} got {}".format(
+ n_rcvd + i, data[n_rcvd + i], tmp[i]
+ )
+ )
n_rcvd += n_read
- if (n_rcvd < n_sent or n_rcvd > n_sent):
+ if n_rcvd < n_sent or n_rcvd > n_sent:
print("Sent {} and got back {}".format(n_sent, n_rcvd))
else:
- print("Got back what we've sent!!");
+ print("Got back what we've sent!!")
finally:
sock.close()
+
+
def run_udp_client(ip, port):
print("Starting UDP client {}:{}".format(repr(ip), repr(port)))
n_packets = 100
@@ -104,38 +121,43 @@ def run_udp_client(ip, port):
server_address = (ip, int(port))
data = prepare_data(10)
try:
- for i in range (0, n_packets):
+ for i in range(0, n_packets):
sock.sendto(data, server_address)
finally:
sock.close()
+
+
def run_client(ip, port, proto):
- if (proto == "tcp"):
+ if proto == "tcp":
run_tcp_client(ip, port)
- elif (proto == "udp"):
+ elif proto == "udp":
run_udp_client(ip, port)
+
+
def run(mode, ip, port, proto):
- if (mode == "server"):
- run_server (ip, port, proto)
- elif (mode == "client"):
- run_client (ip, port, proto)
+ if mode == "server":
+ run_server(ip, port, proto)
+ elif mode == "client":
+ run_client(ip, port, proto)
else:
raise Exception("Unknown mode. Only client and server supported")
+
if __name__ == "__main__":
parser = argparse.ArgumentParser()
- parser.add_argument('-m', action='store', dest='mode')
- parser.add_argument('-i', action='store', dest='ip')
- parser.add_argument('-p', action='store', dest='port')
- parser.add_argument('-proto', action='store', dest='proto')
- parser.add_argument('-a', action='store', dest='action')
- parser.add_argument('-t', action='store', dest='test')
+ parser.add_argument("-m", action="store", dest="mode")
+ parser.add_argument("-i", action="store", dest="ip")
+ parser.add_argument("-p", action="store", dest="port")
+ parser.add_argument("-proto", action="store", dest="proto")
+ parser.add_argument("-a", action="store", dest="action")
+ parser.add_argument("-t", action="store", dest="test")
results = parser.parse_args()
action = results.action
test = results.test
run(results.mode, results.ip, results.port, results.proto)
- #if (len(sys.argv)) < 4:
+ # if (len(sys.argv)) < 4:
# raise Exception("Usage: ./dummy_app <mode> <ip> <port> [<action> <test>]")
- #if (len(sys.argv) == 6):
+ # if (len(sys.argv) == 6):
# action = sys.argv[4]
# test = int(sys.argv[5])
- #run (sys.argv[1], sys.argv[2], int(sys.argv[3]))
+ # run (sys.argv[1], sys.argv[2], int(sys.argv[3]))
diff --git a/src/tools/vppapigen/generate_go.py b/src/tools/vppapigen/generate_go.py
index 1fb53c715e2..fa53bc3dca3 100755
--- a/src/tools/vppapigen/generate_go.py
+++ b/src/tools/vppapigen/generate_go.py
@@ -17,10 +17,12 @@ import sys
def get_go_version(go_root):
# Returns version of the installed Go
- p = subprocess.Popen(["./go", "version"],
- cwd=go_root + "/bin",
- stdout=subprocess.PIPE,
- universal_newlines=True, )
+ p = subprocess.Popen(
+ ["./go", "version"],
+ cwd=go_root + "/bin",
+ stdout=subprocess.PIPE,
+ universal_newlines=True,
+ )
output, _ = p.communicate()
output_fmt = output.replace("go version go", "", 1)
@@ -29,10 +31,12 @@ def get_go_version(go_root):
# Returns version of the installed binary API generator
def get_binapi_gen_version(go_path):
- p = subprocess.Popen(["./binapi-generator", "-version"],
- cwd=go_path + "/bin",
- stdout=subprocess.PIPE,
- universal_newlines=True, )
+ p = subprocess.Popen(
+ ["./binapi-generator", "-version"],
+ cwd=go_path + "/bin",
+ stdout=subprocess.PIPE,
+ universal_newlines=True,
+ )
output, _ = p.communicate()
output_fmt = output.replace("govpp", "", 1)
@@ -45,11 +49,12 @@ def install_golang(go_root):
go_bin = go_root + "/bin/go"
if os.path.exists(go_bin) and os.path.isfile(go_bin):
- print('Go ' + get_go_version(go_root) + ' is already installed')
+ print("Go " + get_go_version(go_root) + " is already installed")
return
- filename = requests.get(
- 'https://golang.org/VERSION?m=text').text + ".linux-amd64.tar.gz"
+ filename = (
+ requests.get("https://golang.org/VERSION?m=text").text + ".linux-amd64.tar.gz"
+ )
url = "https://dl.google.com/go/" + filename
print("Go binary not found, installing the latest version...")
@@ -61,13 +66,13 @@ def install_golang(go_root):
print("Aborting...")
exit(1)
- go_folders = ['src', 'pkg', 'bin']
+ go_folders = ["src", "pkg", "bin"]
for f in go_folders:
if not os.path.exists(os.path.join(go_root, f)):
os.makedirs(os.path.join(go_root, f))
r = requests.get(url)
- with open("/tmp/" + filename, 'wb') as f:
+ with open("/tmp/" + filename, "wb") as f:
f.write(r.content)
go_tf = tarfile.open("/tmp/" + filename)
@@ -78,32 +83,30 @@ def install_golang(go_root):
go_tf.close()
os.remove("/tmp/" + filename)
- print('Go ' + get_go_version(go_root) + ' was installed')
+ print("Go " + get_go_version(go_root) + " was installed")
# Installs latest binary API generator
def install_binapi_gen(c, go_root, go_path):
- os.environ['GO111MODULE'] = "on"
- if (os.path.exists(go_root + "/bin/go") and
- os.path.isfile(go_root + "/bin/go")):
- p = subprocess.Popen(["./go", "get",
- "git.fd.io/govpp.git/cmd/binapi-generator@" + c],
- cwd=go_root + "/bin",
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- universal_newlines=True, )
+ os.environ["GO111MODULE"] = "on"
+ if os.path.exists(go_root + "/bin/go") and os.path.isfile(go_root + "/bin/go"):
+ p = subprocess.Popen(
+ ["./go", "get", "git.fd.io/govpp.git/cmd/binapi-generator@" + c],
+ cwd=go_root + "/bin",
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ universal_newlines=True,
+ )
_, error = p.communicate()
if p.returncode != 0:
- print("binapi generator installation failed: %d %s" %
- (p.returncode, error))
+ print("binapi generator installation failed: %d %s" % (p.returncode, error))
sys.exit(1)
bg_ver = get_binapi_gen_version(go_path)
- print('Installed binary API generator ' + bg_ver)
+ print("Installed binary API generator " + bg_ver)
# Creates generated bindings using GoVPP binapigen to the target folder
-def generate_api(output_dir, vpp_dir, api_list, import_prefix,
- no_source, go_path):
+def generate_api(output_dir, vpp_dir, api_list, import_prefix, no_source, go_path):
json_dir = vpp_dir + "/build-root/install-vpp-native/vpp/share/vpp/api"
if not os.path.exists(json_dir):
@@ -115,19 +118,20 @@ def generate_api(output_dir, vpp_dir, api_list, import_prefix,
if output_dir:
cmd += ["--output-dir=" + output_dir]
if len(api_list):
- print("Following API files were requested by 'GO_API_FILES': " +
- str(api_list))
- print("Note that dependency requirements may generate "
- "additional API files")
+ print("Following API files were requested by 'GO_API_FILES': " + str(api_list))
+ print("Note that dependency requirements may generate " "additional API files")
cmd.append(api_list)
if import_prefix:
cmd.append("-import-prefix=" + import_prefix)
if no_source:
cmd.append("-no-source-path-info")
- p = subprocess.Popen(cmd, cwd=go_path + "/bin",
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- universal_newlines=True, )
+ p = subprocess.Popen(
+ cmd,
+ cwd=go_path + "/bin",
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ universal_newlines=True,
+ )
out = p.communicate()[1]
if p.returncode != 0:
@@ -150,50 +154,70 @@ def main():
vpp_dir = root.parent.parent.parent
parser = argparse.ArgumentParser()
- parser.add_argument("-govpp-commit", "--govpp-commit",
- help="GoVPP commit or branch "
- "(defaults to v0.3.5-45-g671f16c)",
- default="671f16c", # fixed GoVPP version
- type=str)
- parser.add_argument("-output-dir", "--output-dir",
- help="output target directory for generated bindings",
- type=str,
- default=os.path.join(vpp_dir, "vppbinapi"))
- parser.add_argument("-api-files", "--api-files",
- help="api files to generate (without commas)",
- nargs="+",
- type=str,
- default=[])
- parser.add_argument("-import-prefix", "--import-prefix",
- help="prefix imports in the generated go code",
- default="",
- type=str)
- parser.add_argument("-no-source-path-info", "--no-source-path-info",
- help="disable source path info in generated files",
- nargs='?',
- const=True,
- default=True)
+ parser.add_argument(
+ "-govpp-commit",
+ "--govpp-commit",
+ help="GoVPP commit or branch " "(defaults to v0.3.5-45-g671f16c)",
+ default="671f16c", # fixed GoVPP version
+ type=str,
+ )
+ parser.add_argument(
+ "-output-dir",
+ "--output-dir",
+ help="output target directory for generated bindings",
+ type=str,
+ default=os.path.join(vpp_dir, "vppbinapi"),
+ )
+ parser.add_argument(
+ "-api-files",
+ "--api-files",
+ help="api files to generate (without commas)",
+ nargs="+",
+ type=str,
+ default=[],
+ )
+ parser.add_argument(
+ "-import-prefix",
+ "--import-prefix",
+ help="prefix imports in the generated go code",
+ default="",
+ type=str,
+ )
+ parser.add_argument(
+ "-no-source-path-info",
+ "--no-source-path-info",
+ help="disable source path info in generated files",
+ nargs="?",
+ const=True,
+ default=True,
+ )
args = parser.parse_args()
# go specific environment variables
if "GOROOT" in os.environ:
- go_root = os.environ['GOROOT']
+ go_root = os.environ["GOROOT"]
else:
go_binary = shutil.which("go")
if go_binary != "":
go_binary_dir, _ = os.path.split(go_binary)
go_root = os.path.join(go_binary_dir, "..")
else:
- go_root = os.environ['HOME'] + "/.go"
+ go_root = os.environ["HOME"] + "/.go"
if "GOPATH" in os.environ:
- go_path = os.environ['GOPATH']
+ go_path = os.environ["GOPATH"]
else:
- go_path = os.environ['HOME'] + "/go"
+ go_path = os.environ["HOME"] + "/go"
install_golang(go_root)
install_binapi_gen(args.govpp_commit, go_root, go_path)
- generate_api(args.output_dir, str(vpp_dir), args.api_files,
- args.import_prefix, args.no_source_path_info, go_path)
+ generate_api(
+ args.output_dir,
+ str(vpp_dir),
+ args.api_files,
+ args.import_prefix,
+ args.no_source_path_info,
+ go_path,
+ )
if __name__ == "__main__":
diff --git a/src/tools/vppapigen/generate_json.py b/src/tools/vppapigen/generate_json.py
index 288e519edd2..e8041c5a3eb 100755
--- a/src/tools/vppapigen/generate_json.py
+++ b/src/tools/vppapigen/generate_json.py
@@ -16,30 +16,37 @@
import argparse
import pathlib
import subprocess
-BASE_DIR = subprocess.check_output('git rev-parse --show-toplevel',
- shell=True).strip().decode()
+
+BASE_DIR = (
+ subprocess.check_output("git rev-parse --show-toplevel", shell=True)
+ .strip()
+ .decode()
+)
vppapigen_bin = pathlib.Path(
- '%s/src/tools/vppapigen/vppapigen.py' % BASE_DIR).as_posix()
+ "%s/src/tools/vppapigen/vppapigen.py" % BASE_DIR
+).as_posix()
src_dir_depth = 3
output_path = pathlib.Path(
- '%s/build-root/install-vpp-native/vpp/share/vpp/api/' % BASE_DIR)
+ "%s/build-root/install-vpp-native/vpp/share/vpp/api/" % BASE_DIR
+)
output_path_debug = pathlib.Path(
- '%s/build-root/install-vpp_debug-native/vpp/share/vpp/api/' % BASE_DIR)
+ "%s/build-root/install-vpp_debug-native/vpp/share/vpp/api/" % BASE_DIR
+)
output_dir_map = {
- 'plugins': 'plugins',
- 'vlibmemory': 'core',
- 'vnet': 'core',
- 'vlib': 'core',
- 'vpp': 'core',
+ "plugins": "plugins",
+ "vlibmemory": "core",
+ "vnet": "core",
+ "vlib": "core",
+ "vpp": "core",
}
def api_search_globs(src_dir):
globs = []
for g in output_dir_map:
- globs.extend(list(src_dir.glob('%s/**/*.api' % g)))
+ globs.extend(list(src_dir.glob("%s/**/*.api" % g)))
return globs
@@ -51,28 +58,41 @@ def api_files(src_dir):
def vppapigen(vppapigen_bin, output_path, src_dir, src_file):
try:
subprocess.check_output(
- [vppapigen_bin, '--includedir', src_dir.as_posix(),
- '--input', src_file.as_posix(), 'JSON',
- '--output', '%s/%s/%s.json' % (
- output_path,
- output_dir_map[src_file.as_posix().split('/')[
- src_dir_depth + BASE_DIR.count('/') - 1]],
- src_file.name)])
+ [
+ vppapigen_bin,
+ "--includedir",
+ src_dir.as_posix(),
+ "--input",
+ src_file.as_posix(),
+ "JSON",
+ "--output",
+ "%s/%s/%s.json"
+ % (
+ output_path,
+ output_dir_map[
+ src_file.as_posix().split("/")[
+ src_dir_depth + BASE_DIR.count("/") - 1
+ ]
+ ],
+ src_file.name,
+ ),
+ ]
+ )
except KeyError:
- print('src_file: %s' % src_file)
+ print("src_file: %s" % src_file)
raise
def main():
- cliparser = argparse.ArgumentParser(
- description='VPP API JSON definition generator')
- cliparser.add_argument('--srcdir', action='store',
- default='%s/src' % BASE_DIR),
- cliparser.add_argument('--output', action='store',
- help='directory to store files'),
- cliparser.add_argument('--debug-target', action='store_true',
- default=False,
- help="'True' if -debug target"),
+ cliparser = argparse.ArgumentParser(description="VPP API JSON definition generator")
+ cliparser.add_argument("--srcdir", action="store", default="%s/src" % BASE_DIR),
+ cliparser.add_argument("--output", action="store", help="directory to store files"),
+ cliparser.add_argument(
+ "--debug-target",
+ action="store_true",
+ default=False,
+ help="'True' if -debug target",
+ ),
args = cliparser.parse_args()
src_dir = pathlib.Path(args.srcdir)
@@ -86,13 +106,13 @@ def main():
for d in output_dir_map.values():
output_dir.joinpath(d).mkdir(exist_ok=True, parents=True)
- for f in output_dir.glob('**/*.api.json'):
+ for f in output_dir.glob("**/*.api.json"):
f.unlink()
for f in api_files(src_dir):
vppapigen(vppapigen_bin, output_dir, src_dir, f)
- print('json files written to: %s/.' % output_dir)
+ print("json files written to: %s/." % output_dir)
-if __name__ == '__main__':
+if __name__ == "__main__":
main()
diff --git a/src/tools/vppapigen/test_vppapigen.py b/src/tools/vppapigen/test_vppapigen.py
index c454ffc8638..20f6c6da10d 100755
--- a/src/tools/vppapigen/test_vppapigen.py
+++ b/src/tools/vppapigen/test_vppapigen.py
@@ -1,8 +1,7 @@
#!/usr/bin/env python3
import unittest
-from vppapigen import VPPAPI, Option, ParseError, Union, foldup_crcs, \
- global_types
+from vppapigen import VPPAPI, Option, ParseError, Union, foldup_crcs, global_types
import vppapigen
@@ -28,17 +27,17 @@ class TestUnion(unittest.TestCase):
cls.parser = VPPAPI()
def test_union(self):
- test_string = '''
+ test_string = """
union foo_union {
u32 a;
u8 b;
};
- '''
+ """
r = self.parser.parse_string(test_string)
self.assertTrue(isinstance(r[0], Union))
def test_union_vla(self):
- test_string = '''
+ test_string = """
union foo_union_vla {
u32 a;
u8 b[a];
@@ -46,13 +45,13 @@ class TestUnion(unittest.TestCase):
autoreply define foo {
vl_api_foo_union_vla_t v;
};
- '''
+ """
r = self.parser.parse_string(test_string)
self.assertTrue(isinstance(r[0], Union))
self.assertTrue(r[0].vla)
s = self.parser.process(r)
- test_string2 = '''
+ test_string2 = """
union foo_union_vla2 {
u32 a;
u8 b[a];
@@ -61,10 +60,10 @@ class TestUnion(unittest.TestCase):
autoreply define foo2 {
vl_api_foo_union_vla2_t v;
};
- '''
+ """
self.assertRaises(ValueError, self.parser.parse_string, test_string2)
- test_string3 = '''
+ test_string3 = """
union foo_union_vla3 {
u32 a;
u8 b[a];
@@ -73,7 +72,7 @@ class TestUnion(unittest.TestCase):
vl_api_foo_union_vla3_t v;
u32 x;
};
- '''
+ """
self.assertRaises(ValueError, self.parser.parse_string, test_string3)
@@ -83,10 +82,10 @@ class TestTypedef(unittest.TestCase):
cls.parser = VPPAPI()
def test_duplicatetype(self):
- test_string = '''
+ test_string = """
typedef foo1 { u8 dummy; };
typedef foo1 { u8 dummy; };
- '''
+ """
self.assertRaises(KeyError, self.parser.parse_string, test_string)
@@ -96,42 +95,42 @@ class TestDefine(unittest.TestCase):
cls.parser = VPPAPI()
def test_unknowntype(self):
- test_string = 'define foo { foobar foo;};'
+ test_string = "define foo { foobar foo;};"
with self.assertRaises(ParseError) as ctx:
self.parser.parse_string(test_string)
- self.assertIn('Undefined type: foobar', str(ctx.exception))
+ self.assertIn("Undefined type: foobar", str(ctx.exception))
- test_string = 'define { u8 foo;};'
+ test_string = "define { u8 foo;};"
with self.assertRaises(ParseError) as ctx:
self.parser.parse_string(test_string)
def test_flags(self):
- test_string = '''
+ test_string = """
manual_print dont_trace manual_endian define foo { u8 foo; };
define foo_reply {u32 context; i32 retval; };
- '''
+ """
r = self.parser.parse_string(test_string)
self.assertIsNotNone(r)
s = self.parser.process(r)
self.assertIsNotNone(s)
- for d in s['Define']:
- if d.name == 'foo':
+ for d in s["Define"]:
+ if d.name == "foo":
self.assertTrue(d.dont_trace)
self.assertTrue(d.manual_endian)
self.assertTrue(d.manual_print)
self.assertFalse(d.autoreply)
- test_string = '''
+ test_string = """
nonexisting_flag define foo { u8 foo; };
- '''
+ """
with self.assertRaises(ParseError):
self.parser.parse_string(test_string)
def test_options(self):
- test_string = '''
+ test_string = """
define foo { option deprecated; u8 foo; };
define foo_reply {u32 context; i32 retval; };
- '''
+ """
r = self.parser.parse_string(test_string)
self.assertIsNotNone(r)
s = self.parser.process(r)
@@ -144,14 +143,14 @@ class TestService(unittest.TestCase):
cls.parser = VPPAPI()
def test_service(self):
- test_string = '''
+ test_string = """
autoreply define show_version { u8 foo;};
service { rpc show_version returns show_version_reply; };
- '''
+ """
r = self.parser.parse_string(test_string)
s = self.parser.process(r)
- self.assertEqual(s['Service'][0].caller, 'show_version')
- self.assertEqual(s['Service'][0].reply, 'show_version_reply')
+ self.assertEqual(s["Service"][0].caller, "show_version")
+ self.assertEqual(s["Service"][0].reply, "show_version_reply")
def get_crc(apistring, name):
@@ -159,52 +158,52 @@ def get_crc(apistring, name):
parser = vppapigen.VPPAPI()
r = parser.parse_string(apistring)
s = parser.process(r)
- foldup_crcs(s['Define'])
- d = [f for f in s['Define'] if f.name == name]
+ foldup_crcs(s["Define"])
+ d = [f for f in s["Define"] if f.name == name]
return d[0].crc
class TestCRC(unittest.TestCase):
def test_crc(self):
- test_string = '''
+ test_string = """
typedef list { u8 foo; };
autoreply define foo { u8 foo; vl_api_list_t l;};
- '''
- crc = get_crc(test_string, 'foo')
+ """
+ crc = get_crc(test_string, "foo")
# modify underlying type
- test_string = '''
+ test_string = """
typedef list { u8 foo2; };
autoreply define foo { u8 foo; vl_api_list_t l;};
- '''
- crc2 = get_crc(test_string, 'foo')
+ """
+ crc2 = get_crc(test_string, "foo")
self.assertNotEqual(crc, crc2)
# two user-defined types
- test_string = '''
+ test_string = """
typedef address { u8 foo2; };
typedef list { u8 foo2; vl_api_address_t add; };
autoreply define foo { u8 foo; vl_api_list_t l;};
- '''
- crc3 = get_crc(test_string, 'foo')
+ """
+ crc3 = get_crc(test_string, "foo")
- test_string = '''
+ test_string = """
typedef address { u8 foo3; };
typedef list { u8 foo2; vl_api_address_t add; };
autoreply define foo { u8 foo; vl_api_list_t l;};
- '''
- crc4 = get_crc(test_string, 'foo')
+ """
+ crc4 = get_crc(test_string, "foo")
self.assertNotEqual(crc3, crc4)
- test_string = '''
+ test_string = """
typedef address { u8 foo3; };
typedef list { u8 foo2; vl_api_address_t add; u8 foo3; };
autoreply define foo { u8 foo; vl_api_list_t l;};
- '''
- crc5 = get_crc(test_string, 'foo')
+ """
+ crc5 = get_crc(test_string, "foo")
self.assertNotEqual(crc4, crc5)
- test_string = '''
+ test_string = """
typedef ip6_address
{
u8 foo;
@@ -227,11 +226,11 @@ autoreply define sr_policy_add
u32 fib_table;
vl_api_srv6_sid_list_t sids;
};
-'''
+"""
- crc = get_crc(test_string, 'sr_policy_add')
+ crc = get_crc(test_string, "sr_policy_add")
- test_string = '''
+ test_string = """
typedef ip6_address
{
u8 foo;
@@ -253,14 +252,13 @@ autoreply define sr_policy_add
u32 fib_table;
vl_api_srv6_sid_list_t sids;
};
-'''
- crc2 = get_crc(test_string, 'sr_policy_add')
+"""
+ crc2 = get_crc(test_string, "sr_policy_add")
self.assertNotEqual(crc, crc2)
class TestEnum(unittest.TestCase):
-
@classmethod
def setUpClass(cls):
cls.parser = VPPAPI()
@@ -278,8 +276,8 @@ enum tunnel_mode : u8
r = self.parser.parse_string(test_string)
self.assertIsNotNone(r)
s = self.parser.process(r)
- for o in s['types']:
- if o.type == 'Enum':
+ for o in s["types"]:
+ if o.type == "Enum":
self.assertEqual(o.name, "tunnel_mode")
break
else:
@@ -298,8 +296,8 @@ enum virtio_flags {
r = self.parser.parse_string(test_string)
self.assertIsNotNone(r)
s = self.parser.process(r)
- for o in s['types']:
- if o.type == 'Enum':
+ for o in s["types"]:
+ if o.type == "Enum":
self.assertEqual(o.name, "virtio_flags")
break
else:
@@ -307,7 +305,6 @@ enum virtio_flags {
class TestEnumFlag(unittest.TestCase):
-
@classmethod
def setUpClass(cls):
cls.parser = VPPAPI()
@@ -326,8 +323,9 @@ enumflag tunnel_mode_ef : u8
with self.assertRaises(TypeError) as ctx:
r = self.parser.parse_string(test_string)
- self.assertTrue(str(ctx.exception).startswith(
- 'tunnel_mode_ef is not a flag enum.'))
+ self.assertTrue(
+ str(ctx.exception).startswith("tunnel_mode_ef is not a flag enum.")
+ )
def test_enumflag_as_enumflag(self):
test_string = """\
@@ -342,13 +340,13 @@ enumflag virtio_flags_ef {
r = self.parser.parse_string(test_string)
self.assertIsNotNone(r)
s = self.parser.process(r)
- for o in s['types']:
- if o.type == 'EnumFlag':
+ for o in s["types"]:
+ if o.type == "EnumFlag":
self.assertEqual(o.name, "virtio_flags_ef")
break
else:
self.fail()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(verbosity=2)
diff --git a/src/tools/vppapigen/vppapigen.py b/src/tools/vppapigen/vppapigen.py
index 8415c28fb7b..c7bc68180a8 100755
--- a/src/tools/vppapigen/vppapigen.py
+++ b/src/tools/vppapigen/vppapigen.py
@@ -10,9 +10,10 @@ from subprocess import Popen, PIPE
import ply.lex as lex
import ply.yacc as yacc
-assert sys.version_info >= (3, 5), \
- "Not supported Python version: {}".format(sys.version)
-log = logging.getLogger('vppapigen')
+assert sys.version_info >= (3, 5), "Not supported Python version: {}".format(
+ sys.version
+)
+log = logging.getLogger("vppapigen")
# Ensure we don't leave temporary files around
sys.dont_write_bytecode = True
@@ -28,11 +29,10 @@ seen_imports = {}
def global_type_add(name, obj):
- '''Add new type to the dictionary of types '''
- type_name = 'vl_api_' + name + '_t'
+ """Add new type to the dictionary of types"""
+ type_name = "vl_api_" + name + "_t"
if type_name in global_types:
- raise KeyError("Attempted redefinition of {!r} with {!r}.".format(
- name, obj))
+ raise KeyError("Attempted redefinition of {!r} with {!r}.".format(name, obj))
global_types[type_name] = obj
@@ -49,104 +49,104 @@ class VPPAPILexer:
self.filename = filename
reserved = {
- 'service': 'SERVICE',
- 'rpc': 'RPC',
- 'returns': 'RETURNS',
- 'null': 'NULL',
- 'stream': 'STREAM',
- 'events': 'EVENTS',
- 'define': 'DEFINE',
- 'typedef': 'TYPEDEF',
- 'enum': 'ENUM',
- 'enumflag': 'ENUMFLAG',
- 'typeonly': 'TYPEONLY',
- 'manual_print': 'MANUAL_PRINT',
- 'manual_endian': 'MANUAL_ENDIAN',
- 'dont_trace': 'DONT_TRACE',
- 'autoreply': 'AUTOREPLY',
- 'autoendian': 'AUTOENDIAN',
- 'option': 'OPTION',
- 'u8': 'U8',
- 'u16': 'U16',
- 'u32': 'U32',
- 'u64': 'U64',
- 'i8': 'I8',
- 'i16': 'I16',
- 'i32': 'I32',
- 'i64': 'I64',
- 'f64': 'F64',
- 'bool': 'BOOL',
- 'string': 'STRING',
- 'import': 'IMPORT',
- 'true': 'TRUE',
- 'false': 'FALSE',
- 'union': 'UNION',
- 'counters': 'COUNTERS',
- 'paths': 'PATHS',
- 'units': 'UNITS',
- 'severity': 'SEVERITY',
- 'type': 'TYPE',
- 'description': 'DESCRIPTION',
+ "service": "SERVICE",
+ "rpc": "RPC",
+ "returns": "RETURNS",
+ "null": "NULL",
+ "stream": "STREAM",
+ "events": "EVENTS",
+ "define": "DEFINE",
+ "typedef": "TYPEDEF",
+ "enum": "ENUM",
+ "enumflag": "ENUMFLAG",
+ "typeonly": "TYPEONLY",
+ "manual_print": "MANUAL_PRINT",
+ "manual_endian": "MANUAL_ENDIAN",
+ "dont_trace": "DONT_TRACE",
+ "autoreply": "AUTOREPLY",
+ "autoendian": "AUTOENDIAN",
+ "option": "OPTION",
+ "u8": "U8",
+ "u16": "U16",
+ "u32": "U32",
+ "u64": "U64",
+ "i8": "I8",
+ "i16": "I16",
+ "i32": "I32",
+ "i64": "I64",
+ "f64": "F64",
+ "bool": "BOOL",
+ "string": "STRING",
+ "import": "IMPORT",
+ "true": "TRUE",
+ "false": "FALSE",
+ "union": "UNION",
+ "counters": "COUNTERS",
+ "paths": "PATHS",
+ "units": "UNITS",
+ "severity": "SEVERITY",
+ "type": "TYPE",
+ "description": "DESCRIPTION",
}
- tokens = ['STRING_LITERAL',
- 'ID', 'NUM'] + list(reserved.values())
+ tokens = ["STRING_LITERAL", "ID", "NUM"] + list(reserved.values())
- t_ignore_LINE_COMMENT = '//.*'
+ t_ignore_LINE_COMMENT = "//.*"
def t_FALSE(self, t):
- r'false'
+ r"false"
t.value = False
return t
def t_TRUE(self, t):
- r'false'
+ r"false"
t.value = True
return t
def t_NUM(self, t):
- r'0[xX][0-9a-fA-F]+|-?\d+\.?\d*'
- base = 16 if t.value.startswith('0x') else 10
- if '.' in t.value:
+ r"0[xX][0-9a-fA-F]+|-?\d+\.?\d*"
+ base = 16 if t.value.startswith("0x") else 10
+ if "." in t.value:
t.value = float(t.value)
else:
t.value = int(t.value, base)
return t
def t_ID(self, t):
- r'[a-zA-Z_][a-zA-Z_0-9]*'
+ r"[a-zA-Z_][a-zA-Z_0-9]*"
# Check for reserved words
- t.type = VPPAPILexer.reserved.get(t.value, 'ID')
+ t.type = VPPAPILexer.reserved.get(t.value, "ID")
return t
# C string
def t_STRING_LITERAL(self, t):
- r'\"([^\\\n]|(\\.))*?\"'
- t.value = str(t.value).replace("\"", "")
+ r"\"([^\\\n]|(\\.))*?\" "
+ t.value = str(t.value).replace('"', "")
return t
# C or C++ comment (ignore)
def t_comment(self, t):
- r'(/\*(.|\n)*?\*/)|(//.*)'
- t.lexer.lineno += t.value.count('\n')
+ r"(/\*(.|\n)*?\*/)|(//.*)"
+ t.lexer.lineno += t.value.count("\n")
# Error handling rule
def t_error(self, t):
- raise ParseError("Illegal character '{}' ({})"
- "in {}: line {}".format(t.value[0],
- hex(ord(t.value[0])),
- self.filename,
- t.lexer.lineno))
+ raise ParseError(
+ "Illegal character '{}' ({})"
+ "in {}: line {}".format(
+ t.value[0], hex(ord(t.value[0])), self.filename, t.lexer.lineno
+ )
+ )
# Define a rule so we can track line numbers
def t_newline(self, t):
- r'\n+'
+ r"\n+"
t.lexer.lineno += len(t.value)
literals = ":{}[];=.,"
# A string containing ignored characters (spaces and tabs)
- t_ignore = ' \t'
+ t_ignore = " \t"
def vla_mark_length_field(block):
@@ -164,23 +164,25 @@ def vla_is_last_check(name, block):
vla = True
if i + 1 < len(block):
raise ValueError(
- 'VLA field "{}" must be the last field in message "{}"'
- .format(b.fieldname, name))
- elif b.fieldtype.startswith('vl_api_'):
+ 'VLA field "{}" must be the last field in message "{}"'.format(
+ b.fieldname, name
+ )
+ )
+ elif b.fieldtype.startswith("vl_api_"):
if global_types[b.fieldtype].vla:
vla = True
if i + 1 < len(block):
raise ValueError(
'VLA field "{}" must be the last '
- 'field in message "{}"'
- .format(b.fieldname, name))
- elif b.fieldtype == 'string' and b.length == 0:
+ 'field in message "{}"'.format(b.fieldname, name)
+ )
+ elif b.fieldtype == "string" and b.length == 0:
vla = True
if i + 1 < len(block):
raise ValueError(
'VLA field "{}" must be the last '
- 'field in message "{}"'
- .format(b.fieldname, name))
+ 'field in message "{}"'.format(b.fieldname, name)
+ )
return vla
@@ -192,10 +194,9 @@ class Processable:
class Service(Processable):
- type = 'Service'
+ type = "Service"
- def __init__(self, caller, reply, events=None, stream_message=None,
- stream=False):
+ def __init__(self, caller, reply, events=None, stream_message=None, stream=False):
self.caller = caller
self.reply = reply
self.stream = stream
@@ -204,7 +205,7 @@ class Service(Processable):
class Typedef(Processable):
- type = 'Typedef'
+ type = "Typedef"
def __init__(self, name, flags, block):
self.name = name
@@ -214,9 +215,9 @@ class Typedef(Processable):
self.manual_print = False
self.manual_endian = False
for f in flags:
- if f == 'manual_print':
+ if f == "manual_print":
self.manual_print = True
- elif f == 'manual_endian':
+ elif f == "manual_endian":
self.manual_endian = True
global_type_add(name, self)
@@ -224,14 +225,14 @@ class Typedef(Processable):
vla_mark_length_field(self.block)
def process(self, result):
- result['types'].append(self)
+ result["types"].append(self)
def __repr__(self):
return self.name + str(self.flags) + str(self.block)
class Using(Processable):
- type = 'Using'
+ type = "Using"
def __init__(self, name, flags, alias):
self.name = name
@@ -243,16 +244,15 @@ class Using(Processable):
self.manual_print = False
self.manual_endian = False
for f in flags:
- if f == 'manual_print':
+ if f == "manual_print":
self.manual_print = True
- elif f == 'manual_endian':
+ elif f == "manual_endian":
self.manual_endian = True
if isinstance(alias, Array):
- a = {'type': alias.fieldtype,
- 'length': alias.length}
+ a = {"type": alias.fieldtype, "length": alias.length}
else:
- a = {'type': alias.fieldtype}
+ a = {"type": alias.fieldtype}
self.alias = a
self.using = alias
@@ -265,14 +265,14 @@ class Using(Processable):
global_type_add(name, self)
def process(self, result): # -> Dict
- result['types'].append(self)
+ result["types"].append(self)
def __repr__(self):
return self.name + str(self.alias)
class Union(Processable):
- type = 'Union'
+ type = "Union"
def __init__(self, name, flags, block):
self.manual_print = False
@@ -280,9 +280,9 @@ class Union(Processable):
self.name = name
for f in flags:
- if f == 'manual_print':
+ if f == "manual_print":
self.manual_print = True
- elif f == 'manual_endian':
+ elif f == "manual_endian":
self.manual_endian = True
self.block = block
@@ -292,14 +292,14 @@ class Union(Processable):
global_type_add(name, self)
def process(self, result):
- result['types'].append(self)
+ result["types"].append(self)
def __repr__(self):
return str(self.block)
class Define(Processable):
- type = 'Define'
+ type = "Define"
def __init__(self, name, flags, block):
self.name = name
@@ -312,15 +312,15 @@ class Define(Processable):
self.autoendian = 0
self.options = {}
for f in flags:
- if f == 'dont_trace':
+ if f == "dont_trace":
self.dont_trace = True
- elif f == 'manual_print':
+ elif f == "manual_print":
self.manual_print = True
- elif f == 'manual_endian':
+ elif f == "manual_endian":
self.manual_endian = True
- elif f == 'autoreply':
+ elif f == "autoreply":
self.autoreply = True
- elif f == 'autoendian':
+ elif f == "autoendian":
self.autoendian = 1
remove = []
@@ -337,12 +337,11 @@ class Define(Processable):
self.crc = str(block).encode()
def autoreply_block(self, name, parent):
- block = [Field('u32', 'context'),
- Field('i32', 'retval')]
+ block = [Field("u32", "context"), Field("i32", "retval")]
# inherit the parent's options
for k, v in parent.options.items():
block.append(Option(k, v))
- return Define(name + '_reply', [], block)
+ return Define(name + "_reply", [], block)
def process(self, result): # -> Dict
tname = self.__class__.__name__
@@ -355,9 +354,9 @@ class Define(Processable):
class Enum(Processable):
- type = 'Enum'
+ type = "Enum"
- def __init__(self, name, block, enumtype='u32'):
+ def __init__(self, name, block, enumtype="u32"):
self.name = name
self.enumtype = enumtype
self.vla = False
@@ -369,47 +368,50 @@ class Enum(Processable):
bc_set = False
for b in block:
- if 'value' in b:
- count = b['value']
+ if "value" in b:
+ count = b["value"]
else:
count += 1
- block2.append([b['id'], count])
+ block2.append([b["id"], count])
try:
- if b['option']['backwards_compatible']:
+ if b["option"]["backwards_compatible"]:
pass
bc_set = True
except KeyError:
- block3.append([b['id'], count])
+ block3.append([b["id"], count])
if bc_set:
- raise ValueError("Backward compatible enum must "
- "be last {!r} {!r}"
- .format(name, b['id']))
+ raise ValueError(
+ "Backward compatible enum must "
+ "be last {!r} {!r}".format(name, b["id"])
+ )
self.block = block2
self.crc = str(block3).encode()
global_type_add(name, self)
def process(self, result):
- result['types'].append(self)
+ result["types"].append(self)
def __repr__(self):
return self.name + str(self.block)
class EnumFlag(Enum):
- type = 'EnumFlag'
+ type = "EnumFlag"
- def __init__(self, name, block, enumtype='u32'):
+ def __init__(self, name, block, enumtype="u32"):
super(EnumFlag, self).__init__(name, block, enumtype)
for b in self.block:
if bin(b[1])[2:].count("1") > 1:
- raise TypeError("%s is not a flag enum. No element in a "
- "flag enum may have more than a "
- "single bit set." % self.name)
+ raise TypeError(
+ "%s is not a flag enum. No element in a "
+ "flag enum may have more than a "
+ "single bit set." % self.name
+ )
class Import(Processable):
- type = 'Import'
+ type = "Import"
_initialized = False
def __new__(cls, *args, **kwargs):
@@ -440,7 +442,7 @@ class Import(Processable):
class Option(Processable):
- type = 'Option'
+ type = "Option"
def __init__(self, option, value=None):
self.option = option
@@ -458,7 +460,7 @@ class Option(Processable):
class Array(Processable):
- type = 'Array'
+ type = "Array"
def __init__(self, fieldtype, name, length, modern_vla=False):
self.fieldtype = fieldtype
@@ -474,12 +476,11 @@ class Array(Processable):
self.vla = False
def __repr__(self):
- return str([self.fieldtype, self.fieldname, self.length,
- self.lengthfield])
+ return str([self.fieldtype, self.fieldname, self.length, self.lengthfield])
class Field(Processable):
- type = 'Field'
+ type = "Field"
def __init__(self, fieldtype, name, limit=None):
# limit field has been expanded to an options dict.
@@ -487,13 +488,14 @@ class Field(Processable):
self.fieldtype = fieldtype
self.is_lengthfield = False
- if self.fieldtype == 'string':
- raise ValueError("The string type {!r} is an "
- "array type ".format(name))
+ if self.fieldtype == "string":
+ raise ValueError("The string type {!r} is an " "array type ".format(name))
if name in keyword.kwlist:
- raise ValueError("Fieldname {!r} is a python keyword and is not "
- "accessible via the python API. ".format(name))
+ raise ValueError(
+ "Fieldname {!r} is a python keyword and is not "
+ "accessible via the python API. ".format(name)
+ )
self.fieldname = name
self.limit = limit
@@ -502,35 +504,34 @@ class Field(Processable):
class Counter(Processable):
- type = 'Counter'
+ type = "Counter"
def __init__(self, path, counter):
self.name = path
self.block = counter
def process(self, result): # -> Dict
- result['Counters'].append(self)
+ result["Counters"].append(self)
class Paths(Processable):
- type = 'Paths'
+ type = "Paths"
def __init__(self, pathset):
self.paths = pathset
def __repr__(self):
- return "%s(paths=%s)" % (
- self.__class__.__name__, self.paths
- )
+ return "%s(paths=%s)" % (self.__class__.__name__, self.paths)
class Coord:
- """ Coordinates of a syntactic element. Consists of:
- - File name
- - Line number
- - (optional) column number, for the Lexer
+ """Coordinates of a syntactic element. Consists of:
+ - File name
+ - Line number
+ - (optional) column number, for the Lexer
"""
- __slots__ = ('file', 'line', 'column', '__weakref__')
+
+ __slots__ = ("file", "line", "column", "__weakref__")
def __init__(self, file, line, column=None):
self.file = file
@@ -568,49 +569,47 @@ class VPPAPIParser:
self.logger.warning("%s: %s" % (coord, msg))
def _coord(self, lineno, column=None):
- return Coord(
- file=self.filename,
- line=lineno, column=column)
+ return Coord(file=self.filename, line=lineno, column=column)
def _token_coord(self, p, token_idx):
- """ Returns the coordinates for the YaccProduction object 'p' indexed
- with 'token_idx'. The coordinate includes the 'lineno' and
- 'column'. Both follow the lex semantic, starting from 1.
+ """Returns the coordinates for the YaccProduction object 'p' indexed
+ with 'token_idx'. The coordinate includes the 'lineno' and
+ 'column'. Both follow the lex semantic, starting from 1.
"""
- last_cr = p.lexer.lexdata.rfind('\n', 0, p.lexpos(token_idx))
+ last_cr = p.lexer.lexdata.rfind("\n", 0, p.lexpos(token_idx))
if last_cr < 0:
last_cr = -1
- column = (p.lexpos(token_idx) - (last_cr))
+ column = p.lexpos(token_idx) - (last_cr)
return self._coord(p.lineno(token_idx), column)
def p_slist(self, p):
- '''slist : stmt
- | slist stmt'''
+ """slist : stmt
+ | slist stmt"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[2]]
def p_stmt(self, p):
- '''stmt : define
- | typedef
- | option
- | import
- | enum
- | enumflag
- | union
- | service
- | paths
- | counters'''
+ """stmt : define
+ | typedef
+ | option
+ | import
+ | enum
+ | enumflag
+ | union
+ | service
+ | paths
+ | counters"""
p[0] = p[1]
def p_import(self, p):
- '''import : IMPORT STRING_LITERAL ';' '''
+ """import : IMPORT STRING_LITERAL ';'"""
p[0] = Import(p[2], revision=self.revision)
def p_path_elements(self, p):
- '''path_elements : path_element
- | path_elements path_element'''
+ """path_elements : path_element
+ | path_elements path_element"""
if len(p) == 2:
p[0] = p[1]
else:
@@ -620,20 +619,20 @@ class VPPAPIParser:
p[0] = p[1] + [p[2]]
def p_path_element(self, p):
- '''path_element : STRING_LITERAL STRING_LITERAL ';' '''
- p[0] = {'path': p[1], 'counter': p[2]}
+ """path_element : STRING_LITERAL STRING_LITERAL ';'"""
+ p[0] = {"path": p[1], "counter": p[2]}
def p_paths(self, p):
- '''paths : PATHS '{' path_elements '}' ';' '''
+ """paths : PATHS '{' path_elements '}' ';'"""
p[0] = Paths(p[3])
def p_counters(self, p):
- '''counters : COUNTERS ID '{' counter_elements '}' ';' '''
+ """counters : COUNTERS ID '{' counter_elements '}' ';'"""
p[0] = Counter(p[2], p[4])
def p_counter_elements(self, p):
- '''counter_elements : counter_element
- | counter_elements counter_element'''
+ """counter_elements : counter_element
+ | counter_elements counter_element"""
if len(p) == 2:
p[0] = [p[1]]
else:
@@ -643,46 +642,47 @@ class VPPAPIParser:
p[0] = p[1] + [p[2]]
def p_counter_element(self, p):
- '''counter_element : ID '{' counter_statements '}' ';' '''
- p[0] = {**{'name': p[1]}, **p[3]}
+ """counter_element : ID '{' counter_statements '}' ';'"""
+ p[0] = {**{"name": p[1]}, **p[3]}
def p_counter_statements(self, p):
- '''counter_statements : counter_statement
- | counter_statements counter_statement'''
+ """counter_statements : counter_statement
+ | counter_statements counter_statement"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = {**p[1], **p[2]}
def p_counter_statement(self, p):
- '''counter_statement : SEVERITY ID ';'
- | UNITS STRING_LITERAL ';'
- | DESCRIPTION STRING_LITERAL ';'
- | TYPE ID ';' '''
+ """counter_statement : SEVERITY ID ';'
+ | UNITS STRING_LITERAL ';'
+ | DESCRIPTION STRING_LITERAL ';'
+ | TYPE ID ';'"""
p[0] = {p[1]: p[2]}
def p_service(self, p):
- '''service : SERVICE '{' service_statements '}' ';' '''
+ """service : SERVICE '{' service_statements '}' ';'"""
p[0] = p[3]
def p_service_statements(self, p):
- '''service_statements : service_statement
- | service_statements service_statement'''
+ """service_statements : service_statement
+ | service_statements service_statement"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[2]]
def p_service_statement(self, p):
- '''service_statement : RPC ID RETURNS NULL ';'
- | RPC ID RETURNS ID ';'
- | RPC ID RETURNS STREAM ID ';'
- | RPC ID RETURNS ID EVENTS event_list ';' '''
+ """service_statement : RPC ID RETURNS NULL ';'
+ | RPC ID RETURNS ID ';'
+ | RPC ID RETURNS STREAM ID ';'
+ | RPC ID RETURNS ID EVENTS event_list ';'"""
if p[2] == p[4]:
# Verify that caller and reply differ
self._parse_error(
- 'Reply ID ({}) should not be equal to Caller ID'.format(p[2]),
- self._token_coord(p, 1))
+ "Reply ID ({}) should not be equal to Caller ID".format(p[2]),
+ self._token_coord(p, 1),
+ )
if len(p) == 8:
p[0] = Service(p[2], p[4], p[6])
elif len(p) == 7:
@@ -691,280 +691,283 @@ class VPPAPIParser:
p[0] = Service(p[2], p[4])
def p_service_statement2(self, p):
- '''service_statement : RPC ID RETURNS ID STREAM ID ';' '''
+ """service_statement : RPC ID RETURNS ID STREAM ID ';'"""
p[0] = Service(p[2], p[4], stream_message=p[6], stream=True)
def p_event_list(self, p):
- '''event_list : events
- | event_list events '''
+ """event_list : events
+ | event_list events"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[2]]
def p_event(self, p):
- '''events : ID
- | ID ',' '''
+ """events : ID
+ | ID ','"""
p[0] = p[1]
def p_enum(self, p):
- '''enum : ENUM ID '{' enum_statements '}' ';' '''
+ """enum : ENUM ID '{' enum_statements '}' ';'"""
p[0] = Enum(p[2], p[4])
def p_enum_type(self, p):
- ''' enum : ENUM ID ':' enum_size '{' enum_statements '}' ';' '''
+ """enum : ENUM ID ':' enum_size '{' enum_statements '}' ';'"""
if len(p) == 9:
p[0] = Enum(p[2], p[6], enumtype=p[4])
else:
p[0] = Enum(p[2], p[4])
def p_enumflag(self, p):
- '''enumflag : ENUMFLAG ID '{' enum_statements '}' ';' '''
+ """enumflag : ENUMFLAG ID '{' enum_statements '}' ';'"""
p[0] = EnumFlag(p[2], p[4])
def p_enumflag_type(self, p):
- ''' enumflag : ENUMFLAG ID ':' enumflag_size '{' enum_statements '}' ';' ''' # noqa : E502
+ """enumflag : ENUMFLAG ID ':' enumflag_size '{' enum_statements '}' ';'""" # noqa : E502
if len(p) == 9:
p[0] = EnumFlag(p[2], p[6], enumtype=p[4])
else:
p[0] = EnumFlag(p[2], p[4])
def p_enum_size(self, p):
- ''' enum_size : U8
- | U16
- | U32
- | I8
- | I16
- | I32 '''
+ """enum_size : U8
+ | U16
+ | U32
+ | I8
+ | I16
+ | I32"""
p[0] = p[1]
def p_enumflag_size(self, p):
- ''' enumflag_size : U8
- | U16
- | U32 '''
+ """enumflag_size : U8
+ | U16
+ | U32"""
p[0] = p[1]
def p_define(self, p):
- '''define : DEFINE ID '{' block_statements_opt '}' ';' '''
+ """define : DEFINE ID '{' block_statements_opt '}' ';'"""
self.fields = []
p[0] = Define(p[2], [], p[4])
def p_define_flist(self, p):
- '''define : flist DEFINE ID '{' block_statements_opt '}' ';' '''
+ """define : flist DEFINE ID '{' block_statements_opt '}' ';'"""
# Legacy typedef
- if 'typeonly' in p[1]:
- self._parse_error('legacy typedef. use typedef: {} {}[{}];'
- .format(p[1], p[2], p[4]),
- self._token_coord(p, 1))
+ if "typeonly" in p[1]:
+ self._parse_error(
+ "legacy typedef. use typedef: {} {}[{}];".format(p[1], p[2], p[4]),
+ self._token_coord(p, 1),
+ )
else:
p[0] = Define(p[3], p[1], p[5])
def p_flist(self, p):
- '''flist : flag
- | flist flag'''
+ """flist : flag
+ | flist flag"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[2]]
def p_flag(self, p):
- '''flag : MANUAL_PRINT
- | MANUAL_ENDIAN
- | DONT_TRACE
- | TYPEONLY
- | AUTOENDIAN
- | AUTOREPLY'''
+ """flag : MANUAL_PRINT
+ | MANUAL_ENDIAN
+ | DONT_TRACE
+ | TYPEONLY
+ | AUTOENDIAN
+ | AUTOREPLY"""
if len(p) == 1:
return
p[0] = p[1]
def p_typedef(self, p):
- '''typedef : TYPEDEF ID '{' block_statements_opt '}' ';' '''
+ """typedef : TYPEDEF ID '{' block_statements_opt '}' ';'"""
p[0] = Typedef(p[2], [], p[4])
def p_typedef_flist(self, p):
- '''typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';' '''
+ """typedef : flist TYPEDEF ID '{' block_statements_opt '}' ';'"""
p[0] = Typedef(p[3], p[1], p[5])
def p_typedef_alias(self, p):
- '''typedef : TYPEDEF declaration '''
+ """typedef : TYPEDEF declaration"""
p[0] = Using(p[2].fieldname, [], p[2])
def p_typedef_alias_flist(self, p):
- '''typedef : flist TYPEDEF declaration '''
+ """typedef : flist TYPEDEF declaration"""
p[0] = Using(p[3].fieldname, p[1], p[3])
def p_block_statements_opt(self, p):
- '''block_statements_opt : block_statements '''
+ """block_statements_opt : block_statements"""
p[0] = p[1]
def p_block_statements(self, p):
- '''block_statements : block_statement
- | block_statements block_statement'''
+ """block_statements : block_statement
+ | block_statements block_statement"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[2]]
def p_block_statement(self, p):
- '''block_statement : declaration
- | option '''
+ """block_statement : declaration
+ | option"""
p[0] = p[1]
def p_enum_statements(self, p):
- '''enum_statements : enum_statement
- | enum_statements enum_statement'''
+ """enum_statements : enum_statement
+ | enum_statements enum_statement"""
if len(p) == 2:
p[0] = [p[1]]
else:
p[0] = p[1] + [p[2]]
def p_enum_statement(self, p):
- '''enum_statement : ID '=' NUM ','
- | ID ','
- | ID '[' field_options ']' ','
- | ID '=' NUM '[' field_options ']' ',' '''
+ """enum_statement : ID '=' NUM ','
+ | ID ','
+ | ID '[' field_options ']' ','
+ | ID '=' NUM '[' field_options ']' ','"""
if len(p) == 3:
- p[0] = {'id': p[1]}
+ p[0] = {"id": p[1]}
elif len(p) == 5:
- p[0] = {'id': p[1], 'value': p[3]}
+ p[0] = {"id": p[1], "value": p[3]}
elif len(p) == 6:
- p[0] = {'id': p[1], 'option': p[3]}
+ p[0] = {"id": p[1], "option": p[3]}
elif len(p) == 8:
- p[0] = {'id': p[1], 'value': p[3], 'option': p[5]}
+ p[0] = {"id": p[1], "value": p[3], "option": p[5]}
else:
- self._parse_error('ERROR', self._token_coord(p, 1))
+ self._parse_error("ERROR", self._token_coord(p, 1))
def p_field_options(self, p):
- '''field_options : field_option
- | field_options field_option'''
+ """field_options : field_option
+ | field_options field_option"""
if len(p) == 2:
p[0] = p[1]
else:
p[0] = {**p[1], **p[2]}
def p_field_option(self, p):
- '''field_option : ID
- | ID '=' assignee ','
- | ID '=' assignee
+ """field_option : ID
+ | ID '=' assignee ','
+ | ID '=' assignee
- '''
+ """
if len(p) == 2:
p[0] = {p[1]: None}
else:
p[0] = {p[1]: p[3]}
def p_variable_name(self, p):
- '''variable_name : ID
- | TYPE
- | SEVERITY
- | DESCRIPTION
- | COUNTERS
- | PATHS
- '''
+ """variable_name : ID
+ | TYPE
+ | SEVERITY
+ | DESCRIPTION
+ | COUNTERS
+ | PATHS
+ """
p[0] = p[1]
def p_declaration(self, p):
- '''declaration : type_specifier variable_name ';'
- | type_specifier variable_name '[' field_options ']' ';'
- '''
+ """declaration : type_specifier variable_name ';'
+ | type_specifier variable_name '[' field_options ']' ';'
+ """
if len(p) == 7:
p[0] = Field(p[1], p[2], p[4])
elif len(p) == 4:
p[0] = Field(p[1], p[2])
else:
- self._parse_error('ERROR', self._token_coord(p, 1))
+ self._parse_error("ERROR", self._token_coord(p, 1))
self.fields.append(p[2])
def p_declaration_array_vla(self, p):
- '''declaration : type_specifier variable_name '[' ']' ';' '''
+ """declaration : type_specifier variable_name '[' ']' ';'"""
p[0] = Array(p[1], p[2], 0, modern_vla=True)
def p_declaration_array(self, p):
- '''declaration : type_specifier variable_name '[' NUM ']' ';'
- | type_specifier variable_name '[' ID ']' ';' '''
+ """declaration : type_specifier variable_name '[' NUM ']' ';'
+ | type_specifier variable_name '[' ID ']' ';'"""
if len(p) != 7:
return self._parse_error(
- 'array: %s' % p.value,
- self._coord(lineno=p.lineno))
+ "array: %s" % p.value, self._coord(lineno=p.lineno)
+ )
# Make this error later
if type(p[4]) is int and p[4] == 0:
# XXX: Line number is wrong
- self._parse_warning('Old Style VLA: {} {}[{}];'
- .format(p[1], p[2], p[4]),
- self._token_coord(p, 1))
+ self._parse_warning(
+ "Old Style VLA: {} {}[{}];".format(p[1], p[2], p[4]),
+ self._token_coord(p, 1),
+ )
if type(p[4]) is str and p[4] not in self.fields:
# Verify that length field exists
- self._parse_error('Missing length field: {} {}[{}];'
- .format(p[1], p[2], p[4]),
- self._token_coord(p, 1))
+ self._parse_error(
+ "Missing length field: {} {}[{}];".format(p[1], p[2], p[4]),
+ self._token_coord(p, 1),
+ )
p[0] = Array(p[1], p[2], p[4])
def p_option(self, p):
- '''option : OPTION ID '=' assignee ';'
- | OPTION ID ';' '''
+ """option : OPTION ID '=' assignee ';'
+ | OPTION ID ';'"""
if len(p) == 4:
p[0] = Option(p[2])
else:
p[0] = Option(p[2], p[4])
def p_assignee(self, p):
- '''assignee : NUM
- | TRUE
- | FALSE
- | STRING_LITERAL '''
+ """assignee : NUM
+ | TRUE
+ | FALSE
+ | STRING_LITERAL"""
p[0] = p[1]
def p_type_specifier(self, p):
- '''type_specifier : U8
- | U16
- | U32
- | U64
- | I8
- | I16
- | I32
- | I64
- | F64
- | BOOL
- | STRING'''
+ """type_specifier : U8
+ | U16
+ | U32
+ | U64
+ | I8
+ | I16
+ | I32
+ | I64
+ | F64
+ | BOOL
+ | STRING"""
p[0] = p[1]
# Do a second pass later to verify that user defined types are defined
def p_typedef_specifier(self, p):
- '''type_specifier : ID '''
+ """type_specifier : ID"""
if p[1] not in global_types:
- self._parse_error('Undefined type: {}'.format(p[1]),
- self._token_coord(p, 1))
+ self._parse_error(
+ "Undefined type: {}".format(p[1]), self._token_coord(p, 1)
+ )
p[0] = p[1]
def p_union(self, p):
- '''union : UNION ID '{' block_statements_opt '}' ';' '''
+ """union : UNION ID '{' block_statements_opt '}' ';'"""
p[0] = Union(p[2], [], p[4])
def p_union_flist(self, p):
- '''union : flist UNION ID '{' block_statements_opt '}' ';' '''
+ """union : flist UNION ID '{' block_statements_opt '}' ';'"""
p[0] = Union(p[3], p[1], p[5])
# Error rule for syntax errors
def p_error(self, p):
if p:
- self._parse_error(
- 'before: %s' % p.value,
- self._coord(lineno=p.lineno))
+ self._parse_error("before: %s" % p.value, self._coord(lineno=p.lineno))
else:
- self._parse_error('At end of input', self.filename)
-
+ self._parse_error("At end of input", self.filename)
-class VPPAPI():
- def __init__(self, debug=False, filename='', logger=None, revision=None):
+class VPPAPI:
+ def __init__(self, debug=False, filename="", logger=None, revision=None):
self.lexer = lex.lex(module=VPPAPILexer(filename), debug=debug)
- self.parser = yacc.yacc(module=VPPAPIParser(filename, logger,
- revision=revision),
- write_tables=False, debug=debug)
+ self.parser = yacc.yacc(
+ module=VPPAPIParser(filename, logger, revision=revision),
+ write_tables=False,
+ debug=debug,
+ )
self.logger = logger
self.revision = revision
self.filename = filename
@@ -979,38 +982,40 @@ class VPPAPI():
def parse_filename(self, filename, debug=0):
if self.revision:
- git_show = 'git show {}:{}'.format(self.revision, filename)
- proc = Popen(git_show.split(), stdout=PIPE, encoding='utf-8')
+ git_show = "git show {}:{}".format(self.revision, filename)
+ proc = Popen(git_show.split(), stdout=PIPE, encoding="utf-8")
try:
data, errs = proc.communicate()
if proc.returncode != 0:
- print('File not found: {}:{}'
- .format(self.revision, filename), file=sys.stderr)
+ print(
+ "File not found: {}:{}".format(self.revision, filename),
+ file=sys.stderr,
+ )
sys.exit(2)
return self.parse_string(data, debug=debug)
except Exception:
sys.exit(3)
else:
try:
- with open(filename, encoding='utf-8') as fd:
+ with open(filename, encoding="utf-8") as fd:
return self.parse_fd(fd, None)
except FileNotFoundError:
- print('File not found: {}'.format(filename), file=sys.stderr)
+ print("File not found: {}".format(filename), file=sys.stderr)
sys.exit(2)
def process(self, objs):
s = {}
- s['Option'] = {}
- s['Define'] = []
- s['Service'] = []
- s['types'] = []
- s['Import'] = []
- s['Counters'] = []
- s['Paths'] = []
+ s["Option"] = {}
+ s["Define"] = []
+ s["Service"] = []
+ s["types"] = []
+ s["Import"] = []
+ s["Counters"] = []
+ s["Paths"] = []
crc = 0
for o in objs:
try:
- crc = binascii.crc32(o.crc, crc) & 0xffffffff
+ crc = binascii.crc32(o.crc, crc) & 0xFFFFFFFF
except AttributeError:
pass
@@ -1021,82 +1026,84 @@ class VPPAPI():
else:
o.process(s)
- msgs = {d.name: d for d in s['Define']}
- svcs = {s.caller: s for s in s['Service']}
- replies = {s.reply: s for s in s['Service']}
+ msgs = {d.name: d for d in s["Define"]}
+ svcs = {s.caller: s for s in s["Service"]}
+ replies = {s.reply: s for s in s["Service"]}
seen_services = {}
- s['file_crc'] = crc
+ s["file_crc"] = crc
for service in svcs:
if service not in msgs:
raise ValueError(
- 'Service definition refers to unknown message'
- ' definition: {}'.format(service))
- if svcs[service].reply != 'null' and \
- svcs[service].reply not in msgs:
- raise ValueError('Service definition refers to unknown message'
- ' definition in reply: {}'
- .format(svcs[service].reply))
+ "Service definition refers to unknown message"
+ " definition: {}".format(service)
+ )
+ if svcs[service].reply != "null" and svcs[service].reply not in msgs:
+ raise ValueError(
+ "Service definition refers to unknown message"
+ " definition in reply: {}".format(svcs[service].reply)
+ )
if service in replies:
- raise ValueError('Service definition refers to message'
- ' marked as reply: {}'.format(service))
+ raise ValueError(
+ "Service definition refers to message"
+ " marked as reply: {}".format(service)
+ )
for event in svcs[service].events:
if event not in msgs:
- raise ValueError('Service definition refers to unknown '
- 'event: {} in message: {}'
- .format(event, service))
+ raise ValueError(
+ "Service definition refers to unknown "
+ "event: {} in message: {}".format(event, service)
+ )
seen_services[event] = True
# Create services implicitly
for d in msgs:
if d in seen_services:
continue
- if d.endswith('_reply'):
+ if d.endswith("_reply"):
if d[:-6] in svcs:
continue
if d[:-6] not in msgs:
- raise ValueError('{} missing calling message'
- .format(d))
+ raise ValueError("{} missing calling message".format(d))
continue
- if d.endswith('_dump'):
+ if d.endswith("_dump"):
if d in svcs:
continue
- if d[:-5]+'_details' in msgs:
- s['Service'].append(Service(d, d[:-5]+'_details',
- stream=True))
+ if d[:-5] + "_details" in msgs:
+ s["Service"].append(Service(d, d[:-5] + "_details", stream=True))
else:
- raise ValueError('{} missing details message'
- .format(d))
+ raise ValueError("{} missing details message".format(d))
continue
- if d.endswith('_details'):
- if d[:-8]+'_get' in msgs:
- if d[:-8]+'_get' in svcs:
+ if d.endswith("_details"):
+ if d[:-8] + "_get" in msgs:
+ if d[:-8] + "_get" in svcs:
continue
- raise ValueError('{} should be in a stream service'
- .format(d[:-8]+'_get'))
- if d[:-8]+'_dump' in msgs:
+ raise ValueError(
+ "{} should be in a stream service".format(d[:-8] + "_get")
+ )
+ if d[:-8] + "_dump" in msgs:
continue
- raise ValueError('{} missing dump or get message'
- .format(d))
+ raise ValueError("{} missing dump or get message".format(d))
if d in svcs:
continue
- if d+'_reply' in msgs:
- s['Service'].append(Service(d, d+'_reply'))
+ if d + "_reply" in msgs:
+ s["Service"].append(Service(d, d + "_reply"))
else:
raise ValueError(
- '{} missing reply message ({}) or service definition'
- .format(d, d+'_reply'))
+ "{} missing reply message ({}) or service definition".format(
+ d, d + "_reply"
+ )
+ )
return s
def process_imports(self, objs, in_import, result): # -> List
for o in objs:
# Only allow the following object types from imported file
- if in_import and not isinstance(o, (Enum, Import, Typedef,
- Union, Using)):
+ if in_import and not isinstance(o, (Enum, Import, Typedef, Union, Using)):
continue
if isinstance(o, Import):
result.append(o)
@@ -1109,7 +1116,7 @@ class VPPAPI():
# Add message ids to each message.
def add_msg_id(s):
for o in s:
- o.block.insert(0, Field('u16', '_vl_msg_id'))
+ o.block.insert(0, Field("u16", "_vl_msg_id"))
return s
@@ -1129,11 +1136,11 @@ def dirlist_get():
def foldup_blocks(block, crc):
for b in block:
# Look up CRC in user defined types
- if b.fieldtype.startswith('vl_api_'):
+ if b.fieldtype.startswith("vl_api_"):
# Recursively
t = global_types[b.fieldtype]
try:
- crc = binascii.crc32(t.crc, crc) & 0xffffffff
+ crc = binascii.crc32(t.crc, crc) & 0xFFFFFFFF
crc = foldup_blocks(t.block, crc)
except AttributeError:
pass
@@ -1142,34 +1149,43 @@ def foldup_blocks(block, crc):
def foldup_crcs(s):
for f in s:
- f.crc = foldup_blocks(f.block,
- binascii.crc32(f.crc) & 0xffffffff)
+ f.crc = foldup_blocks(f.block, binascii.crc32(f.crc) & 0xFFFFFFFF)
#
# Main
#
def main():
- if sys.version_info < (3, 5,):
- log.exception('vppapigen requires a supported version of python. '
- 'Please use version 3.5 or greater. '
- 'Using %s', sys.version)
+ if sys.version_info < (
+ 3,
+ 5,
+ ):
+ log.exception(
+ "vppapigen requires a supported version of python. "
+ "Please use version 3.5 or greater. "
+ "Using %s",
+ sys.version,
+ )
return 1
- cliparser = argparse.ArgumentParser(description='VPP API generator')
- cliparser.add_argument('--pluginpath', default="")
- cliparser.add_argument('--includedir', action='append')
- cliparser.add_argument('--outputdir', action='store')
- cliparser.add_argument('--input')
- cliparser.add_argument('--output', nargs='?',
- type=argparse.FileType('w', encoding='UTF-8'),
- default=sys.stdout)
-
- cliparser.add_argument('output_module', nargs='?', default='C')
- cliparser.add_argument('--debug', action='store_true')
- cliparser.add_argument('--show-name', nargs=1)
- cliparser.add_argument('--git-revision',
- help="Git revision to use for opening files")
+ cliparser = argparse.ArgumentParser(description="VPP API generator")
+ cliparser.add_argument("--pluginpath", default="")
+ cliparser.add_argument("--includedir", action="append")
+ cliparser.add_argument("--outputdir", action="store")
+ cliparser.add_argument("--input")
+ cliparser.add_argument(
+ "--output",
+ nargs="?",
+ type=argparse.FileType("w", encoding="UTF-8"),
+ default=sys.stdout,
+ )
+
+ cliparser.add_argument("output_module", nargs="?", default="C")
+ cliparser.add_argument("--debug", action="store_true")
+ cliparser.add_argument("--show-name", nargs=1)
+ cliparser.add_argument(
+ "--git-revision", help="Git revision to use for opening files"
+ )
args = cliparser.parse_args()
dirlist_add(args.includedir)
@@ -1182,7 +1198,7 @@ def main():
elif args.input:
filename = args.input
else:
- filename = ''
+ filename = ""
if args.debug:
logging.basicConfig(stream=sys.stdout, level=logging.WARNING)
@@ -1195,36 +1211,34 @@ def main():
from importlib.machinery import SourceFileLoader
# Default path
- pluginpath = ''
+ pluginpath = ""
if not args.pluginpath:
cand = []
cand.append(os.path.dirname(os.path.realpath(__file__)))
- cand.append(os.path.dirname(os.path.realpath(__file__)) +
- '/../share/vpp/')
+ cand.append(os.path.dirname(os.path.realpath(__file__)) + "/../share/vpp/")
for c in cand:
- c += '/'
- if os.path.isfile('{}vppapigen_{}.py'
- .format(c, args.output_module.lower())):
+ c += "/"
+ if os.path.isfile(
+ "{}vppapigen_{}.py".format(c, args.output_module.lower())
+ ):
pluginpath = c
break
else:
- pluginpath = args.pluginpath + '/'
- if pluginpath == '':
- log.exception('Output plugin not found')
+ pluginpath = args.pluginpath + "/"
+ if pluginpath == "":
+ log.exception("Output plugin not found")
return 1
- module_path = '{}vppapigen_{}.py'.format(pluginpath,
- args.output_module.lower())
+ module_path = "{}vppapigen_{}.py".format(pluginpath, args.output_module.lower())
try:
- plugin = SourceFileLoader(args.output_module,
- module_path).load_module()
+ plugin = SourceFileLoader(args.output_module, module_path).load_module()
except Exception as err:
- log.exception('Error importing output plugin: %s, %s',
- module_path, err)
+ log.exception("Error importing output plugin: %s, %s", module_path, err)
return 1
- parser = VPPAPI(debug=args.debug, filename=filename, logger=log,
- revision=args.git_revision)
+ parser = VPPAPI(
+ debug=args.debug, filename=filename, logger=log, revision=args.git_revision
+ )
try:
if not args.input:
@@ -1232,7 +1246,7 @@ def main():
else:
parsed_objects = parser.parse_filename(args.input, log)
except ParseError as e:
- print('Parse error: ', e, file=sys.stderr)
+ print("Parse error: ", e, file=sys.stderr)
sys.exit(1)
# Build a list of objects. Hash of lists.
@@ -1250,32 +1264,33 @@ def main():
else:
s = parser.process(parsed_objects)
imports = parser.process_imports(parsed_objects, False, result)
- s['imported'] = parser.process(imports)
+ s["imported"] = parser.process(imports)
# Add msg_id field
- s['Define'] = add_msg_id(s['Define'])
+ s["Define"] = add_msg_id(s["Define"])
# Fold up CRCs
- foldup_crcs(s['Define'])
+ foldup_crcs(s["Define"])
#
# Debug
if args.debug:
import pprint
+
pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr)
- for t in s['Define']:
+ for t in s["Define"]:
pp.pprint([t.name, t.flags, t.block])
- for t in s['types']:
+ for t in s["types"]:
pp.pprint([t.name, t.block])
result = plugin.run(args, filename, s)
if result:
print(result, file=args.output)
else:
- log.exception('Running plugin failed: %s %s', filename, result)
+ log.exception("Running plugin failed: %s %s", filename, result)
return 1
return 0
-if __name__ == '__main__':
+if __name__ == "__main__":
sys.exit(main())
diff --git a/src/tools/vppapigen/vppapigen_c.py b/src/tools/vppapigen/vppapigen_c.py
index f93e89843a3..fdbb7270a8a 100644
--- a/src/tools/vppapigen/vppapigen_c.py
+++ b/src/tools/vppapigen/vppapigen_c.py
@@ -18,10 +18,10 @@
# binary API format
#
-'''
+"""
This module creates C code for core VPP, VPP plugins and client side VAT and
VAT2 tests.
-'''
+"""
import datetime
import itertools
@@ -35,98 +35,103 @@ process_imports = False
###############################################################################
-class ToJSON():
- '''Class to generate functions converting from VPP binary API to JSON.'''
+class ToJSON:
+ """Class to generate functions converting from VPP binary API to JSON."""
+
_dispatch = {}
- noprint_fields = {'_vl_msg_id': None,
- 'client_index': None,
- 'context': None}
- is_number = {'u8': None,
- 'i8': None,
- 'u16': None,
- 'i16': None,
- 'u32': None,
- 'i32': None,
- 'u64': None,
- 'i64': None,
- 'f64': None,
- }
+ noprint_fields = {"_vl_msg_id": None, "client_index": None, "context": None}
+ is_number = {
+ "u8": None,
+ "i8": None,
+ "u16": None,
+ "i16": None,
+ "u32": None,
+ "i32": None,
+ "u64": None,
+ "i64": None,
+ "f64": None,
+ }
def __init__(self, module, types, defines, imported_types, stream):
self.stream = stream
self.module = module
self.defines = defines
self.types = types
- self.types_hash = {'vl_api_'+d.name+'_t':
- d for d in types + imported_types}
+ self.types_hash = {"vl_api_" + d.name + "_t": d for d in types + imported_types}
self.defines_hash = {d.name: d for d in defines}
def header(self):
- '''Output the top boilerplate.'''
+ """Output the top boilerplate."""
write = self.stream.write
- write('#ifndef included_{}_api_tojson_h\n'.format(self.module))
- write('#define included_{}_api_tojson_h\n'.format(self.module))
- write('#include <vppinfra/cJSON.h>\n\n')
- write('#include <vppinfra/jsonformat.h>\n\n')
- if self.module == 'interface_types':
- write('#define vl_printfun\n')
- write('#include <vnet/interface_types.api.h>\n\n')
+ write("#ifndef included_{}_api_tojson_h\n".format(self.module))
+ write("#define included_{}_api_tojson_h\n".format(self.module))
+ write("#include <vppinfra/cJSON.h>\n\n")
+ write("#include <vppinfra/jsonformat.h>\n\n")
+ if self.module == "interface_types":
+ write("#define vl_printfun\n")
+ write("#include <vnet/interface_types.api.h>\n\n")
def footer(self):
- '''Output the bottom boilerplate.'''
+ """Output the bottom boilerplate."""
write = self.stream.write
- write('#endif\n')
+ write("#endif\n")
def get_base_type(self, t):
vt_type = None
try:
vt = self.types_hash[t]
- if vt.type == 'Using' and 'length' not in vt.alias:
- vt_type = vt.alias['type']
+ if vt.type == "Using" and "length" not in vt.alias:
+ vt_type = vt.alias["type"]
except KeyError:
vt = t
return vt, vt_type
def get_json_func(self, t):
- '''Given the type, returns the function to use to create a
- cJSON object'''
+ """Given the type, returns the function to use to create a
+ cJSON object"""
vt, vt_type = self.get_base_type(t)
if t in self.is_number or vt_type in self.is_number:
- return 'cJSON_AddNumberToObject', '', False
- if t == 'bool':
- return 'cJSON_AddBoolToObject', '', False
+ return "cJSON_AddNumberToObject", "", False
+ if t == "bool":
+ return "cJSON_AddBoolToObject", "", False
# Lookup type name check if it's enum
- if vt.type == 'Enum' or vt.type == 'EnumFlag':
- return '{t}_tojson'.format(t=t), '', True
- return '{t}_tojson'.format(t=t), '&', True
+ if vt.type == "Enum" or vt.type == "EnumFlag":
+ return "{t}_tojson".format(t=t), "", True
+ return "{t}_tojson".format(t=t), "&", True
def get_json_array_func(self, t):
- '''Given a type returns the function to create a cJSON object
- for arrays.'''
+ """Given a type returns the function to create a cJSON object
+ for arrays."""
if t in self.is_number:
- return 'cJSON_CreateNumber', ''
- if t == 'bool':
- return 'cJSON_CreateBool', ''
+ return "cJSON_CreateNumber", ""
+ if t == "bool":
+ return "cJSON_CreateBool", ""
vt, vt_type = self.get_base_type(t)
- if vt.type == 'Enum' or vt.type == 'EnumFlag':
- return '{t}_tojson'.format(t=t), ''
- return '{t}_tojson'.format(t=t), '&'
+ if vt.type == "Enum" or vt.type == "EnumFlag":
+ return "{t}_tojson".format(t=t), ""
+ return "{t}_tojson".format(t=t), "&"
def print_string(self, o):
- '''Create cJSON object from vl_api_string_t'''
+ """Create cJSON object from vl_api_string_t"""
write = self.stream.write
if o.modern_vla:
- write(' vl_api_string_cJSON_AddToObject(o, "{n}", &a->{n});\n'
- .format(n=o.fieldname))
+ write(
+ ' vl_api_string_cJSON_AddToObject(o, "{n}", &a->{n});\n'.format(
+ n=o.fieldname
+ )
+ )
else:
- write(' cJSON_AddStringToObject(o, "{n}", (char *)a->{n});\n'
- .format(n=o.fieldname))
+ write(
+ ' cJSON_AddStringToObject(o, "{n}", (char *)a->{n});\n'.format(
+ n=o.fieldname
+ )
+ )
def print_field(self, o):
- '''Called for every field in a typedef or define.'''
+ """Called for every field in a typedef or define."""
write = self.stream.write
if o.fieldname in self.noprint_fields:
return
@@ -134,19 +139,21 @@ class ToJSON():
f, p, newobj = self.get_json_func(o.fieldtype)
if newobj:
- write(' cJSON_AddItemToObject(o, "{n}", {f}({p}a->{n}));\n'
- .format(f=f, p=p, n=o.fieldname))
+ write(
+ ' cJSON_AddItemToObject(o, "{n}", {f}({p}a->{n}));\n'.format(
+ f=f, p=p, n=o.fieldname
+ )
+ )
else:
- write(' {f}(o, "{n}", {p}a->{n});\n'
- .format(f=f, p=p, n=o.fieldname))
+ write(' {f}(o, "{n}", {p}a->{n});\n'.format(f=f, p=p, n=o.fieldname))
- _dispatch['Field'] = print_field
+ _dispatch["Field"] = print_field
def print_array(self, o):
- '''Converts a VPP API array to cJSON array.'''
+ """Converts a VPP API array to cJSON array."""
write = self.stream.write
- forloop = '''\
+ forloop = """\
{{
int i;
cJSON *array = cJSON_AddArrayToObject(o, "{n}");
@@ -154,237 +161,263 @@ class ToJSON():
cJSON_AddItemToArray(array, {f}({p}a->{n}[i]));
}}
}}
-'''
+"""
- if o.fieldtype == 'string':
+ if o.fieldtype == "string":
self.print_string(o)
return
- lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
- if o.fieldtype == 'u8':
- write(' {\n')
+ lfield = "a->" + o.lengthfield if o.lengthfield else o.length
+ if o.fieldtype == "u8":
+ write(" {\n")
# What is length field doing here?
- write(' u8 *s = format(0, "0x%U", format_hex_bytes, '
- '&a->{n}, {lfield});\n'
- .format(n=o.fieldname, lfield=lfield))
- write(' cJSON_AddStringToObject(o, "{n}", (char *)s);\n'
- .format(n=o.fieldname))
- write(' vec_free(s);\n')
- write(' }\n')
+ write(
+ ' u8 *s = format(0, "0x%U", format_hex_bytes, '
+ "&a->{n}, {lfield});\n".format(n=o.fieldname, lfield=lfield)
+ )
+ write(
+ ' cJSON_AddStringToObject(o, "{n}", (char *)s);\n'.format(
+ n=o.fieldname
+ )
+ )
+ write(" vec_free(s);\n")
+ write(" }\n")
return
f, p = self.get_json_array_func(o.fieldtype)
- write(forloop.format(lfield=lfield,
- t=o.fieldtype,
- n=o.fieldname,
- f=f,
- p=p))
+ write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname, f=f, p=p))
- _dispatch['Array'] = print_array
+ _dispatch["Array"] = print_array
def print_enum(self, o):
- '''Create cJSON object (string) for VPP API enum'''
+ """Create cJSON object (string) for VPP API enum"""
write = self.stream.write
- write('static inline cJSON *vl_api_{name}_t_tojson '
- '(vl_api_{name}_t a) {{\n'.format(name=o.name))
+ write(
+ "static inline cJSON *vl_api_{name}_t_tojson "
+ "(vl_api_{name}_t a) {{\n".format(name=o.name)
+ )
write(" switch(a) {\n")
for b in o.block:
write(" case %s:\n" % b[1])
write(' return cJSON_CreateString("{}");\n'.format(b[0]))
write(' default: return cJSON_CreateString("Invalid ENUM");\n')
- write(' }\n')
- write(' return 0;\n')
- write('}\n')
+ write(" }\n")
+ write(" return 0;\n")
+ write("}\n")
- _dispatch['Enum'] = print_enum
+ _dispatch["Enum"] = print_enum
def print_enum_flag(self, o):
- '''Create cJSON object (string) for VPP API enum'''
+ """Create cJSON object (string) for VPP API enum"""
write = self.stream.write
- write('static inline cJSON *vl_api_{name}_t_tojson '
- '(vl_api_{name}_t a) {{\n'.format(name=o.name))
- write(' cJSON *array = cJSON_CreateArray();\n')
+ write(
+ "static inline cJSON *vl_api_{name}_t_tojson "
+ "(vl_api_{name}_t a) {{\n".format(name=o.name)
+ )
+ write(" cJSON *array = cJSON_CreateArray();\n")
for b in o.block:
if b[1] == 0:
- continue
- write(' if (a & {})\n'.format(b[0]))
+ continue
+ write(" if (a & {})\n".format(b[0]))
write(
- ' cJSON_AddItemToArray(array, cJSON_CreateString("{}"));\n'.format(b[0]))
- write(' return array;\n')
- write('}\n')
+ ' cJSON_AddItemToArray(array, cJSON_CreateString("{}"));\n'.format(
+ b[0]
+ )
+ )
+ write(" return array;\n")
+ write("}\n")
- _dispatch['EnumFlag'] = print_enum_flag
+ _dispatch["EnumFlag"] = print_enum_flag
def print_typedef(self, o):
- '''Create cJSON (dictionary) object from VPP API typedef'''
+ """Create cJSON (dictionary) object from VPP API typedef"""
write = self.stream.write
- write('static inline cJSON *vl_api_{name}_t_tojson '
- '(vl_api_{name}_t *a) {{\n'.format(name=o.name))
- write(' cJSON *o = cJSON_CreateObject();\n')
+ write(
+ "static inline cJSON *vl_api_{name}_t_tojson "
+ "(vl_api_{name}_t *a) {{\n".format(name=o.name)
+ )
+ write(" cJSON *o = cJSON_CreateObject();\n")
for t in o.block:
self._dispatch[t.type](self, t)
- write(' return o;\n')
- write('}\n')
+ write(" return o;\n")
+ write("}\n")
def print_define(self, o):
- '''Create cJSON (dictionary) object from VPP API define'''
+ """Create cJSON (dictionary) object from VPP API define"""
write = self.stream.write
- write('static inline cJSON *vl_api_{name}_t_tojson '
- '(vl_api_{name}_t *a) {{\n'.format(name=o.name))
- write(' cJSON *o = cJSON_CreateObject();\n')
- write(' cJSON_AddStringToObject(o, "_msgname", "{}");\n'
- .format(o.name))
- write(' cJSON_AddStringToObject(o, "_crc", "{crc:08x}");\n'
- .format(crc=o.crc))
+ write(
+ "static inline cJSON *vl_api_{name}_t_tojson "
+ "(vl_api_{name}_t *a) {{\n".format(name=o.name)
+ )
+ write(" cJSON *o = cJSON_CreateObject();\n")
+ write(' cJSON_AddStringToObject(o, "_msgname", "{}");\n'.format(o.name))
+ write(
+ ' cJSON_AddStringToObject(o, "_crc", "{crc:08x}");\n'.format(crc=o.crc)
+ )
for t in o.block:
self._dispatch[t.type](self, t)
- write(' return o;\n')
- write('}\n')
+ write(" return o;\n")
+ write("}\n")
def print_using(self, o):
- '''Create cJSON (dictionary) object from VPP API aliased type'''
+ """Create cJSON (dictionary) object from VPP API aliased type"""
if o.manual_print:
return
write = self.stream.write
- write('static inline cJSON *vl_api_{name}_t_tojson '
- '(vl_api_{name}_t *a) {{\n'.format(name=o.name))
-
- write(' u8 *s = format(0, "%U", format_vl_api_{}_t, a);\n'
- .format(o.name))
- write(' cJSON *o = cJSON_CreateString((char *)s);\n')
- write(' vec_free(s);\n')
- write(' return o;\n')
- write('}\n')
-
- _dispatch['Typedef'] = print_typedef
- _dispatch['Define'] = print_define
- _dispatch['Using'] = print_using
- _dispatch['Union'] = print_typedef
+ write(
+ "static inline cJSON *vl_api_{name}_t_tojson "
+ "(vl_api_{name}_t *a) {{\n".format(name=o.name)
+ )
+
+ write(' u8 *s = format(0, "%U", format_vl_api_{}_t, a);\n'.format(o.name))
+ write(" cJSON *o = cJSON_CreateString((char *)s);\n")
+ write(" vec_free(s);\n")
+ write(" return o;\n")
+ write("}\n")
+
+ _dispatch["Typedef"] = print_typedef
+ _dispatch["Define"] = print_define
+ _dispatch["Using"] = print_using
+ _dispatch["Union"] = print_typedef
def generate_function(self, t):
- '''Main entry point'''
+ """Main entry point"""
write = self.stream.write
if t.manual_print:
- write('/* Manual print {} */\n'.format(t.name))
+ write("/* Manual print {} */\n".format(t.name))
return
self._dispatch[t.type](self, t)
def generate_types(self):
- '''Main entry point'''
+ """Main entry point"""
for t in self.types:
self.generate_function(t)
def generate_defines(self):
- '''Main entry point'''
+ """Main entry point"""
for t in self.defines:
self.generate_function(t)
-class FromJSON():
- '''
+class FromJSON:
+ """
Parse JSON objects into VPP API binary message structures.
- '''
+ """
+
_dispatch = {}
- noprint_fields = {'_vl_msg_id': None,
- 'client_index': None,
- 'context': None}
- is_number = {'u8': None,
- 'i8': None,
- 'u16': None,
- 'i16': None,
- 'u32': None,
- 'i32': None,
- 'u64': None,
- 'i64': None,
- 'f64': None,
- }
+ noprint_fields = {"_vl_msg_id": None, "client_index": None, "context": None}
+ is_number = {
+ "u8": None,
+ "i8": None,
+ "u16": None,
+ "i16": None,
+ "u32": None,
+ "i32": None,
+ "u64": None,
+ "i64": None,
+ "f64": None,
+ }
def __init__(self, module, types, defines, imported_types, stream):
self.stream = stream
self.module = module
self.defines = defines
self.types = types
- self.types_hash = {'vl_api_'+d.name+'_t':
- d for d in types + imported_types}
+ self.types_hash = {"vl_api_" + d.name + "_t": d for d in types + imported_types}
self.defines_hash = {d.name: d for d in defines}
def header(self):
- '''Output the top boilerplate.'''
+ """Output the top boilerplate."""
write = self.stream.write
- write('#ifndef included_{}_api_fromjson_h\n'.format(self.module))
- write('#define included_{}_api_fromjson_h\n'.format(self.module))
- write('#include <vppinfra/cJSON.h>\n\n')
- write('#include <vppinfra/jsonformat.h>\n\n')
+ write("#ifndef included_{}_api_fromjson_h\n".format(self.module))
+ write("#define included_{}_api_fromjson_h\n".format(self.module))
+ write("#include <vppinfra/cJSON.h>\n\n")
+ write("#include <vppinfra/jsonformat.h>\n\n")
write('#pragma GCC diagnostic ignored "-Wunused-label"\n')
def is_base_type(self, t):
- '''Check if a type is one of the VPP API base types'''
+ """Check if a type is one of the VPP API base types"""
if t in self.is_number:
return True
- if t == 'bool':
+ if t == "bool":
return True
return False
def footer(self):
- '''Output the bottom boilerplate.'''
+ """Output the bottom boilerplate."""
write = self.stream.write
- write('#endif\n')
+ write("#endif\n")
def print_string(self, o, toplevel=False):
- '''Convert JSON string to vl_api_string_t'''
+ """Convert JSON string to vl_api_string_t"""
write = self.stream.write
msgvar = "a" if toplevel else "*mp"
msgsize = "l" if toplevel else "*len"
if o.modern_vla:
- write(' char *p = cJSON_GetStringValue(item);\n')
- write(' size_t plen = strlen(p);\n')
- write(' {msgvar} = cJSON_realloc({msgvar}, {msgsize} + plen, {msgsize});\n'
- .format(msgvar=msgvar, msgsize=msgsize))
- write(' if ({msgvar} == 0) goto error;\n'.format(msgvar=msgvar))
- write(' vl_api_c_string_to_api_string(p, (void *){msgvar} + '
- '{msgsize} - sizeof(vl_api_string_t));\n'
- .format(msgvar=msgvar, msgsize=msgsize))
- write(' {msgsize} += plen;\n'.format(msgsize=msgsize))
+ write(" char *p = cJSON_GetStringValue(item);\n")
+ write(" size_t plen = strlen(p);\n")
+ write(
+ " {msgvar} = cJSON_realloc({msgvar}, {msgsize} + plen, {msgsize});\n".format(
+ msgvar=msgvar, msgsize=msgsize
+ )
+ )
+ write(" if ({msgvar} == 0) goto error;\n".format(msgvar=msgvar))
+ write(
+ " vl_api_c_string_to_api_string(p, (void *){msgvar} + "
+ "{msgsize} - sizeof(vl_api_string_t));\n".format(
+ msgvar=msgvar, msgsize=msgsize
+ )
+ )
+ write(" {msgsize} += plen;\n".format(msgsize=msgsize))
else:
- write(' strncpy_s((char *)a->{n}, sizeof(a->{n}), '
- 'cJSON_GetStringValue(item), sizeof(a->{n}) - 1);\n'
- .format(n=o.fieldname))
+ write(
+ " strncpy_s((char *)a->{n}, sizeof(a->{n}), "
+ "cJSON_GetStringValue(item), sizeof(a->{n}) - 1);\n".format(
+ n=o.fieldname
+ )
+ )
def print_field(self, o, toplevel=False):
- '''Called for every field in a typedef or define.'''
+ """Called for every field in a typedef or define."""
write = self.stream.write
if o.fieldname in self.noprint_fields:
return
is_bt = self.is_base_type(o.fieldtype)
- t = 'vl_api_{}'.format(o.fieldtype) if is_bt else o.fieldtype
+ t = "vl_api_{}".format(o.fieldtype) if is_bt else o.fieldtype
msgvar = "(void **)&a" if toplevel else "mp"
msgsize = "&l" if toplevel else "len"
if is_bt:
- write(' vl_api_{t}_fromjson(item, &a->{n});\n'
- .format(t=o.fieldtype, n=o.fieldname))
+ write(
+ " vl_api_{t}_fromjson(item, &a->{n});\n".format(
+ t=o.fieldtype, n=o.fieldname
+ )
+ )
else:
- write(' if ({t}_fromjson({msgvar}, '
- '{msgsize}, item, &a->{n}) < 0) goto error;\n'
- .format(t=t, n=o.fieldname, msgvar=msgvar, msgsize=msgsize))
+ write(
+ " if ({t}_fromjson({msgvar}, "
+ "{msgsize}, item, &a->{n}) < 0) goto error;\n".format(
+ t=t, n=o.fieldname, msgvar=msgvar, msgsize=msgsize
+ )
+ )
- _dispatch['Field'] = print_field
+ _dispatch["Field"] = print_field
def print_array(self, o, toplevel=False):
- '''Convert JSON array to VPP API array'''
+ """Convert JSON array to VPP API array"""
write = self.stream.write
- forloop = '''\
+ forloop = """\
{{
int i;
cJSON *array = cJSON_GetObjectItem(o, "{n}");
@@ -395,8 +428,8 @@ class FromJSON():
{call}
}}
}}
-'''
- forloop_vla = '''\
+"""
+ forloop_vla = """\
{{
int i;
cJSON *array = cJSON_GetObjectItem(o, "{n}");
@@ -410,271 +443,296 @@ class FromJSON():
{call}
}}
}}
-'''
+"""
t = o.fieldtype
- if o.fieldtype == 'string':
+ if o.fieldtype == "string":
self.print_string(o, toplevel)
return
- lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
+ lfield = "a->" + o.lengthfield if o.lengthfield else o.length
msgvar = "(void **)&a" if toplevel else "mp"
realloc = "a" if toplevel else "*mp"
msgsize = "l" if toplevel else "*len"
- if o.fieldtype == 'u8':
+ if o.fieldtype == "u8":
if o.lengthfield:
- write(' s = u8string_fromjson(o, "{}");\n'
- .format(o.fieldname))
- write(' if (!s) goto error;\n')
- write(' {} = vec_len(s);\n'.format(lfield))
-
- write(' {realloc} = cJSON_realloc({realloc}, {msgsize} + '
- 'vec_len(s), {msgsize});\n'.format(msgvar=msgvar, msgsize=msgsize, realloc=realloc))
- write(' memcpy((void *){realloc} + {msgsize}, s, '
- 'vec_len(s));\n'.format(realloc=realloc, msgsize=msgsize))
- write(' {msgsize} += vec_len(s);\n'.format(msgsize=msgsize))
-
- write(' vec_free(s);\n')
+ write(' s = u8string_fromjson(o, "{}");\n'.format(o.fieldname))
+ write(" if (!s) goto error;\n")
+ write(" {} = vec_len(s);\n".format(lfield))
+
+ write(
+ " {realloc} = cJSON_realloc({realloc}, {msgsize} + "
+ "vec_len(s), {msgsize});\n".format(
+ msgvar=msgvar, msgsize=msgsize, realloc=realloc
+ )
+ )
+ write(
+ " memcpy((void *){realloc} + {msgsize}, s, "
+ "vec_len(s));\n".format(realloc=realloc, msgsize=msgsize)
+ )
+ write(" {msgsize} += vec_len(s);\n".format(msgsize=msgsize))
+
+ write(" vec_free(s);\n")
else:
- write(' if (u8string_fromjson2(o, "{n}", a->{n}) < 0) goto error;\n'
- .format(n=o.fieldname))
+ write(
+ ' if (u8string_fromjson2(o, "{n}", a->{n}) < 0) goto error;\n'.format(
+ n=o.fieldname
+ )
+ )
return
is_bt = self.is_base_type(o.fieldtype)
if o.lengthfield:
if is_bt:
- call = ('vl_api_{t}_fromjson(e, &d[i]);'
- .format(t=o.fieldtype))
+ call = "vl_api_{t}_fromjson(e, &d[i]);".format(t=o.fieldtype)
else:
- call = ('if ({t}_fromjson({msgvar}, len, e, &d[i]) < 0) goto error; '
- .format(t=o.fieldtype, msgvar=msgvar))
- write(forloop_vla.format(lfield=lfield,
- t=o.fieldtype,
- n=o.fieldname,
- call=call,
- realloc=realloc,
- msgsize=msgsize))
+ call = "if ({t}_fromjson({msgvar}, len, e, &d[i]) < 0) goto error; ".format(
+ t=o.fieldtype, msgvar=msgvar
+ )
+ write(
+ forloop_vla.format(
+ lfield=lfield,
+ t=o.fieldtype,
+ n=o.fieldname,
+ call=call,
+ realloc=realloc,
+ msgsize=msgsize,
+ )
+ )
else:
if is_bt:
- call = ('vl_api_{t}_fromjson(e, &a->{n}[i]);'
- .format(t=t, n=o.fieldname))
+ call = "vl_api_{t}_fromjson(e, &a->{n}[i]);".format(t=t, n=o.fieldname)
else:
- call = ('if ({}_fromjson({}, len, e, &a->{}[i]) < 0) goto error;'
- .format(t, msgvar, o.fieldname))
- write(forloop.format(lfield=lfield,
- t=t,
- n=o.fieldname,
- call=call,
- msgvar=msgvar,
- realloc=realloc,
- msgsize=msgsize))
-
- _dispatch['Array'] = print_array
+ call = "if ({}_fromjson({}, len, e, &a->{}[i]) < 0) goto error;".format(
+ t, msgvar, o.fieldname
+ )
+ write(
+ forloop.format(
+ lfield=lfield,
+ t=t,
+ n=o.fieldname,
+ call=call,
+ msgvar=msgvar,
+ realloc=realloc,
+ msgsize=msgsize,
+ )
+ )
+
+ _dispatch["Array"] = print_array
def print_enum(self, o):
- '''Convert to JSON enum(string) to VPP API enum (int)'''
+ """Convert to JSON enum(string) to VPP API enum (int)"""
write = self.stream.write
- write('static inline int vl_api_{n}_t_fromjson'
- '(void **mp, int *len, cJSON *o, vl_api_{n}_t *a) {{\n'
- .format(n=o.name))
- write(' char *p = cJSON_GetStringValue(o);\n')
+ write(
+ "static inline int vl_api_{n}_t_fromjson"
+ "(void **mp, int *len, cJSON *o, vl_api_{n}_t *a) {{\n".format(n=o.name)
+ )
+ write(" char *p = cJSON_GetStringValue(o);\n")
for b in o.block:
- write(' if (strcmp(p, "{}") == 0) {{*a = {}; return 0;}}\n'
- .format(b[0], b[1]))
- write(' *a = 0;\n')
- write(' return -1;\n')
- write('}\n')
+ write(
+ ' if (strcmp(p, "{}") == 0) {{*a = {}; return 0;}}\n'.format(
+ b[0], b[1]
+ )
+ )
+ write(" *a = 0;\n")
+ write(" return -1;\n")
+ write("}\n")
- _dispatch['Enum'] = print_enum
+ _dispatch["Enum"] = print_enum
def print_enum_flag(self, o):
- '''Convert to JSON enum(string) to VPP API enum (int)'''
+ """Convert to JSON enum(string) to VPP API enum (int)"""
write = self.stream.write
- write('static inline int vl_api_{n}_t_fromjson '
- '(void **mp, int *len, cJSON *o, vl_api_{n}_t *a) {{\n'
- .format(n=o.name))
- write(' int i;\n')
- write(' *a = 0;\n')
- write(' for (i = 0; i < cJSON_GetArraySize(o); i++) {\n')
- write(' cJSON *e = cJSON_GetArrayItem(o, i);\n')
- write(' char *p = cJSON_GetStringValue(e);\n')
- write(' if (!p) return -1;\n')
+ write(
+ "static inline int vl_api_{n}_t_fromjson "
+ "(void **mp, int *len, cJSON *o, vl_api_{n}_t *a) {{\n".format(n=o.name)
+ )
+ write(" int i;\n")
+ write(" *a = 0;\n")
+ write(" for (i = 0; i < cJSON_GetArraySize(o); i++) {\n")
+ write(" cJSON *e = cJSON_GetArrayItem(o, i);\n")
+ write(" char *p = cJSON_GetStringValue(e);\n")
+ write(" if (!p) return -1;\n")
for b in o.block:
- write(' if (strcmp(p, "{}") == 0) *a |= {};\n'
- .format(b[0], b[1]))
- write(' }\n')
- write(' return 0;\n')
- write('}\n')
+ write(' if (strcmp(p, "{}") == 0) *a |= {};\n'.format(b[0], b[1]))
+ write(" }\n")
+ write(" return 0;\n")
+ write("}\n")
- _dispatch['EnumFlag'] = print_enum_flag
+ _dispatch["EnumFlag"] = print_enum_flag
def print_typedef(self, o):
- '''Convert from JSON object to VPP API binary representation'''
+ """Convert from JSON object to VPP API binary representation"""
write = self.stream.write
- write('static inline int vl_api_{name}_t_fromjson (void **mp, '
- 'int *len, cJSON *o, vl_api_{name}_t *a) {{\n'
- .format(name=o.name))
- write(' cJSON *item __attribute__ ((unused));\n')
- write(' u8 *s __attribute__ ((unused));\n')
+ write(
+ "static inline int vl_api_{name}_t_fromjson (void **mp, "
+ "int *len, cJSON *o, vl_api_{name}_t *a) {{\n".format(name=o.name)
+ )
+ write(" cJSON *item __attribute__ ((unused));\n")
+ write(" u8 *s __attribute__ ((unused));\n")
for t in o.block:
- if t.type == 'Field' and t.is_lengthfield:
+ if t.type == "Field" and t.is_lengthfield:
continue
- write('\n item = cJSON_GetObjectItem(o, "{}");\n'
- .format(t.fieldname))
- write(' if (!item) goto error;\n')
+ write('\n item = cJSON_GetObjectItem(o, "{}");\n'.format(t.fieldname))
+ write(" if (!item) goto error;\n")
self._dispatch[t.type](self, t)
- write('\n return 0;\n')
- write('\n error:\n')
- write(' return -1;\n')
- write('}\n')
+ write("\n return 0;\n")
+ write("\n error:\n")
+ write(" return -1;\n")
+ write("}\n")
def print_union(self, o):
- '''Convert JSON object to VPP API binary union'''
+ """Convert JSON object to VPP API binary union"""
write = self.stream.write
- write('static inline int vl_api_{name}_t_fromjson (void **mp, '
- 'int *len, cJSON *o, vl_api_{name}_t *a) {{\n'
- .format(name=o.name))
- write(' cJSON *item __attribute__ ((unused));\n')
- write(' u8 *s __attribute__ ((unused));\n')
+ write(
+ "static inline int vl_api_{name}_t_fromjson (void **mp, "
+ "int *len, cJSON *o, vl_api_{name}_t *a) {{\n".format(name=o.name)
+ )
+ write(" cJSON *item __attribute__ ((unused));\n")
+ write(" u8 *s __attribute__ ((unused));\n")
for t in o.block:
- if t.type == 'Field' and t.is_lengthfield:
+ if t.type == "Field" and t.is_lengthfield:
continue
- write(' item = cJSON_GetObjectItem(o, "{}");\n'
- .format(t.fieldname))
- write(' if (item) {\n')
+ write(' item = cJSON_GetObjectItem(o, "{}");\n'.format(t.fieldname))
+ write(" if (item) {\n")
self._dispatch[t.type](self, t)
- write(' };\n')
- write('\n return 0;\n')
- write('\n error:\n')
- write(' return -1;\n')
- write('}\n')
+ write(" };\n")
+ write("\n return 0;\n")
+ write("\n error:\n")
+ write(" return -1;\n")
+ write("}\n")
def print_define(self, o):
- '''Convert JSON object to VPP API message'''
+ """Convert JSON object to VPP API message"""
write = self.stream.write
error = 0
- write('static inline vl_api_{name}_t *vl_api_{name}_t_fromjson '
- '(cJSON *o, int *len) {{\n'.format(name=o.name))
- write(' cJSON *item __attribute__ ((unused));\n')
- write(' u8 *s __attribute__ ((unused));\n')
- write(' int l = sizeof(vl_api_{}_t);\n'.format(o.name))
- write(' vl_api_{}_t *a = cJSON_malloc(l);\n'.format(o.name))
- write('\n')
+ write(
+ "static inline vl_api_{name}_t *vl_api_{name}_t_fromjson "
+ "(cJSON *o, int *len) {{\n".format(name=o.name)
+ )
+ write(" cJSON *item __attribute__ ((unused));\n")
+ write(" u8 *s __attribute__ ((unused));\n")
+ write(" int l = sizeof(vl_api_{}_t);\n".format(o.name))
+ write(" vl_api_{}_t *a = cJSON_malloc(l);\n".format(o.name))
+ write("\n")
for t in o.block:
if t.fieldname in self.noprint_fields:
continue
- if t.type == 'Field' and t.is_lengthfield:
+ if t.type == "Field" and t.is_lengthfield:
continue
- write(' item = cJSON_GetObjectItem(o, "{}");\n'
- .format(t.fieldname))
- write(' if (!item) goto error;\n')
+ write(' item = cJSON_GetObjectItem(o, "{}");\n'.format(t.fieldname))
+ write(" if (!item) goto error;\n")
error += 1
self._dispatch[t.type](self, t, toplevel=True)
- write('\n')
+ write("\n")
- write(' *len = l;\n')
- write(' return a;\n')
+ write(" *len = l;\n")
+ write(" return a;\n")
if error:
- write('\n error:\n')
- write(' cJSON_free(a);\n')
- write(' return 0;\n')
- write('}\n')
+ write("\n error:\n")
+ write(" cJSON_free(a);\n")
+ write(" return 0;\n")
+ write("}\n")
def print_using(self, o):
- '''Convert JSON field to VPP type alias'''
+ """Convert JSON field to VPP type alias"""
write = self.stream.write
if o.manual_print:
return
t = o.using
- write('static inline int vl_api_{name}_t_fromjson (void **mp, '
- 'int *len, cJSON *o, vl_api_{name}_t *a) {{\n'
- .format(name=o.name))
- if 'length' in o.alias:
- if t.fieldtype != 'u8':
- raise ValueError("Error in processing type {} for {}"
- .format(t.fieldtype, o.name))
- write(' vl_api_u8_string_fromjson(o, (u8 *)a, {});\n'
- .format(o.alias['length']))
+ write(
+ "static inline int vl_api_{name}_t_fromjson (void **mp, "
+ "int *len, cJSON *o, vl_api_{name}_t *a) {{\n".format(name=o.name)
+ )
+ if "length" in o.alias:
+ if t.fieldtype != "u8":
+ raise ValueError(
+ "Error in processing type {} for {}".format(t.fieldtype, o.name)
+ )
+ write(
+ " vl_api_u8_string_fromjson(o, (u8 *)a, {});\n".format(
+ o.alias["length"]
+ )
+ )
else:
- write(' vl_api_{t}_fromjson(o, ({t} *)a);\n'
- .format(t=t.fieldtype))
+ write(" vl_api_{t}_fromjson(o, ({t} *)a);\n".format(t=t.fieldtype))
- write(' return 0;\n')
- write('}\n')
+ write(" return 0;\n")
+ write("}\n")
- _dispatch['Typedef'] = print_typedef
- _dispatch['Define'] = print_define
- _dispatch['Using'] = print_using
- _dispatch['Union'] = print_union
+ _dispatch["Typedef"] = print_typedef
+ _dispatch["Define"] = print_define
+ _dispatch["Using"] = print_using
+ _dispatch["Union"] = print_union
def generate_function(self, t):
- '''Main entry point'''
+ """Main entry point"""
write = self.stream.write
if t.manual_print:
- write('/* Manual print {} */\n'.format(t.name))
+ write("/* Manual print {} */\n".format(t.name))
return
self._dispatch[t.type](self, t)
def generate_types(self):
- '''Main entry point'''
+ """Main entry point"""
for t in self.types:
self.generate_function(t)
def generate_defines(self):
- '''Main entry point'''
+ """Main entry point"""
for t in self.defines:
self.generate_function(t)
def generate_tojson(s, modulename, stream):
- '''Generate all functions to convert from API to JSON'''
+ """Generate all functions to convert from API to JSON"""
write = stream.write
- write('/* Imported API files */\n')
- for i in s['Import']:
- f = i.filename.replace('plugins/', '')
- write('#include <{}_tojson.h>\n'.format(f))
+ write("/* Imported API files */\n")
+ for i in s["Import"]:
+ f = i.filename.replace("plugins/", "")
+ write("#include <{}_tojson.h>\n".format(f))
- pp = ToJSON(modulename, s['types'], s['Define'], s['imported']['types'],
- stream)
+ pp = ToJSON(modulename, s["types"], s["Define"], s["imported"]["types"], stream)
pp.header()
pp.generate_types()
pp.generate_defines()
pp.footer()
- return ''
+ return ""
def generate_fromjson(s, modulename, stream):
- '''Generate all functions to convert from JSON to API'''
+ """Generate all functions to convert from JSON to API"""
write = stream.write
- write('/* Imported API files */\n')
- for i in s['Import']:
- f = i.filename.replace('plugins/', '')
- write('#include <{}_fromjson.h>\n'.format(f))
+ write("/* Imported API files */\n")
+ for i in s["Import"]:
+ f = i.filename.replace("plugins/", "")
+ write("#include <{}_fromjson.h>\n".format(f))
- pp = FromJSON(modulename, s['types'], s['Define'], s['imported']['types'],
- stream)
+ pp = FromJSON(modulename, s["types"], s["Define"], s["imported"]["types"], stream)
pp.header()
pp.generate_types()
pp.generate_defines()
pp.footer()
- return ''
+ return ""
+
###############################################################################
DATESTRING = datetime.datetime.utcfromtimestamp(
- int(os.environ.get('SOURCE_DATE_EPOCH', time.time())))
-TOP_BOILERPLATE = '''\
+ int(os.environ.get("SOURCE_DATE_EPOCH", time.time()))
+)
+TOP_BOILERPLATE = """\
/*
* VLIB API definitions {datestring}
* Input file: {input_filename}
@@ -693,45 +751,47 @@ TOP_BOILERPLATE = '''\
#endif
#define VL_API_PACKED(x) x __attribute__ ((packed))
-'''
+"""
-BOTTOM_BOILERPLATE = '''\
+BOTTOM_BOILERPLATE = """\
/****** API CRC (whole file) *****/
#ifdef vl_api_version
vl_api_version({input_filename}, {file_crc:#08x})
#endif
-'''
+"""
def msg_ids(s):
- '''Generate macro to map API message id to handler'''
- output = '''\
+ """Generate macro to map API message id to handler"""
+ output = """\
/****** Message ID / handler enum ******/
#ifdef vl_msg_id
-'''
+"""
- for t in s['Define']:
- output += "vl_msg_id(VL_API_%s, vl_api_%s_t_handler)\n" % \
- (t.name.upper(), t.name)
+ for t in s["Define"]:
+ output += "vl_msg_id(VL_API_%s, vl_api_%s_t_handler)\n" % (
+ t.name.upper(),
+ t.name,
+ )
output += "#endif"
return output
def msg_names(s):
- '''Generate calls to name mapping macro'''
- output = '''\
+ """Generate calls to name mapping macro"""
+ output = """\
/****** Message names ******/
#ifdef vl_msg_name
-'''
+"""
- for t in s['Define']:
+ for t in s["Define"]:
dont_trace = 0 if t.dont_trace else 1
output += "vl_msg_name(vl_api_%s_t, %d)\n" % (t.name, dont_trace)
output += "#endif"
@@ -740,190 +800,215 @@ def msg_names(s):
def msg_name_crc_list(s, suffix):
- '''Generate list of names to CRC mappings'''
- output = '''\
+ """Generate list of names to CRC mappings"""
+ output = """\
/****** Message name, crc list ******/
#ifdef vl_msg_name_crc_list
-'''
+"""
output += "#define foreach_vl_msg_name_crc_%s " % suffix
- for t in s['Define']:
- output += "\\\n_(VL_API_%s, %s, %08x) " % \
- (t.name.upper(), t.name, t.crc)
+ for t in s["Define"]:
+ output += "\\\n_(VL_API_%s, %s, %08x) " % (t.name.upper(), t.name, t.crc)
output += "\n#endif"
return output
def api2c(fieldtype):
- '''Map between API type names and internal VPP type names'''
- mappingtable = {'string': 'vl_api_string_t', }
+ """Map between API type names and internal VPP type names"""
+ mappingtable = {
+ "string": "vl_api_string_t",
+ }
if fieldtype in mappingtable:
return mappingtable[fieldtype]
return fieldtype
def typedefs(filename):
- '''Include in the main files to the types file'''
- output = '''\
+ """Include in the main files to the types file"""
+ output = """\
/****** Typedefs ******/
#ifdef vl_typedefs
#include "{include}.api_types.h"
#endif
-'''.format(include=filename)
+""".format(
+ include=filename
+ )
return output
-FORMAT_STRINGS = {'u8': '%u',
- 'bool': '%u',
- 'i8': '%d',
- 'u16': '%u',
- 'i16': '%d',
- 'u32': '%u',
- 'i32': '%ld',
- 'u64': '%llu',
- 'i64': '%lld',
- 'f64': '%.2f'}
+FORMAT_STRINGS = {
+ "u8": "%u",
+ "bool": "%u",
+ "i8": "%d",
+ "u16": "%u",
+ "i16": "%d",
+ "u32": "%u",
+ "i32": "%ld",
+ "u64": "%llu",
+ "i64": "%lld",
+ "f64": "%.2f",
+}
+
+class Printfun:
+ """Functions for pretty printing VPP API messages"""
-class Printfun():
- '''Functions for pretty printing VPP API messages'''
_dispatch = {}
- noprint_fields = {'_vl_msg_id': None,
- 'client_index': None,
- 'context': None}
+ noprint_fields = {"_vl_msg_id": None, "client_index": None, "context": None}
def __init__(self, stream):
self.stream = stream
@staticmethod
def print_string(o, stream):
- '''Pretty print a vl_api_string_t'''
+ """Pretty print a vl_api_string_t"""
write = stream.write
if o.modern_vla:
- write(' if (vl_api_string_len(&a->{f}) > 0) {{\n'
- .format(f=o.fieldname))
- write(' s = format(s, "\\n%U{f}: %U", '
- 'format_white_space, indent, '
- 'vl_api_format_string, (&a->{f}));\n'.format(f=o.fieldname))
- write(' } else {\n')
- write(' s = format(s, "\\n%U{f}:", '
- 'format_white_space, indent);\n'.format(f=o.fieldname))
- write(' }\n')
+ write(" if (vl_api_string_len(&a->{f}) > 0) {{\n".format(f=o.fieldname))
+ write(
+ ' s = format(s, "\\n%U{f}: %U", '
+ "format_white_space, indent, "
+ "vl_api_format_string, (&a->{f}));\n".format(f=o.fieldname)
+ )
+ write(" } else {\n")
+ write(
+ ' s = format(s, "\\n%U{f}:", '
+ "format_white_space, indent);\n".format(f=o.fieldname)
+ )
+ write(" }\n")
else:
- write(' s = format(s, "\\n%U{f}: %s", '
- 'format_white_space, indent, a->{f});\n'
- .format(f=o.fieldname))
+ write(
+ ' s = format(s, "\\n%U{f}: %s", '
+ "format_white_space, indent, a->{f});\n".format(f=o.fieldname)
+ )
def print_field(self, o, stream):
- '''Pretty print API field'''
+ """Pretty print API field"""
write = stream.write
if o.fieldname in self.noprint_fields:
return
if o.fieldtype in FORMAT_STRINGS:
f = FORMAT_STRINGS[o.fieldtype]
- write(' s = format(s, "\\n%U{n}: {f}", '
- 'format_white_space, indent, a->{n});\n'
- .format(n=o.fieldname, f=f))
+ write(
+ ' s = format(s, "\\n%U{n}: {f}", '
+ "format_white_space, indent, a->{n});\n".format(n=o.fieldname, f=f)
+ )
else:
- write(' s = format(s, "\\n%U{n}: %U", '
- 'format_white_space, indent, '
- 'format_{t}, &a->{n}, indent);\n'
- .format(n=o.fieldname, t=o.fieldtype))
+ write(
+ ' s = format(s, "\\n%U{n}: %U", '
+ "format_white_space, indent, "
+ "format_{t}, &a->{n}, indent);\n".format(n=o.fieldname, t=o.fieldtype)
+ )
- _dispatch['Field'] = print_field
+ _dispatch["Field"] = print_field
def print_array(self, o, stream):
- '''Pretty print API array'''
+ """Pretty print API array"""
write = stream.write
- forloop = '''\
+ forloop = """\
for (i = 0; i < {lfield}; i++) {{
s = format(s, "\\n%U{n}: %U",
format_white_space, indent, format_{t}, &a->{n}[i], indent);
}}
-'''
+"""
- forloop_format = '''\
+ forloop_format = """\
for (i = 0; i < {lfield}; i++) {{
s = format(s, "\\n%U{n}: {t}",
format_white_space, indent, a->{n}[i]);
}}
-'''
+"""
- if o.fieldtype == 'string':
+ if o.fieldtype == "string":
self.print_string(o, stream)
return
- if o.fieldtype == 'u8':
+ if o.fieldtype == "u8":
if o.lengthfield:
- write(' s = format(s, "\\n%U{n}: %U", format_white_space, '
- 'indent, format_hex_bytes, a->{n}, a->{lfield});\n'
- .format(n=o.fieldname, lfield=o.lengthfield))
+ write(
+ ' s = format(s, "\\n%U{n}: %U", format_white_space, '
+ "indent, format_hex_bytes, a->{n}, a->{lfield});\n".format(
+ n=o.fieldname, lfield=o.lengthfield
+ )
+ )
else:
- write(' s = format(s, "\\n%U{n}: %U", format_white_space, '
- 'indent, format_hex_bytes, a, {lfield});\n'
- .format(n=o.fieldname, lfield=o.length))
+ write(
+ ' s = format(s, "\\n%U{n}: %U", format_white_space, '
+ "indent, format_hex_bytes, a, {lfield});\n".format(
+ n=o.fieldname, lfield=o.length
+ )
+ )
return
- lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
+ lfield = "a->" + o.lengthfield if o.lengthfield else o.length
if o.fieldtype in FORMAT_STRINGS:
- write(forloop_format.format(lfield=lfield,
- t=FORMAT_STRINGS[o.fieldtype],
- n=o.fieldname))
+ write(
+ forloop_format.format(
+ lfield=lfield, t=FORMAT_STRINGS[o.fieldtype], n=o.fieldname
+ )
+ )
else:
write(forloop.format(lfield=lfield, t=o.fieldtype, n=o.fieldname))
- _dispatch['Array'] = print_array
+ _dispatch["Array"] = print_array
@staticmethod
def print_alias(k, v, stream):
- '''Pretty print type alias'''
+ """Pretty print type alias"""
write = stream.write
- if ('length' in v.alias and v.alias['length'] and
- v.alias['type'] == 'u8'):
- write(' return format(s, "%U", format_hex_bytes, a, {});\n'
- .format(v.alias['length']))
- elif v.alias['type'] in FORMAT_STRINGS:
- write(' return format(s, "{}", *a);\n'
- .format(FORMAT_STRINGS[v.alias['type']]))
+ if "length" in v.alias and v.alias["length"] and v.alias["type"] == "u8":
+ write(
+ ' return format(s, "%U", format_hex_bytes, a, {});\n'.format(
+ v.alias["length"]
+ )
+ )
+ elif v.alias["type"] in FORMAT_STRINGS:
+ write(
+ ' return format(s, "{}", *a);\n'.format(
+ FORMAT_STRINGS[v.alias["type"]]
+ )
+ )
else:
- write(' return format(s, "{} (print not implemented)");\n'
- .format(k))
+ write(' return format(s, "{} (print not implemented)");\n'.format(k))
@staticmethod
def print_enum(o, stream):
- '''Pretty print API enum'''
+ """Pretty print API enum"""
write = stream.write
write(" switch(*a) {\n")
for b in o:
write(" case %s:\n" % b[1])
write(' return format(s, "{}");\n'.format(b[0]))
- write(' }\n')
+ write(" }\n")
- _dispatch['Enum'] = print_enum
- _dispatch['EnumFlag'] = print_enum
+ _dispatch["Enum"] = print_enum
+ _dispatch["EnumFlag"] = print_enum
def print_obj(self, o, stream):
- '''Entry point'''
+ """Entry point"""
write = stream.write
if o.type in self._dispatch:
self._dispatch[o.type](self, o, stream)
else:
- write(' s = format(s, "\\n{} {} {} (print not implemented");\n'
- .format(o.type, o.fieldtype, o.fieldname))
+ write(
+ ' s = format(s, "\\n{} {} {} (print not implemented");\n'.format(
+ o.type, o.fieldtype, o.fieldname
+ )
+ )
def printfun(objs, stream, modulename):
- '''Main entry point for pretty print function generation'''
+ """Main entry point for pretty print function generation"""
write = stream.write
- h = '''\
+ h = """\
/****** Print functions *****/
#ifdef vl_printfun
#ifndef included_{module}_printfun
@@ -940,15 +1025,15 @@ def printfun(objs, stream, modulename):
#include "{module}.api_tojson.h"
#include "{module}.api_fromjson.h"
-'''
+"""
- signature = '''\
+ signature = """\
static inline void *vl_api_{name}_t_print{suffix} (vl_api_{name}_t *a, void *handle)
{{
u8 *s = 0;
u32 indent __attribute__((unused)) = 2;
int i __attribute__((unused));
-'''
+"""
h = h.format(module=modulename)
write(h)
@@ -958,171 +1043,172 @@ static inline void *vl_api_{name}_t_print{suffix} (vl_api_{name}_t *a, void *han
if t.manual_print:
write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
continue
- write(signature.format(name=t.name, suffix=''))
- write(' /* Message definition: vl_api_{}_t: */\n'.format(t.name))
- write(" s = format(s, \"vl_api_%s_t:\");\n" % t.name)
+ write(signature.format(name=t.name, suffix=""))
+ write(" /* Message definition: vl_api_{}_t: */\n".format(t.name))
+ write(' s = format(s, "vl_api_%s_t:");\n' % t.name)
for o in t.block:
pp.print_obj(o, stream)
- write(' vec_add1(s, 0);\n')
- write(' vl_print (handle, (char *)s);\n')
- write(' vec_free (s);\n')
- write(' return handle;\n')
- write('}\n\n')
-
- write(signature.format(name=t.name, suffix='_json'))
- write(' cJSON * o = vl_api_{}_t_tojson(a);\n'.format(t.name))
- write(' (void)s;\n')
- write(' char *out = cJSON_Print(o);\n')
- write(' vl_print(handle, out);\n')
- write(' cJSON_Delete(o);\n')
- write(' cJSON_free(out);\n')
- write(' return handle;\n')
- write('}\n\n')
+ write(" vec_add1(s, 0);\n")
+ write(" vl_print (handle, (char *)s);\n")
+ write(" vec_free (s);\n")
+ write(" return handle;\n")
+ write("}\n\n")
+
+ write(signature.format(name=t.name, suffix="_json"))
+ write(" cJSON * o = vl_api_{}_t_tojson(a);\n".format(t.name))
+ write(" (void)s;\n")
+ write(" char *out = cJSON_Print(o);\n")
+ write(" vl_print(handle, out);\n")
+ write(" cJSON_Delete(o);\n")
+ write(" cJSON_free(out);\n")
+ write(" return handle;\n")
+ write("}\n\n")
write("\n#endif")
write("\n#endif /* vl_printfun */\n")
- return ''
+ return ""
def printfun_types(objs, stream, modulename):
- '''Pretty print API types'''
+ """Pretty print API types"""
write = stream.write
pp = Printfun(stream)
- h = '''\
+ h = """\
/****** Print functions *****/
#ifdef vl_printfun
#ifndef included_{module}_printfun_types
#define included_{module}_printfun_types
-'''
+"""
h = h.format(module=modulename)
write(h)
- signature = '''\
+ signature = """\
static inline u8 *format_vl_api_{name}_t (u8 *s, va_list * args)
{{
vl_api_{name}_t *a = va_arg (*args, vl_api_{name}_t *);
u32 indent __attribute__((unused)) = va_arg (*args, u32);
int i __attribute__((unused));
indent += 2;
-'''
+"""
for t in objs:
- if t.__class__.__name__ == 'Enum' or t.__class__.__name__ == 'EnumFlag':
+ if t.__class__.__name__ == "Enum" or t.__class__.__name__ == "EnumFlag":
write(signature.format(name=t.name))
pp.print_enum(t.block, stream)
- write(' return s;\n')
- write('}\n\n')
+ write(" return s;\n")
+ write("}\n\n")
continue
if t.manual_print:
write("/***** manual: vl_api_%s_t_print *****/\n\n" % t.name)
continue
- if t.__class__.__name__ == 'Using':
+ if t.__class__.__name__ == "Using":
write(signature.format(name=t.name))
pp.print_alias(t.name, t, stream)
- write('}\n\n')
+ write("}\n\n")
continue
write(signature.format(name=t.name))
for o in t.block:
pp.print_obj(o, stream)
- write(' return s;\n')
- write('}\n\n')
+ write(" return s;\n")
+ write("}\n\n")
write("\n#endif")
write("\n#endif /* vl_printfun_types */\n")
def generate_imports(imports):
- '''Add #include matching the API import statements'''
- output = '/* Imported API files */\n'
- output += '#ifndef vl_api_version\n'
+ """Add #include matching the API import statements"""
+ output = "/* Imported API files */\n"
+ output += "#ifndef vl_api_version\n"
for i in imports:
- s = i.filename.replace('plugins/', '')
- output += '#include <{}.h>\n'.format(s)
- output += '#endif\n'
+ s = i.filename.replace("plugins/", "")
+ output += "#include <{}.h>\n".format(s)
+ output += "#endif\n"
return output
ENDIAN_STRINGS = {
- 'u16': 'clib_net_to_host_u16',
- 'u32': 'clib_net_to_host_u32',
- 'u64': 'clib_net_to_host_u64',
- 'i16': 'clib_net_to_host_i16',
- 'i32': 'clib_net_to_host_i32',
- 'i64': 'clib_net_to_host_i64',
- 'f64': 'clib_net_to_host_f64',
+ "u16": "clib_net_to_host_u16",
+ "u32": "clib_net_to_host_u32",
+ "u64": "clib_net_to_host_u64",
+ "i16": "clib_net_to_host_i16",
+ "i32": "clib_net_to_host_i32",
+ "i64": "clib_net_to_host_i64",
+ "f64": "clib_net_to_host_f64",
}
def endianfun_array(o):
- '''Generate endian functions for arrays'''
- forloop = '''\
+ """Generate endian functions for arrays"""
+ forloop = """\
for (i = 0; i < {length}; i++) {{
a->{name}[i] = {format}(a->{name}[i]);
}}
-'''
+"""
- forloop_format = '''\
+ forloop_format = """\
for (i = 0; i < {length}; i++) {{
{type}_endian(&a->{name}[i]);
}}
-'''
+"""
- output = ''
- if o.fieldtype == 'u8' or o.fieldtype == 'string' or o.fieldtype == 'bool':
- output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
+ output = ""
+ if o.fieldtype == "u8" or o.fieldtype == "string" or o.fieldtype == "bool":
+ output += " /* a->{n} = a->{n} (no-op) */\n".format(n=o.fieldname)
else:
- lfield = 'a->' + o.lengthfield if o.lengthfield else o.length
+ lfield = "a->" + o.lengthfield if o.lengthfield else o.length
if o.fieldtype in ENDIAN_STRINGS:
- output += (forloop
- .format(length=lfield,
- format=ENDIAN_STRINGS[o.fieldtype],
- name=o.fieldname))
+ output += forloop.format(
+ length=lfield, format=ENDIAN_STRINGS[o.fieldtype], name=o.fieldname
+ )
else:
- output += (forloop_format
- .format(length=lfield, type=o.fieldtype,
- name=o.fieldname))
+ output += forloop_format.format(
+ length=lfield, type=o.fieldtype, name=o.fieldname
+ )
return output
-NO_ENDIAN_CONVERSION = {'client_index': None}
+NO_ENDIAN_CONVERSION = {"client_index": None}
def endianfun_obj(o):
- '''Generate endian conversion function for type'''
- output = ''
- if o.type == 'Array':
+ """Generate endian conversion function for type"""
+ output = ""
+ if o.type == "Array":
return endianfun_array(o)
- if o.type != 'Field':
- output += (' s = format(s, "\\n{} {} {} (print not implemented");\n'
- .format(o.type, o.fieldtype, o.fieldname))
+ if o.type != "Field":
+ output += ' s = format(s, "\\n{} {} {} (print not implemented");\n'.format(
+ o.type, o.fieldtype, o.fieldname
+ )
return output
if o.fieldname in NO_ENDIAN_CONVERSION:
- output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
+ output += " /* a->{n} = a->{n} (no-op) */\n".format(n=o.fieldname)
return output
if o.fieldtype in ENDIAN_STRINGS:
- output += (' a->{name} = {format}(a->{name});\n'
- .format(name=o.fieldname,
- format=ENDIAN_STRINGS[o.fieldtype]))
- elif o.fieldtype.startswith('vl_api_'):
- output += (' {type}_endian(&a->{name});\n'
- .format(type=o.fieldtype, name=o.fieldname))
+ output += " a->{name} = {format}(a->{name});\n".format(
+ name=o.fieldname, format=ENDIAN_STRINGS[o.fieldtype]
+ )
+ elif o.fieldtype.startswith("vl_api_"):
+ output += " {type}_endian(&a->{name});\n".format(
+ type=o.fieldtype, name=o.fieldname
+ )
else:
- output += ' /* a->{n} = a->{n} (no-op) */\n'.format(n=o.fieldname)
+ output += " /* a->{n} = a->{n} (no-op) */\n".format(n=o.fieldname)
return output
def endianfun(objs, modulename):
- '''Main entry point for endian function generation'''
- output = '''\
+ """Main entry point for endian function generation"""
+ output = """\
/****** Endian swap functions *****/\n\
#ifdef vl_endianfun
@@ -1136,51 +1222,50 @@ def endianfun(objs, modulename):
#define clib_net_to_host_uword clib_net_to_host_u32
#endif
-'''
+"""
output = output.format(module=modulename)
- signature = '''\
+ signature = """\
static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
{{
int i __attribute__((unused));
-'''
+"""
for t in objs:
- if t.__class__.__name__ == 'Enum' or t.__class__.__name__ == 'EnumFlag':
+ if t.__class__.__name__ == "Enum" or t.__class__.__name__ == "EnumFlag":
output += signature.format(name=t.name)
if t.enumtype in ENDIAN_STRINGS:
- output += (' *a = {}(*a);\n'
- .format(ENDIAN_STRINGS[t.enumtype]))
+ output += " *a = {}(*a);\n".format(ENDIAN_STRINGS[t.enumtype])
else:
- output += (' /* a->{name} = a->{name} (no-op) */\n'
- .format(name=t.name))
+ output += " /* a->{name} = a->{name} (no-op) */\n".format(
+ name=t.name
+ )
- output += '}\n\n'
+ output += "}\n\n"
continue
if t.manual_endian:
output += "/***** manual: vl_api_%s_t_endian *****/\n\n" % t.name
continue
- if t.__class__.__name__ == 'Using':
+ if t.__class__.__name__ == "Using":
output += signature.format(name=t.name)
- if ('length' in t.alias and t.alias['length'] and
- t.alias['type'] == 'u8'):
- output += (' /* a->{name} = a->{name} (no-op) */\n'
- .format(name=t.name))
- elif t.alias['type'] in FORMAT_STRINGS:
- output += (' *a = {}(*a);\n'
- .format(ENDIAN_STRINGS[t.alias['type']]))
+ if "length" in t.alias and t.alias["length"] and t.alias["type"] == "u8":
+ output += " /* a->{name} = a->{name} (no-op) */\n".format(
+ name=t.name
+ )
+ elif t.alias["type"] in FORMAT_STRINGS:
+ output += " *a = {}(*a);\n".format(ENDIAN_STRINGS[t.alias["type"]])
else:
- output += ' /* Not Implemented yet {} */'.format(t.name)
- output += '}\n\n'
+ output += " /* Not Implemented yet {} */".format(t.name)
+ output += "}\n\n"
continue
output += signature.format(name=t.name)
for o in t.block:
output += endianfun_obj(o)
- output += '}\n\n'
+ output += "}\n\n"
output += "\n#endif"
output += "\n#endif /* vl_endianfun */\n\n"
@@ -1189,32 +1274,32 @@ static inline void vl_api_{name}_t_endian (vl_api_{name}_t *a)
def calc_size_fun(objs, modulename):
- '''Main entry point for calculate size function generation'''
- output = '''\
+ """Main entry point for calculate size function generation"""
+ output = """\
/****** Calculate size functions *****/\n\
#ifdef vl_calcsizefun
#ifndef included_{module}_calcsizefun
#define included_{module}_calcsizefun
-'''
+"""
output = output.format(module=modulename)
- signature = '''\
+ signature = """\
/* calculate message size of message in network byte order */
static inline uword vl_api_{name}_t_calc_size (vl_api_{name}_t *a)
{{
-'''
+"""
for o in objs:
tname = o.__class__.__name__
output += signature.format(name=o.name)
output += f" return sizeof(*a)"
- if tname == 'Using':
- if 'length' in o.alias:
+ if tname == "Using":
+ if "length" in o.alias:
try:
- tmp = int(o.alias['length'])
+ tmp = int(o.alias["length"])
if tmp == 0:
raise (f"Unexpected length '0' for alias {o}")
except:
@@ -1224,36 +1309,44 @@ static inline uword vl_api_{name}_t_calc_size (vl_api_{name}_t *a)
print(dir(o.alias))
print(o.alias)
raise
- elif tname == 'Enum' or tname == 'EnumFlag':
+ elif tname == "Enum" or tname == "EnumFlag":
pass
else:
for b in o.block:
- if b.type == 'Option':
+ if b.type == "Option":
continue
- elif b.type == 'Field':
- if b.fieldtype.startswith('vl_api_'):
+ elif b.type == "Field":
+ if b.fieldtype.startswith("vl_api_"):
output += f" - sizeof(a->{b.fieldname})"
output += f" + {b.fieldtype}_calc_size(&a->{b.fieldname})"
- elif b.type == 'Array':
+ elif b.type == "Array":
if b.lengthfield:
- m = list(filter(lambda x: x.fieldname == b.lengthfield, o.block))
+ m = list(
+ filter(lambda x: x.fieldname == b.lengthfield, o.block)
+ )
if len(m) != 1:
- raise Exception(f"Expected 1 match for field '{b.lengthfield}', got '{m}'")
+ raise Exception(
+ f"Expected 1 match for field '{b.lengthfield}', got '{m}'"
+ )
lf = m[0]
if lf.fieldtype in ENDIAN_STRINGS:
output += f" + {ENDIAN_STRINGS[lf.fieldtype]}(a->{b.lengthfield}) * sizeof(a->{b.fieldname}[0])"
elif lf.fieldtype == "u8":
- output += f" + a->{b.lengthfield} * sizeof(a->{b.fieldname}[0])"
+ output += (
+ f" + a->{b.lengthfield} * sizeof(a->{b.fieldname}[0])"
+ )
else:
- raise Exception(f"Don't know how to endian swap {lf.fieldtype}")
+ raise Exception(
+ f"Don't know how to endian swap {lf.fieldtype}"
+ )
else:
# Fixed length strings decay to nul terminated u8
- if b.fieldtype == 'string':
+ if b.fieldtype == "string":
if b.modern_vla:
output += f" + vl_api_string_len(&a->{b.fieldname})"
output += ";\n"
- output += '}\n\n'
+ output += "}\n\n"
output += "\n#endif"
output += "\n#endif /* vl_calcsizefun */\n\n"
@@ -1261,18 +1354,22 @@ static inline uword vl_api_{name}_t_calc_size (vl_api_{name}_t *a)
def version_tuple(s, module):
- '''Generate semantic version string'''
- output = '''\
+ """Generate semantic version string"""
+ output = """\
/****** Version tuple *****/
#ifdef vl_api_version_tuple
-'''
- if 'version' in s['Option']:
- v = s['Option']['version']
- (major, minor, patch) = v.split('.')
- output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % \
- (module, major, minor, patch)
+"""
+ if "version" in s["Option"]:
+ v = s["Option"]["version"]
+ (major, minor, patch) = v.split(".")
+ output += "vl_api_version_tuple(%s, %s, %s, %s)\n" % (
+ module,
+ major,
+ minor,
+ patch,
+ )
output += "\n#endif /* vl_api_version_tuple */\n\n"
@@ -1280,131 +1377,145 @@ def version_tuple(s, module):
def generate_include_enum(s, module, stream):
- '''Generate <name>.api_enum.h'''
+ """Generate <name>.api_enum.h"""
write = stream.write
- if 'Define' in s:
- write('typedef enum {\n')
- for t in s['Define']:
- write(' VL_API_{},\n'.format(t.name.upper()))
- write(' VL_MSG_{}_LAST\n'.format(module.upper()))
- write('}} vl_api_{}_enum_t;\n'.format(module))
+ if "Define" in s:
+ write("typedef enum {\n")
+ for t in s["Define"]:
+ write(" VL_API_{},\n".format(t.name.upper()))
+ write(" VL_MSG_{}_LAST\n".format(module.upper()))
+ write("}} vl_api_{}_enum_t;\n".format(module))
def generate_include_counters(s, stream):
- '''Include file for the counter data model types.'''
+ """Include file for the counter data model types."""
write = stream.write
for counters in s:
csetname = counters.name
- write('typedef enum {\n')
+ write("typedef enum {\n")
for c in counters.block:
- write(' {}_ERROR_{},\n'
- .format(csetname.upper(), c['name'].upper()))
- write(' {}_N_ERROR\n'.format(csetname.upper()))
- write('}} vl_counter_{}_enum_t;\n'.format(csetname))
+ write(" {}_ERROR_{},\n".format(csetname.upper(), c["name"].upper()))
+ write(" {}_N_ERROR\n".format(csetname.upper()))
+ write("}} vl_counter_{}_enum_t;\n".format(csetname))
- write('extern vlib_error_desc_t {}_error_counters[];\n'.format(csetname))
+ write("extern vlib_error_desc_t {}_error_counters[];\n".format(csetname))
def generate_include_types(s, module, stream):
- '''Generate separate API _types file.'''
+ """Generate separate API _types file."""
write = stream.write
- write('#ifndef included_{module}_api_types_h\n'.format(module=module))
- write('#define included_{module}_api_types_h\n'.format(module=module))
-
- if 'version' in s['Option']:
- v = s['Option']['version']
- (major, minor, patch) = v.split('.')
- write('#define VL_API_{m}_API_VERSION_MAJOR {v}\n'
- .format(m=module.upper(), v=major))
- write('#define VL_API_{m}_API_VERSION_MINOR {v}\n'
- .format(m=module.upper(), v=minor))
- write('#define VL_API_{m}_API_VERSION_PATCH {v}\n'
- .format(m=module.upper(), v=patch))
-
- if 'Import' in s:
- write('/* Imported API files */\n')
- for i in s['Import']:
- filename = i.filename.replace('plugins/', '')
- write('#include <{}_types.h>\n'.format(filename))
-
- for o in itertools.chain(s['types'], s['Define']):
+ write("#ifndef included_{module}_api_types_h\n".format(module=module))
+ write("#define included_{module}_api_types_h\n".format(module=module))
+
+ if "version" in s["Option"]:
+ v = s["Option"]["version"]
+ (major, minor, patch) = v.split(".")
+ write(
+ "#define VL_API_{m}_API_VERSION_MAJOR {v}\n".format(
+ m=module.upper(), v=major
+ )
+ )
+ write(
+ "#define VL_API_{m}_API_VERSION_MINOR {v}\n".format(
+ m=module.upper(), v=minor
+ )
+ )
+ write(
+ "#define VL_API_{m}_API_VERSION_PATCH {v}\n".format(
+ m=module.upper(), v=patch
+ )
+ )
+
+ if "Import" in s:
+ write("/* Imported API files */\n")
+ for i in s["Import"]:
+ filename = i.filename.replace("plugins/", "")
+ write("#include <{}_types.h>\n".format(filename))
+
+ for o in itertools.chain(s["types"], s["Define"]):
tname = o.__class__.__name__
- if tname == 'Using':
- if 'length' in o.alias:
- write('typedef %s vl_api_%s_t[%s];\n' %
- (o.alias['type'], o.name, o.alias['length']))
+ if tname == "Using":
+ if "length" in o.alias:
+ write(
+ "typedef %s vl_api_%s_t[%s];\n"
+ % (o.alias["type"], o.name, o.alias["length"])
+ )
else:
- write('typedef %s vl_api_%s_t;\n' % (o.alias['type'], o.name))
- elif tname == 'Enum' or tname == 'EnumFlag':
- if o.enumtype == 'u32':
+ write("typedef %s vl_api_%s_t;\n" % (o.alias["type"], o.name))
+ elif tname == "Enum" or tname == "EnumFlag":
+ if o.enumtype == "u32":
write("typedef enum {\n")
else:
write("typedef enum __attribute__((packed)) {\n")
for b in o.block:
write(" %s = %s,\n" % (b[0], b[1]))
- write('} vl_api_%s_t;\n' % o.name)
- if o.enumtype != 'u32':
- size1 = 'sizeof(vl_api_%s_t)' % o.name
- size2 = 'sizeof(%s)' % o.enumtype
- err_str = 'size of API enum %s is wrong' % o.name
- write('STATIC_ASSERT(%s == %s, "%s");\n'
- % (size1, size2, err_str))
+ write("} vl_api_%s_t;\n" % o.name)
+ if o.enumtype != "u32":
+ size1 = "sizeof(vl_api_%s_t)" % o.name
+ size2 = "sizeof(%s)" % o.enumtype
+ err_str = "size of API enum %s is wrong" % o.name
+ write('STATIC_ASSERT(%s == %s, "%s");\n' % (size1, size2, err_str))
else:
- if tname == 'Union':
- write("typedef union __attribute__ ((packed)) _vl_api_%s {\n"
- % o.name)
+ if tname == "Union":
+ write("typedef union __attribute__ ((packed)) _vl_api_%s {\n" % o.name)
else:
- write(("typedef struct __attribute__ ((packed)) _vl_api_%s {\n")
- % o.name)
+ write(
+ ("typedef struct __attribute__ ((packed)) _vl_api_%s {\n") % o.name
+ )
for b in o.block:
- if b.type == 'Option':
+ if b.type == "Option":
continue
- if b.type == 'Field':
- write(" %s %s;\n" % (api2c(b.fieldtype),
- b.fieldname))
- elif b.type == 'Array':
+ if b.type == "Field":
+ write(" %s %s;\n" % (api2c(b.fieldtype), b.fieldname))
+ elif b.type == "Array":
if b.lengthfield:
- write(" %s %s[0];\n" % (api2c(b.fieldtype),
- b.fieldname))
+ write(" %s %s[0];\n" % (api2c(b.fieldtype), b.fieldname))
else:
# Fixed length strings decay to nul terminated u8
- if b.fieldtype == 'string':
+ if b.fieldtype == "string":
if b.modern_vla:
- write(' {} {};\n'
- .format(api2c(b.fieldtype),
- b.fieldname))
+ write(
+ " {} {};\n".format(
+ api2c(b.fieldtype), b.fieldname
+ )
+ )
else:
- write(' u8 {}[{}];\n'
- .format(b.fieldname, b.length))
+ write(" u8 {}[{}];\n".format(b.fieldname, b.length))
else:
- write(" %s %s[%s];\n" %
- (api2c(b.fieldtype), b.fieldname,
- b.length))
+ write(
+ " %s %s[%s];\n"
+ % (api2c(b.fieldtype), b.fieldname, b.length)
+ )
else:
- raise ValueError("Error in processing type {} for {}"
- .format(b, o.name))
+ raise ValueError(
+ "Error in processing type {} for {}".format(b, o.name)
+ )
- write('} vl_api_%s_t;\n' % o.name)
- write(f'#define VL_API_{o.name.upper()}_IS_CONSTANT_SIZE ({0 if o.vla else 1})\n\n')
+ write("} vl_api_%s_t;\n" % o.name)
+ write(
+ f"#define VL_API_{o.name.upper()}_IS_CONSTANT_SIZE ({0 if o.vla else 1})\n\n"
+ )
- for t in s['Define']:
- write('#define VL_API_{ID}_CRC "{n}_{crc:08x}"\n'
- .format(n=t.name, ID=t.name.upper(), crc=t.crc))
+ for t in s["Define"]:
+ write(
+ '#define VL_API_{ID}_CRC "{n}_{crc:08x}"\n'.format(
+ n=t.name, ID=t.name.upper(), crc=t.crc
+ )
+ )
write("\n#endif\n")
-def generate_c_boilerplate(services, defines, counters, file_crc,
- module, stream):
- '''VPP side plugin.'''
+def generate_c_boilerplate(services, defines, counters, file_crc, module, stream):
+ """VPP side plugin."""
write = stream.write
define_hash = {d.name: d for d in defines}
- hdr = '''\
+ hdr = """\
#define vl_endianfun /* define message structures */
#include "{module}.api.h"
#undef vl_endianfun
@@ -1419,89 +1530,98 @@ def generate_c_boilerplate(services, defines, counters, file_crc,
#include "{module}.api.h"
#undef vl_printfun
-'''
+"""
write(hdr.format(module=module))
- write('static u16\n')
- write('setup_message_id_table (void) {\n')
- write(' api_main_t *am = my_api_main;\n')
- write(' vl_msg_api_msg_config_t c;\n')
- write(' u16 msg_id_base = vl_msg_api_get_msg_ids ("{}_{crc:08x}", '
- 'VL_MSG_{m}_LAST);\n'
- .format(module, crc=file_crc, m=module.upper()))
+ write("static u16\n")
+ write("setup_message_id_table (void) {\n")
+ write(" api_main_t *am = my_api_main;\n")
+ write(" vl_msg_api_msg_config_t c;\n")
+ write(
+ ' u16 msg_id_base = vl_msg_api_get_msg_ids ("{}_{crc:08x}", '
+ "VL_MSG_{m}_LAST);\n".format(module, crc=file_crc, m=module.upper())
+ )
for d in defines:
- write(' vl_msg_api_add_msg_name_crc (am, "{n}_{crc:08x}",\n'
- ' VL_API_{ID} + msg_id_base);\n'
- .format(n=d.name, ID=d.name.upper(), crc=d.crc))
+ write(
+ ' vl_msg_api_add_msg_name_crc (am, "{n}_{crc:08x}",\n'
+ " VL_API_{ID} + msg_id_base);\n".format(
+ n=d.name, ID=d.name.upper(), crc=d.crc
+ )
+ )
for s in services:
d = define_hash[s.caller]
- write(' c = (vl_msg_api_msg_config_t) '
- ' {{.id = VL_API_{ID} + msg_id_base,\n'
- ' .name = "{n}",\n'
- ' .handler = vl_api_{n}_t_handler,\n'
- ' .cleanup = vl_noop_handler,\n'
- ' .endian = vl_api_{n}_t_endian,\n'
- ' .print = vl_api_{n}_t_print,\n'
- ' .traced = 1,\n'
- ' .replay = 1,\n'
- ' .print_json = vl_api_{n}_t_print_json,\n'
- ' .tojson = vl_api_{n}_t_tojson,\n'
- ' .fromjson = vl_api_{n}_t_fromjson,\n'
- ' .calc_size = vl_api_{n}_t_calc_size,\n'
- ' .is_autoendian = {auto}}};\n'
- .format(n=s.caller, ID=s.caller.upper(),
- auto=d.autoendian))
- write(' vl_msg_api_config (&c);\n')
+ write(
+ " c = (vl_msg_api_msg_config_t) "
+ " {{.id = VL_API_{ID} + msg_id_base,\n"
+ ' .name = "{n}",\n'
+ " .handler = vl_api_{n}_t_handler,\n"
+ " .cleanup = vl_noop_handler,\n"
+ " .endian = vl_api_{n}_t_endian,\n"
+ " .print = vl_api_{n}_t_print,\n"
+ " .traced = 1,\n"
+ " .replay = 1,\n"
+ " .print_json = vl_api_{n}_t_print_json,\n"
+ " .tojson = vl_api_{n}_t_tojson,\n"
+ " .fromjson = vl_api_{n}_t_fromjson,\n"
+ " .calc_size = vl_api_{n}_t_calc_size,\n"
+ " .is_autoendian = {auto}}};\n".format(
+ n=s.caller, ID=s.caller.upper(), auto=d.autoendian
+ )
+ )
+ write(" vl_msg_api_config (&c);\n")
try:
d = define_hash[s.reply]
- write(' c = (vl_msg_api_msg_config_t) '
- '{{.id = VL_API_{ID} + msg_id_base,\n'
- ' .name = "{n}",\n'
- ' .handler = 0,\n'
- ' .cleanup = vl_noop_handler,\n'
- ' .endian = vl_api_{n}_t_endian,\n'
- ' .print = vl_api_{n}_t_print,\n'
- ' .traced = 1,\n'
- ' .replay = 1,\n'
- ' .print_json = vl_api_{n}_t_print_json,\n'
- ' .tojson = vl_api_{n}_t_tojson,\n'
- ' .fromjson = vl_api_{n}_t_fromjson,\n'
- ' .calc_size = vl_api_{n}_t_calc_size,\n'
- ' .is_autoendian = {auto}}};\n'
- .format(n=s.reply, ID=s.reply.upper(),
- auto=d.autoendian))
- write(' vl_msg_api_config (&c);\n')
+ write(
+ " c = (vl_msg_api_msg_config_t) "
+ "{{.id = VL_API_{ID} + msg_id_base,\n"
+ ' .name = "{n}",\n'
+ " .handler = 0,\n"
+ " .cleanup = vl_noop_handler,\n"
+ " .endian = vl_api_{n}_t_endian,\n"
+ " .print = vl_api_{n}_t_print,\n"
+ " .traced = 1,\n"
+ " .replay = 1,\n"
+ " .print_json = vl_api_{n}_t_print_json,\n"
+ " .tojson = vl_api_{n}_t_tojson,\n"
+ " .fromjson = vl_api_{n}_t_fromjson,\n"
+ " .calc_size = vl_api_{n}_t_calc_size,\n"
+ " .is_autoendian = {auto}}};\n".format(
+ n=s.reply, ID=s.reply.upper(), auto=d.autoendian
+ )
+ )
+ write(" vl_msg_api_config (&c);\n")
except KeyError:
pass
- write(' return msg_id_base;\n')
- write('}\n')
+ write(" return msg_id_base;\n")
+ write("}\n")
- severity = {'error': 'VL_COUNTER_SEVERITY_ERROR',
- 'info': 'VL_COUNTER_SEVERITY_INFO',
- 'warn': 'VL_COUNTER_SEVERITY_WARN'}
+ severity = {
+ "error": "VL_COUNTER_SEVERITY_ERROR",
+ "info": "VL_COUNTER_SEVERITY_INFO",
+ "warn": "VL_COUNTER_SEVERITY_WARN",
+ }
for cnt in counters:
csetname = cnt.name
- write('vlib_error_desc_t {}_error_counters[] = {{\n'.format(csetname))
+ write("vlib_error_desc_t {}_error_counters[] = {{\n".format(csetname))
for c in cnt.block:
- write(' {\n')
- write(' .name = "{}",\n'.format(c['name']))
- write(' .desc = "{}",\n'.format(c['description']))
- write(' .severity = {},\n'.format(severity[c['severity']]))
- write(' },\n')
- write('};\n')
+ write(" {\n")
+ write(' .name = "{}",\n'.format(c["name"]))
+ write(' .desc = "{}",\n'.format(c["description"]))
+ write(" .severity = {},\n".format(severity[c["severity"]]))
+ write(" },\n")
+ write("};\n")
-def generate_c_test_boilerplate(services, defines, file_crc, module, plugin,
- stream):
- '''Generate code for legacy style VAT. To be deleted.'''
+def generate_c_test_boilerplate(services, defines, file_crc, module, plugin, stream):
+ """Generate code for legacy style VAT. To be deleted."""
write = stream.write
define_hash = {d.name: d for d in defines}
- hdr = '''\
+ hdr = """\
#define vl_endianfun /* define message structures */
#include "{module}.api.h"
#undef vl_endianfun
@@ -1516,7 +1636,7 @@ def generate_c_test_boilerplate(services, defines, file_crc, module, plugin,
#include "{module}.api.h"
#undef vl_printfun
-'''
+"""
write(hdr.format(module=module))
for s in services:
@@ -1525,113 +1645,133 @@ def generate_c_test_boilerplate(services, defines, file_crc, module, plugin,
except KeyError:
continue
if d.manual_print:
- write('/*\n'
- ' * Manual definition requested for: \n'
- ' * vl_api_{n}_t_handler()\n'
- ' */\n'
- .format(n=s.reply))
+ write(
+ "/*\n"
+ " * Manual definition requested for: \n"
+ " * vl_api_{n}_t_handler()\n"
+ " */\n".format(n=s.reply)
+ )
continue
if not define_hash[s.caller].autoreply:
- write('/* Generation not supported (vl_api_{n}_t_handler()) */\n'
- .format(n=s.reply))
+ write(
+ "/* Generation not supported (vl_api_{n}_t_handler()) */\n".format(
+ n=s.reply
+ )
+ )
continue
- write('#ifndef VL_API_{n}_T_HANDLER\n'.format(n=s.reply.upper()))
- write('static void\n')
- write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'
- .format(n=s.reply))
- write(' vat_main_t * vam = {}_test_main.vat_main;\n'.format(module))
- write(' i32 retval = ntohl(mp->retval);\n')
- write(' if (vam->async_mode) {\n')
- write(' vam->async_errors += (retval < 0);\n')
- write(' } else {\n')
- write(' vam->retval = retval;\n')
- write(' vam->result_ready = 1;\n')
- write(' }\n')
- write('}\n')
- write('#endif\n')
+ write("#ifndef VL_API_{n}_T_HANDLER\n".format(n=s.reply.upper()))
+ write("static void\n")
+ write("vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n".format(n=s.reply))
+ write(" vat_main_t * vam = {}_test_main.vat_main;\n".format(module))
+ write(" i32 retval = ntohl(mp->retval);\n")
+ write(" if (vam->async_mode) {\n")
+ write(" vam->async_errors += (retval < 0);\n")
+ write(" } else {\n")
+ write(" vam->retval = retval;\n")
+ write(" vam->result_ready = 1;\n")
+ write(" }\n")
+ write("}\n")
+ write("#endif\n")
for e in s.events:
if define_hash[e].manual_print:
continue
- write('static void\n')
- write('vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n'.format(n=e))
+ write("static void\n")
+ write("vl_api_{n}_t_handler (vl_api_{n}_t * mp) {{\n".format(n=e))
write(' vl_print(0, "{n} event called:");\n'.format(n=e))
- write(' vl_api_{n}_t_print(mp, 0);\n'.format(n=e))
- write('}\n')
+ write(" vl_api_{n}_t_print(mp, 0);\n".format(n=e))
+ write("}\n")
- write('static void\n')
- write('setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n')
+ write("static void\n")
+ write("setup_message_id_table (vat_main_t * vam, u16 msg_id_base) {\n")
for s in services:
- write(' vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, '
- ' "{n}",\n'
- ' vl_api_{n}_t_handler, '
- ' vl_noop_handler,\n'
- ' vl_api_{n}_t_endian, '
- ' vl_api_{n}_t_print,\n'
- ' sizeof(vl_api_{n}_t), 1,\n'
- ' vl_api_{n}_t_print_json,\n'
- ' vl_api_{n}_t_tojson,\n'
- ' vl_api_{n}_t_fromjson,\n'
- ' vl_api_{n}_t_calc_size);\n'
- .format(n=s.reply, ID=s.reply.upper()))
- write(' hash_set_mem (vam->function_by_name, "{n}", api_{n});\n'
- .format(n=s.caller))
+ write(
+ " vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "
+ ' "{n}",\n'
+ " vl_api_{n}_t_handler, "
+ " vl_noop_handler,\n"
+ " vl_api_{n}_t_endian, "
+ " vl_api_{n}_t_print,\n"
+ " sizeof(vl_api_{n}_t), 1,\n"
+ " vl_api_{n}_t_print_json,\n"
+ " vl_api_{n}_t_tojson,\n"
+ " vl_api_{n}_t_fromjson,\n"
+ " vl_api_{n}_t_calc_size);\n".format(
+ n=s.reply, ID=s.reply.upper()
+ )
+ )
+ write(
+ ' hash_set_mem (vam->function_by_name, "{n}", api_{n});\n'.format(
+ n=s.caller
+ )
+ )
try:
- write(' hash_set_mem (vam->help_by_name, "{n}", "{help}");\n'
- .format(n=s.caller,
- help=define_hash[s.caller].options['vat_help']))
+ write(
+ ' hash_set_mem (vam->help_by_name, "{n}", "{help}");\n'.format(
+ n=s.caller, help=define_hash[s.caller].options["vat_help"]
+ )
+ )
except KeyError:
pass
# Events
for e in s.events:
- write(' vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, '
- ' "{n}",\n'
- ' vl_api_{n}_t_handler, '
- ' vl_noop_handler,\n'
- ' vl_api_{n}_t_endian, '
- ' vl_api_{n}_t_print,\n'
- ' sizeof(vl_api_{n}_t), 1,\n'
- ' vl_api_{n}_t_print_json,\n'
- ' vl_api_{n}_t_tojson,\n'
- ' vl_api_{n}_t_fromjson,\n'
- ' vl_api_{n}_t_calc_size);\n'
- .format(n=e, ID=e.upper()))
-
- write('}\n')
- write('clib_error_t * vat_plugin_register (vat_main_t *vam)\n')
- write('{\n')
- write(' {n}_test_main_t * mainp = &{n}_test_main;\n'.format(n=module))
- write(' mainp->vat_main = vam;\n')
- write(' mainp->msg_id_base = vl_client_get_first_plugin_msg_id '
- ' ("{n}_{crc:08x}");\n'
- .format(n=module, crc=file_crc))
- write(' if (mainp->msg_id_base == (u16) ~0)\n')
- write(' return clib_error_return (0, "{} plugin not loaded...");\n'
- .format(module))
- write(' setup_message_id_table (vam, mainp->msg_id_base);\n')
- write('#ifdef VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE\n')
- write(' VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE(vam);\n')
- write('#endif\n')
- write(' return 0;\n')
- write('}\n')
+ write(
+ " vl_msg_api_set_handlers(VL_API_{ID} + msg_id_base, "
+ ' "{n}",\n'
+ " vl_api_{n}_t_handler, "
+ " vl_noop_handler,\n"
+ " vl_api_{n}_t_endian, "
+ " vl_api_{n}_t_print,\n"
+ " sizeof(vl_api_{n}_t), 1,\n"
+ " vl_api_{n}_t_print_json,\n"
+ " vl_api_{n}_t_tojson,\n"
+ " vl_api_{n}_t_fromjson,\n"
+ " vl_api_{n}_t_calc_size);\n".format(
+ n=e, ID=e.upper()
+ )
+ )
+
+ write("}\n")
+ write("clib_error_t * vat_plugin_register (vat_main_t *vam)\n")
+ write("{\n")
+ write(" {n}_test_main_t * mainp = &{n}_test_main;\n".format(n=module))
+ write(" mainp->vat_main = vam;\n")
+ write(
+ " mainp->msg_id_base = vl_client_get_first_plugin_msg_id "
+ ' ("{n}_{crc:08x}");\n'.format(n=module, crc=file_crc)
+ )
+ write(" if (mainp->msg_id_base == (u16) ~0)\n")
+ write(
+ ' return clib_error_return (0, "{} plugin not loaded...");\n'.format(
+ module
+ )
+ )
+ write(" setup_message_id_table (vam, mainp->msg_id_base);\n")
+ write("#ifdef VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE\n")
+ write(" VL_API_LOCAL_SETUP_MESSAGE_ID_TABLE(vam);\n")
+ write("#endif\n")
+ write(" return 0;\n")
+ write("}\n")
def apifunc(func):
- '''Check if a method is generated already.'''
+ """Check if a method is generated already."""
+
def _f(module, d, processed, *args):
if d.name in processed:
return None
processed[d.name] = True
return func(module, d, *args)
+
return _f
def c_test_api_service(s, dump, stream):
- '''Generate JSON code for a service.'''
+ """Generate JSON code for a service."""
write = stream.write
- req_reply_template = '''\
+ req_reply_template = """\
static cJSON *
api_{n} (cJSON *o)
{{
@@ -1664,8 +1804,8 @@ api_{n} (cJSON *o)
return vl_api_{r}_t_tojson(rmp);
}}
-'''
- dump_details_template = '''\
+"""
+ dump_details_template = """\
static cJSON *
api_{n} (cJSON *o)
{{
@@ -1719,8 +1859,8 @@ api_{n} (cJSON *o)
return reply;
}}
-'''
- gets_details_reply_template = '''\
+"""
+ gets_details_reply_template = """\
static cJSON *
api_{n} (cJSON *o)
{{
@@ -1769,32 +1909,42 @@ api_{n} (cJSON *o)
return reply;
}}
-'''
+"""
if dump:
if s.stream_message:
- write(gets_details_reply_template
- .format(n=s.caller, r=s.reply, N=s.caller.upper(),
- R=s.reply.upper(), d=s.stream_message,
- D=s.stream_message.upper()))
+ write(
+ gets_details_reply_template.format(
+ n=s.caller,
+ r=s.reply,
+ N=s.caller.upper(),
+ R=s.reply.upper(),
+ d=s.stream_message,
+ D=s.stream_message.upper(),
+ )
+ )
else:
- write(dump_details_template.format(n=s.caller, r=s.reply,
- N=s.caller.upper(),
- R=s.reply.upper()))
+ write(
+ dump_details_template.format(
+ n=s.caller, r=s.reply, N=s.caller.upper(), R=s.reply.upper()
+ )
+ )
else:
- write(req_reply_template.format(n=s.caller, r=s.reply,
- N=s.caller.upper(),
- R=s.reply.upper()))
+ write(
+ req_reply_template.format(
+ n=s.caller, r=s.reply, N=s.caller.upper(), R=s.reply.upper()
+ )
+ )
def generate_c_test2_boilerplate(services, defines, module, stream):
- '''Generate code for VAT2 plugin.'''
+ """Generate code for VAT2 plugin."""
write = stream.write
define_hash = {d.name: d for d in defines}
# replies = {}
- hdr = '''\
+ hdr = """\
#include <vlibapi/api.h>
#include <vlibmemory/api.h>
#include <vppinfra/error.h>
@@ -1829,7 +1979,7 @@ def generate_c_test2_boilerplate(services, defines, module, stream):
#include <vat2/vat2_helpers.h>
-'''
+"""
write(hdr.format(module=module))
@@ -1838,123 +1988,123 @@ def generate_c_test2_boilerplate(services, defines, module, stream):
continue
c_test_api_service(s, s.stream, stream)
- write('void vat2_register_function(char *, cJSON * (*)(cJSON *), cJSON * (*)(void *), u32);\n')
+ write(
+ "void vat2_register_function(char *, cJSON * (*)(cJSON *), cJSON * (*)(void *), u32);\n"
+ )
# write('__attribute__((constructor))')
- write('clib_error_t *\n')
- write('vat2_register_plugin (void) {\n')
+ write("clib_error_t *\n")
+ write("vat2_register_plugin (void) {\n")
for s in services:
if s.reply not in define_hash:
continue
crc = define_hash[s.caller].crc
- write(' vat2_register_function("{n}", api_{n}, (cJSON * (*)(void *))vl_api_{n}_t_tojson, 0x{crc:08x});\n'
- .format(n=s.caller, crc=crc))
- write(' return 0;\n')
- write('}\n')
+ write(
+ ' vat2_register_function("{n}", api_{n}, (cJSON * (*)(void *))vl_api_{n}_t_tojson, 0x{crc:08x});\n'.format(
+ n=s.caller, crc=crc
+ )
+ )
+ write(" return 0;\n")
+ write("}\n")
#
# Plugin entry point
#
def run(args, apifilename, s):
- '''Main plugin entry point.'''
+ """Main plugin entry point."""
stream = StringIO()
if not args.outputdir:
- sys.stderr.write('Missing --outputdir argument')
+ sys.stderr.write("Missing --outputdir argument")
return None
basename = os.path.basename(apifilename)
filename, _ = os.path.splitext(basename)
- modulename = filename.replace('.', '_')
- filename_enum = os.path.join(args.outputdir + '/' + basename + '_enum.h')
- filename_types = os.path.join(args.outputdir + '/' + basename + '_types.h')
- filename_c = os.path.join(args.outputdir + '/' + basename + '.c')
- filename_c_test = os.path.join(args.outputdir + '/' + basename + '_test.c')
- filename_c_test2 = (os.path.join(args.outputdir + '/' + basename +
- '_test2.c'))
- filename_c_tojson = (os.path.join(args.outputdir +
- '/' + basename + '_tojson.h'))
- filename_c_fromjson = (os.path.join(args.outputdir + '/' +
- basename + '_fromjson.h'))
+ modulename = filename.replace(".", "_")
+ filename_enum = os.path.join(args.outputdir + "/" + basename + "_enum.h")
+ filename_types = os.path.join(args.outputdir + "/" + basename + "_types.h")
+ filename_c = os.path.join(args.outputdir + "/" + basename + ".c")
+ filename_c_test = os.path.join(args.outputdir + "/" + basename + "_test.c")
+ filename_c_test2 = os.path.join(args.outputdir + "/" + basename + "_test2.c")
+ filename_c_tojson = os.path.join(args.outputdir + "/" + basename + "_tojson.h")
+ filename_c_fromjson = os.path.join(args.outputdir + "/" + basename + "_fromjson.h")
# Generate separate types file
st = StringIO()
generate_include_types(s, modulename, st)
- with open(filename_types, 'w') as fd:
+ with open(filename_types, "w") as fd:
st.seek(0)
shutil.copyfileobj(st, fd)
st.close()
# Generate separate enum file
st = StringIO()
- st.write('#ifndef included_{}_api_enum_h\n'.format(modulename))
- st.write('#define included_{}_api_enum_h\n'.format(modulename))
+ st.write("#ifndef included_{}_api_enum_h\n".format(modulename))
+ st.write("#define included_{}_api_enum_h\n".format(modulename))
generate_include_enum(s, modulename, st)
- generate_include_counters(s['Counters'], st)
- st.write('#endif\n')
- with open(filename_enum, 'w') as fd:
+ generate_include_counters(s["Counters"], st)
+ st.write("#endif\n")
+ with open(filename_enum, "w") as fd:
st.seek(0)
shutil.copyfileobj(st, fd)
st.close()
# Generate separate C file
st = StringIO()
- generate_c_boilerplate(s['Service'], s['Define'], s['Counters'],
- s['file_crc'], modulename, st)
- with open(filename_c, 'w') as fd:
+ generate_c_boilerplate(
+ s["Service"], s["Define"], s["Counters"], s["file_crc"], modulename, st
+ )
+ with open(filename_c, "w") as fd:
st.seek(0)
shutil.copyfileobj(st, fd)
st.close()
# Generate separate C test file
st = StringIO()
- plugin = bool('plugin' in apifilename)
- generate_c_test_boilerplate(s['Service'], s['Define'],
- s['file_crc'],
- modulename, plugin, st)
- with open(filename_c_test, 'w') as fd:
+ plugin = bool("plugin" in apifilename)
+ generate_c_test_boilerplate(
+ s["Service"], s["Define"], s["file_crc"], modulename, plugin, st
+ )
+ with open(filename_c_test, "w") as fd:
st.seek(0)
shutil.copyfileobj(st, fd)
st.close()
# Fully autogenerated VATv2 C test file
st = StringIO()
- generate_c_test2_boilerplate(s['Service'], s['Define'],
- modulename, st)
- with open(filename_c_test2, 'w') as fd:
+ generate_c_test2_boilerplate(s["Service"], s["Define"], modulename, st)
+ with open(filename_c_test2, "w") as fd:
st.seek(0)
shutil.copyfileobj(st, fd)
- st.close() #
+ st.close() #
# Generate separate JSON file
st = StringIO()
generate_tojson(s, modulename, st)
- with open(filename_c_tojson, 'w') as fd:
+ with open(filename_c_tojson, "w") as fd:
st.seek(0)
shutil.copyfileobj(st, fd)
st.close()
st = StringIO()
generate_fromjson(s, modulename, st)
- with open(filename_c_fromjson, 'w') as fd:
+ with open(filename_c_fromjson, "w") as fd:
st.seek(0)
shutil.copyfileobj(st, fd)
st.close()
- output = TOP_BOILERPLATE.format(datestring=DATESTRING,
- input_filename=basename)
- output += generate_imports(s['Import'])
+ output = TOP_BOILERPLATE.format(datestring=DATESTRING, input_filename=basename)
+ output += generate_imports(s["Import"])
output += msg_ids(s)
output += msg_names(s)
output += msg_name_crc_list(s, filename)
output += typedefs(modulename)
- printfun_types(s['types'], stream, modulename)
- printfun(s['Define'], stream, modulename)
+ printfun_types(s["types"], stream, modulename)
+ printfun(s["Define"], stream, modulename)
output += stream.getvalue()
stream.close()
- output += endianfun(s['types'] + s['Define'], modulename)
- output += calc_size_fun(s['types'] + s['Define'], modulename)
+ output += endianfun(s["types"] + s["Define"], modulename)
+ output += calc_size_fun(s["types"] + s["Define"], modulename)
output += version_tuple(s, basename)
- output += BOTTOM_BOILERPLATE.format(input_filename=basename,
- file_crc=s['file_crc'])
+ output += BOTTOM_BOILERPLATE.format(input_filename=basename, file_crc=s["file_crc"])
return output
diff --git a/src/tools/vppapigen/vppapigen_crc.py b/src/tools/vppapigen/vppapigen_crc.py
index 791e347292e..525f6c07efc 100644
--- a/src/tools/vppapigen/vppapigen_crc.py
+++ b/src/tools/vppapigen/vppapigen_crc.py
@@ -12,11 +12,10 @@ def run(args, input_filename, s):
major = 0
minor = 0
patch = 0
- if 'version' in s['Option']:
- v = s['Option']['version']
- (major, minor, patch) = v.split('.')
- j['_version'] = {'major': major, 'minor': minor, 'patch': patch}
- for t in s['Define']:
- j[t.name] = {'crc': f'{t.crc:#08x}', 'version': major,
- 'options': t.options}
- return json.dumps(j, indent=4, separators=(',', ': '))
+ if "version" in s["Option"]:
+ v = s["Option"]["version"]
+ (major, minor, patch) = v.split(".")
+ j["_version"] = {"major": major, "minor": minor, "patch": patch}
+ for t in s["Define"]:
+ j[t.name] = {"crc": f"{t.crc:#08x}", "version": major, "options": t.options}
+ return json.dumps(j, indent=4, separators=(",", ": "))
diff --git a/src/tools/vppapigen/vppapigen_json.py b/src/tools/vppapigen/vppapigen_json.py
index 5fa839f9854..695b8cc7aa2 100644
--- a/src/tools/vppapigen/vppapigen_json.py
+++ b/src/tools/vppapigen/vppapigen_json.py
@@ -14,7 +14,7 @@ def walk_imports(s):
def walk_counters(s, pathset):
r = []
for e in s:
- r2 = {'name': e.name, 'elements': e.block}
+ r2 = {"name": e.name, "elements": e.block}
r.append(r2)
r3 = []
@@ -31,7 +31,7 @@ def walk_enums(s):
d.append(e.name)
for b in e.block:
d.append(b)
- d.append({'enumtype': e.enumtype})
+ d.append({"enumtype": e.enumtype})
r.append(d)
return r
@@ -39,13 +39,13 @@ def walk_enums(s):
def walk_services(s):
r = {}
for e in s:
- d = {'reply': e.reply}
+ d = {"reply": e.reply}
if e.stream:
- d['stream'] = True
+ d["stream"] = True
if e.stream_message:
- d['stream_msg'] = e.stream_message
+ d["stream_msg"] = e.stream_message
if e.events:
- d['events'] = e.events
+ d["events"] = e.events
r[e.caller] = d
return r
@@ -56,28 +56,27 @@ def walk_defs(s, is_message=False):
d = []
d.append(t.name)
for b in t.block:
- if b.type == 'Option':
+ if b.type == "Option":
continue
- if b.type == 'Field':
+ if b.type == "Field":
if b.limit:
d.append([b.fieldtype, b.fieldname, b.limit])
else:
d.append([b.fieldtype, b.fieldname])
- elif b.type == 'Array':
+ elif b.type == "Array":
if b.lengthfield:
- d.append([b.fieldtype, b.fieldname,
- b.length, b.lengthfield])
+ d.append([b.fieldtype, b.fieldname, b.length, b.lengthfield])
else:
d.append([b.fieldtype, b.fieldname, b.length])
- elif b.type == 'Union':
+ elif b.type == "Union":
pass
else:
raise ValueError("Error in processing array type %s" % b)
if is_message and t.crc:
c = {}
- c['crc'] = "{0:#0{1}x}".format(t.crc, 10)
- c['options'] = t.options
+ c["crc"] = "{0:#0{1}x}".format(t.crc, 10)
+ c["options"] = t.options
d.append(c)
r.append(d)
@@ -90,19 +89,19 @@ def walk_defs(s, is_message=False):
def run(args, filename, s):
j = {}
- j['types'] = (walk_defs([o for o in s['types']
- if o.__class__.__name__ == 'Typedef']))
- j['messages'] = walk_defs(s['Define'], True)
- j['unions'] = (walk_defs([o for o in s['types']
- if o.__class__.__name__ == 'Union']))
- j['enums'] = (walk_enums([o for o in s['types']
- if o.__class__.__name__ == 'Enum']))
- j['enumflags'] = (walk_enums([o for o in s['types']
- if o.__class__.__name__ == 'EnumFlag']))
- j['services'] = walk_services(s['Service'])
- j['options'] = s['Option']
- j['aliases'] = {o.name:o.alias for o in s['types'] if o.__class__.__name__ == 'Using'}
- j['vl_api_version'] = hex(s['file_crc'])
- j['imports'] = walk_imports(i for i in s['Import'])
- j['counters'], j['paths'] = walk_counters(s['Counters'], s['Paths'])
- return json.dumps(j, indent=4, separators=(',', ': '))
+ j["types"] = walk_defs([o for o in s["types"] if o.__class__.__name__ == "Typedef"])
+ j["messages"] = walk_defs(s["Define"], True)
+ j["unions"] = walk_defs([o for o in s["types"] if o.__class__.__name__ == "Union"])
+ j["enums"] = walk_enums([o for o in s["types"] if o.__class__.__name__ == "Enum"])
+ j["enumflags"] = walk_enums(
+ [o for o in s["types"] if o.__class__.__name__ == "EnumFlag"]
+ )
+ j["services"] = walk_services(s["Service"])
+ j["options"] = s["Option"]
+ j["aliases"] = {
+ o.name: o.alias for o in s["types"] if o.__class__.__name__ == "Using"
+ }
+ j["vl_api_version"] = hex(s["file_crc"])
+ j["imports"] = walk_imports(i for i in s["Import"])
+ j["counters"], j["paths"] = walk_counters(s["Counters"], s["Paths"])
+ return json.dumps(j, indent=4, separators=(",", ": "))
diff --git a/src/vpp-api/python/setup.py b/src/vpp-api/python/setup.py
index 8bf6def2227..18637ba21b7 100644
--- a/src/vpp-api/python/setup.py
+++ b/src/vpp-api/python/setup.py
@@ -21,15 +21,16 @@ except ImportError:
requirements = []
setup(
- name='vpp_papi',
- version='2.0.0',
- description='VPP Python binding',
- author='Ole Troan',
- author_email='ot@cisco.com',
- url='https://wiki.fd.io/view/VPP/Python_API',
- license='Apache-2.0',
- test_suite='vpp_papi.tests',
+ name="vpp_papi",
+ version="2.0.0",
+ description="VPP Python binding",
+ author="Ole Troan",
+ author_email="ot@cisco.com",
+ url="https://wiki.fd.io/view/VPP/Python_API",
+ license="Apache-2.0",
+ test_suite="vpp_papi.tests",
install_requires=requirements,
packages=find_packages(),
- long_description='''VPP Python language binding.''',
- zip_safe=True)
+ long_description="""VPP Python language binding.""",
+ zip_safe=True,
+)
diff --git a/src/vpp-api/python/vpp_papi/__init__.py b/src/vpp-api/python/vpp_papi/__init__.py
index b2b4fc78fc1..f87b6480d4e 100644
--- a/src/vpp-api/python/vpp_papi/__init__.py
+++ b/src/vpp-api/python/vpp_papi/__init__.py
@@ -3,7 +3,7 @@ from .vpp_papi import VppEnum, VppEnumType, VppEnumFlag # noqa: F401
from .vpp_papi import VPPIOError, VPPRuntimeError, VPPValueError # noqa: F401
from .vpp_papi import VPPApiClient # noqa: F401
from .vpp_papi import VPPApiJSONFiles # noqa: F401
-from . macaddress import MACAddress, mac_pton, mac_ntop # noqa: F401
+from .macaddress import MACAddress, mac_pton, mac_ntop # noqa: F401
# sorted lexicographically
from .vpp_serializer import BaseTypes # noqa: F401
@@ -11,6 +11,7 @@ from .vpp_serializer import VPPEnumType, VPPType, VPPTypeAlias # noqa: F401
from .vpp_serializer import VPPMessage, VPPUnionType # noqa: F401
import pkg_resources # part of setuptools
+
try:
__version__ = pkg_resources.get_distribution("vpp_papi").version
except (pkg_resources.DistributionNotFound):
diff --git a/src/vpp-api/python/vpp_papi/macaddress.py b/src/vpp-api/python/vpp_papi/macaddress.py
index c3b10a3c11e..8799bd7be24 100644
--- a/src/vpp-api/python/vpp_papi/macaddress.py
+++ b/src/vpp-api/python/vpp_papi/macaddress.py
@@ -18,20 +18,19 @@ import binascii
def mac_pton(s):
- '''Convert MAC address as text to binary'''
- return binascii.unhexlify(s.replace(':', ''))
+ """Convert MAC address as text to binary"""
+ return binascii.unhexlify(s.replace(":", ""))
def mac_ntop(binary):
- '''Convert MAC address as binary to text'''
- x = b':'.join(binascii.hexlify(binary)[i:i + 2]
- for i in range(0, 12, 2))
- return str(x.decode('ascii'))
+ """Convert MAC address as binary to text"""
+ x = b":".join(binascii.hexlify(binary)[i : i + 2] for i in range(0, 12, 2))
+ return str(x.decode("ascii"))
-class MACAddress():
+class MACAddress:
def __init__(self, mac):
- '''MAC Address as a text-string (aa:bb:cc:dd:ee:ff) or 6 bytes'''
+ """MAC Address as a text-string (aa:bb:cc:dd:ee:ff) or 6 bytes"""
# Of course Python 2 doesn't distinguish str from bytes
if type(mac) is bytes and len(mac) == 6:
self.mac_binary = mac
@@ -51,7 +50,7 @@ class MACAddress():
return self.mac_string
def __repr__(self):
- return '%s(%s)' % (self.__class__.__name__, self.mac_string)
+ return "%s(%s)" % (self.__class__.__name__, self.mac_string)
def __eq__(self, other):
diff --git a/src/vpp-api/python/vpp_papi/tests/test_macaddress.py b/src/vpp-api/python/vpp_papi/tests/test_macaddress.py
index 08e365afd92..e86ec75c76e 100644
--- a/src/vpp-api/python/vpp_papi/tests/test_macaddress.py
+++ b/src/vpp-api/python/vpp_papi/tests/test_macaddress.py
@@ -3,8 +3,6 @@ from vpp_papi import MACAddress
class TestMacAddress(unittest.TestCase):
-
def test_eq(self):
- mac = '11:22:33:44:55:66'
- self.assertEqual(MACAddress(mac),
- MACAddress(mac))
+ mac = "11:22:33:44:55:66"
+ self.assertEqual(MACAddress(mac), MACAddress(mac))
diff --git a/src/vpp-api/python/vpp_papi/tests/test_vpp_format.py b/src/vpp-api/python/vpp_papi/tests/test_vpp_format.py
index 5c179c02e0a..ae4d2c5126d 100644
--- a/src/vpp-api/python/vpp_papi/tests/test_vpp_format.py
+++ b/src/vpp-api/python/vpp_papi/tests/test_vpp_format.py
@@ -25,57 +25,64 @@ from vpp_papi import vpp_format
from parameterized import parameterized
-ip4_addr = '1.2.3.4'
-ip4_addrn = b'\x01\x02\x03\x04'
+ip4_addr = "1.2.3.4"
+ip4_addrn = b"\x01\x02\x03\x04"
ip4_prefix_len = 32
-ip4_prefix = '%s/%s' % (ip4_addr, ip4_prefix_len)
+ip4_prefix = "%s/%s" % (ip4_addr, ip4_prefix_len)
ipv4_network = ipaddress.IPv4Network(text_type(ip4_prefix))
-ip4_addr_format_vl_api_address_t = {'un': {'ip4': b'\x01\x02\x03\x04'},
- 'af': 0}
-ip4_addr_format_vl_api_prefix_t = {'address': # noqa: E127,E501
- {'un': {'ip4': b'\x01\x02\x03\x04'},
- 'af': 0},
- 'len': ip4_prefix_len}
-ip4_addr_format_vl_api_prefix_packed_t = {'address': b'\x01\x02\x03\x04',
- 'len': ip4_prefix_len}
-
-ip6_addr = 'dead::'
-ip6_addrn = b'\xde\xad\x00\x00\x00\x00\x00\x00' \
- b'\x00\x00\x00\x00\x00\x00\x00\x00'
+ip4_addr_format_vl_api_address_t = {"un": {"ip4": b"\x01\x02\x03\x04"}, "af": 0}
+ip4_addr_format_vl_api_prefix_t = {
+ "address": {"un": {"ip4": b"\x01\x02\x03\x04"}, "af": 0}, # noqa: E127,E501
+ "len": ip4_prefix_len,
+}
+ip4_addr_format_vl_api_prefix_packed_t = {
+ "address": b"\x01\x02\x03\x04",
+ "len": ip4_prefix_len,
+}
+
+ip6_addr = "dead::"
+ip6_addrn = b"\xde\xad\x00\x00\x00\x00\x00\x00" b"\x00\x00\x00\x00\x00\x00\x00\x00"
ip6_prefix_len = 127
-ip6_prefix = '%s/%s' % (ip6_addr, ip6_prefix_len)
+ip6_prefix = "%s/%s" % (ip6_addr, ip6_prefix_len)
ipv6_network = ipaddress.IPv6Network(text_type(ip6_prefix))
-ip6_addr_format_vl_api_address_t = {'un': {'ip6': b'\xde\xad\x00\x00'
- b'\x00\x00\x00\x00'
- b'\x00\x00\x00\x00'
- b'\x00\x00\x00\x00'},
- 'af': 1}
-ip6_addr_format_vl_api_prefix_t = {'address': # noqa: E127
- {'af': 1,
- 'un': {
- 'ip6': b'\xde\xad\x00\x00'
- b'\x00\x00\x00\x00'
- b'\x00\x00\x00\x00'
- b'\x00\x00\x00\x00'}},
- 'len': ip6_prefix_len}
-ip6_addr_format_vl_api_prefix_packed_t = {'address': b'\xde\xad\x00\x00' # noqa: E127,E501
- b'\x00\x00\x00\x00'
- b'\x00\x00\x00\x00'
- b'\x00\x00\x00\x00',
- 'len': ip6_prefix_len}
+ip6_addr_format_vl_api_address_t = {
+ "un": {
+ "ip6": b"\xde\xad\x00\x00"
+ b"\x00\x00\x00\x00"
+ b"\x00\x00\x00\x00"
+ b"\x00\x00\x00\x00"
+ },
+ "af": 1,
+}
+ip6_addr_format_vl_api_prefix_t = {
+ "address": { # noqa: E127
+ "af": 1,
+ "un": {
+ "ip6": b"\xde\xad\x00\x00"
+ b"\x00\x00\x00\x00"
+ b"\x00\x00\x00\x00"
+ b"\x00\x00\x00\x00"
+ },
+ },
+ "len": ip6_prefix_len,
+}
+ip6_addr_format_vl_api_prefix_packed_t = {
+ "address": b"\xde\xad\x00\x00" # noqa: E127,E501
+ b"\x00\x00\x00\x00"
+ b"\x00\x00\x00\x00"
+ b"\x00\x00\x00\x00",
+ "len": ip6_prefix_len,
+}
class TestVppFormat(unittest.TestCase):
-
def test_format_vl_api_address_t(self):
res = vpp_format.format_vl_api_address_t(ip4_addr)
self.assertEqual(res, ip4_addr_format_vl_api_address_t)
# PY2: raises socket.error
# PY3: raises OSError
- with self.assertRaises((TypeError,
- socket.error,
- OSError)):
+ with self.assertRaises((TypeError, socket.error, OSError)):
res = vpp_format.format_vl_api_address_t(ip4_addrn)
res = vpp_format.format_vl_api_address_t(ip6_addr)
@@ -84,19 +91,14 @@ class TestVppFormat(unittest.TestCase):
with self.assertRaises(TypeError):
es = vpp_format.format_vl_api_address_t(ip6_addrn)
- @parameterized.expand([('ip4 prefix',
- ip4_prefix,
- ip4_addr_format_vl_api_prefix_t),
- ('ip6 prefix',
- ip6_prefix,
- ip6_addr_format_vl_api_prefix_t),
- ('IPv4Network',
- ipv4_network,
- ip4_addr_format_vl_api_prefix_t),
- ('IPv6Network',
- ipv6_network,
- ip6_addr_format_vl_api_prefix_t),
- ])
+ @parameterized.expand(
+ [
+ ("ip4 prefix", ip4_prefix, ip4_addr_format_vl_api_prefix_t),
+ ("ip6 prefix", ip6_prefix, ip6_addr_format_vl_api_prefix_t),
+ ("IPv4Network", ipv4_network, ip4_addr_format_vl_api_prefix_t),
+ ("IPv6Network", ipv6_network, ip6_addr_format_vl_api_prefix_t),
+ ]
+ )
def test_format_vl_api_prefix_t(self, _, arg, expected):
res = vpp_format.format_vl_api_prefix_t(arg)
self.assertEqual(res, expected)
diff --git a/src/vpp-api/python/vpp_papi/tests/test_vpp_papi.py b/src/vpp-api/python/vpp_papi/tests/test_vpp_papi.py
index 99acb7c7469..2b21c83966a 100644
--- a/src/vpp-api/python/vpp_papi/tests/test_vpp_papi.py
+++ b/src/vpp-api/python/vpp_papi/tests/test_vpp_papi.py
@@ -24,7 +24,7 @@ from vpp_papi import vpp_transport_shmem
class TestVppPapiVPPApiClient(unittest.TestCase):
def test_getcontext(self):
- vpp_papi.VPPApiClient.apidir = '.'
+ vpp_papi.VPPApiClient.apidir = "."
c = vpp_papi.VPPApiClient(testmode=True, use_socket=True)
# reset initialization at module load time.
@@ -39,7 +39,7 @@ class TestVppPapiVPPApiClientMp(unittest.TestCase):
# run_tests.py (eg. make test TEST_JOBS=10)
def test_get_context_mp(self):
- vpp_papi.VPPApiClient.apidir = '.'
+ vpp_papi.VPPApiClient.apidir = "."
c = vpp_papi.VPPApiClient(testmode=True, use_socket=True)
# reset initialization at module load time.
@@ -243,11 +243,11 @@ class TestVppPapiLogging(unittest.TestCase):
pass
client = Vpp
- with self.assertLogs('vpp_papi', level='DEBUG') as cm:
+ with self.assertLogs("vpp_papi", level="DEBUG") as cm:
vpp_papi.vpp_atexit(client)
- self.assertEqual(cm.output, ['DEBUG:vpp_papi:Cleaning up VPP on exit'])
+ self.assertEqual(cm.output, ["DEBUG:vpp_papi:Cleaning up VPP on exit"])
with self.assertRaises(AssertionError):
- with self.assertLogs('vpp_papi.serializer', level='DEBUG') as cm:
+ with self.assertLogs("vpp_papi.serializer", level="DEBUG") as cm:
vpp_papi.vpp_atexit(client)
self.assertEqual(cm.output, [])
diff --git a/src/vpp-api/python/vpp_papi/tests/test_vpp_serializer.py b/src/vpp-api/python/vpp_papi/tests/test_vpp_serializer.py
index c9b3d672d6a..eee38f00632 100755
--- a/src/vpp-api/python/vpp_papi/tests/test_vpp_serializer.py
+++ b/src/vpp-api/python/vpp_papi/tests/test_vpp_serializer.py
@@ -13,61 +13,57 @@ from ipaddress import *
class TestLimits(unittest.TestCase):
def test_string(self):
- fixed_string = VPPType('fixed_string',
- [['string', 'name', 16]])
+ fixed_string = VPPType("fixed_string", [["string", "name", 16]])
- b = fixed_string.pack({'name': 'foobar'})
+ b = fixed_string.pack({"name": "foobar"})
self.assertEqual(len(b), 16)
# Ensure string is nul terminated
- self.assertEqual(b.decode('ascii')[6], '\x00')
+ self.assertEqual(b.decode("ascii")[6], "\x00")
nt, size = fixed_string.unpack(b)
self.assertEqual(size, 16)
- self.assertEqual(nt.name, 'foobar')
+ self.assertEqual(nt.name, "foobar")
# Empty string
- b = fixed_string.pack({'name': ''})
+ b = fixed_string.pack({"name": ""})
self.assertEqual(len(b), 16)
nt, size = fixed_string.unpack(b)
self.assertEqual(size, 16)
- self.assertEqual(nt.name, '')
+ self.assertEqual(nt.name, "")
# String too long
with self.assertRaises(VPPSerializerValueError):
- b = fixed_string.pack({'name': 'foobarfoobar1234'})
+ b = fixed_string.pack({"name": "foobarfoobar1234"})
- variable_string = VPPType('variable_string',
- [['string', 'name', 0]])
- b = variable_string.pack({'name': 'foobar'})
- self.assertEqual(len(b), 4 + len('foobar'))
+ variable_string = VPPType("variable_string", [["string", "name", 0]])
+ b = variable_string.pack({"name": "foobar"})
+ self.assertEqual(len(b), 4 + len("foobar"))
nt, size = variable_string.unpack(b)
- self.assertEqual(size, 4 + len('foobar'))
- self.assertEqual(nt.name, 'foobar')
- self.assertEqual(len(nt.name), len('foobar'))
+ self.assertEqual(size, 4 + len("foobar"))
+ self.assertEqual(nt.name, "foobar")
+ self.assertEqual(len(nt.name), len("foobar"))
def test_limit(self):
- limited_type = VPPType('limited_type_t',
- [['string', 'name', 0, {'limit': 16}]])
- unlimited_type = VPPType('limited_type_t',
- [['string', 'name', 0]])
+ limited_type = VPPType("limited_type_t", [["string", "name", 0, {"limit": 16}]])
+ unlimited_type = VPPType("limited_type_t", [["string", "name", 0]])
- b = limited_type.pack({'name': 'foobar'})
+ b = limited_type.pack({"name": "foobar"})
self.assertEqual(len(b), 10)
- b = unlimited_type.pack({'name': 'foobar'})
+ b = unlimited_type.pack({"name": "foobar"})
self.assertEqual(len(b), 10)
with self.assertRaises(VPPSerializerValueError):
- b = limited_type.pack({'name': 'foobar'*3})
+ b = limited_type.pack({"name": "foobar" * 3})
class TestDefaults(unittest.TestCase):
def test_defaults(self):
- default_type = VPPType('default_type_t',
- [['u16', 'mtu', {'default': 1500, 'limit': 0}]])
- without_default_type = VPPType('without_default_type_t',
- [['u16', 'mtu']])
+ default_type = VPPType(
+ "default_type_t", [["u16", "mtu", {"default": 1500, "limit": 0}]]
+ )
+ without_default_type = VPPType("without_default_type_t", [["u16", "mtu"]])
b = default_type.pack({})
self.assertEqual(len(b), 2)
@@ -76,7 +72,7 @@ class TestDefaults(unittest.TestCase):
self.assertEqual(nt.mtu, 1500)
# distinguish between parameter 0 and parameter not passed
- b = default_type.pack({'mtu': 0})
+ b = default_type.pack({"mtu": 0})
self.assertEqual(len(b), 2)
nt, size = default_type.unpack(b)
self.assertEqual(len(b), size)
@@ -90,13 +86,15 @@ class TestDefaults(unittest.TestCase):
self.assertEqual(nt.mtu, 0)
# default enum type
- VPPEnumType('vl_api_enum_t', [["ADDRESS_IP4", 0],
- ["ADDRESS_IP6", 1],
- {"enumtype": "u32"}])
+ VPPEnumType(
+ "vl_api_enum_t",
+ [["ADDRESS_IP4", 0], ["ADDRESS_IP6", 1], {"enumtype": "u32"}],
+ )
- default_with_enum = VPPType('default_enum_type_t',
- [['u16', 'mtu'], ['vl_api_enum_t',
- 'e', {'default': 1}]])
+ default_with_enum = VPPType(
+ "default_enum_type_t",
+ [["u16", "mtu"], ["vl_api_enum_t", "e", {"default": 1}]],
+ )
b = default_with_enum.pack({})
self.assertEqual(len(b), 6)
@@ -106,275 +104,275 @@ class TestDefaults(unittest.TestCase):
class TestAddType(unittest.TestCase):
-
def test_union(self):
- un = VPPUnionType('test_union',
- [['u8', 'is_bool'],
- ['u32', 'is_int']])
+ un = VPPUnionType("test_union", [["u8", "is_bool"], ["u32", "is_int"]])
- b = un.pack({'is_int': 0x12345678})
+ b = un.pack({"is_int": 0x12345678})
nt, size = un.unpack(b)
self.assertEqual(len(b), size)
self.assertEqual(nt.is_bool, 0x12)
self.assertEqual(nt.is_int, 0x12345678)
def test_address(self):
- af = VPPEnumType('vl_api_address_family_t', [["ADDRESS_IP4", 0],
- ["ADDRESS_IP6", 1],
- {"enumtype": "u32"}])
- aff = VPPEnumFlagType('vl_api_address_family_flag_t', [["ADDRESS_IP4", 0],
- ["ADDRESS_IP6", 1],
- {"enumtype": "u32"}])
- ip4 = VPPTypeAlias('vl_api_ip4_address_t', {'type': 'u8',
- 'length': 4})
- ip6 = VPPTypeAlias('vl_api_ip6_address_t', {'type': 'u8',
- 'length': 16})
- VPPUnionType('vl_api_address_union_t',
- [["vl_api_ip4_address_t", "ip4"],
- ["vl_api_ip6_address_t", "ip6"]])
-
- address = VPPType('vl_api_address_t',
- [['vl_api_address_family_t', 'af'],
- ['vl_api_address_union_t', 'un']])
-
- prefix = VPPType('vl_api_prefix_t',
- [['vl_api_address_t', 'address'],
- ['u8', 'len']])
-
- va_address_list = VPPType('list_addresses',
- [['u8', 'count'],
- ['vl_api_address_t', 'addresses',
- 0, 'count']])
-
- message_with_va_address_list = VPPType('msg_with_vla',
- [['list_addresses',
- 'vla_address'],
- ['u8', 'is_cool']])
-
- b = ip4.pack(inet_pton(AF_INET, '1.1.1.1'))
+ af = VPPEnumType(
+ "vl_api_address_family_t",
+ [["ADDRESS_IP4", 0], ["ADDRESS_IP6", 1], {"enumtype": "u32"}],
+ )
+ aff = VPPEnumFlagType(
+ "vl_api_address_family_flag_t",
+ [["ADDRESS_IP4", 0], ["ADDRESS_IP6", 1], {"enumtype": "u32"}],
+ )
+ ip4 = VPPTypeAlias("vl_api_ip4_address_t", {"type": "u8", "length": 4})
+ ip6 = VPPTypeAlias("vl_api_ip6_address_t", {"type": "u8", "length": 16})
+ VPPUnionType(
+ "vl_api_address_union_t",
+ [["vl_api_ip4_address_t", "ip4"], ["vl_api_ip6_address_t", "ip6"]],
+ )
+
+ address = VPPType(
+ "vl_api_address_t",
+ [["vl_api_address_family_t", "af"], ["vl_api_address_union_t", "un"]],
+ )
+
+ prefix = VPPType(
+ "vl_api_prefix_t", [["vl_api_address_t", "address"], ["u8", "len"]]
+ )
+
+ va_address_list = VPPType(
+ "list_addresses",
+ [["u8", "count"], ["vl_api_address_t", "addresses", 0, "count"]],
+ )
+
+ message_with_va_address_list = VPPType(
+ "msg_with_vla", [["list_addresses", "vla_address"], ["u8", "is_cool"]]
+ )
+
+ b = ip4.pack(inet_pton(AF_INET, "1.1.1.1"))
self.assertEqual(len(b), 4)
nt, size = ip4.unpack(b)
- self.assertEqual(str(nt), '1.1.1.1')
+ self.assertEqual(str(nt), "1.1.1.1")
- b = ip6.pack(inet_pton(AF_INET6, '1::1'))
+ b = ip6.pack(inet_pton(AF_INET6, "1::1"))
self.assertEqual(len(b), 16)
- b = address.pack({'af': af.ADDRESS_IP4,
- 'un':
- {'ip4': inet_pton(AF_INET, '2.2.2.2')}})
+ b = address.pack(
+ {"af": af.ADDRESS_IP4, "un": {"ip4": inet_pton(AF_INET, "2.2.2.2")}}
+ )
self.assertEqual(len(b), 20)
nt, size = address.unpack(b)
- self.assertEqual(str(nt), '2.2.2.2')
+ self.assertEqual(str(nt), "2.2.2.2")
# List of addresses
address_list = []
for i in range(4):
- address_list.append({'af': af.ADDRESS_IP4,
- 'un':
- {'ip4': inet_pton(AF_INET, '2.2.2.2')}})
- b = va_address_list.pack({'count': len(address_list),
- 'addresses': address_list})
+ address_list.append(
+ {"af": af.ADDRESS_IP4, "un": {"ip4": inet_pton(AF_INET, "2.2.2.2")}}
+ )
+ b = va_address_list.pack(
+ {"count": len(address_list), "addresses": address_list}
+ )
self.assertEqual(len(b), 81)
nt, size = va_address_list.unpack(b)
- self.assertEqual(str(nt.addresses[0]), '2.2.2.2')
-
- b = message_with_va_address_list.pack({'vla_address':
- {'count': len(address_list),
- 'addresses': address_list},
- 'is_cool': 100})
+ self.assertEqual(str(nt.addresses[0]), "2.2.2.2")
+
+ b = message_with_va_address_list.pack(
+ {
+ "vla_address": {"count": len(address_list), "addresses": address_list},
+ "is_cool": 100,
+ }
+ )
self.assertEqual(len(b), 82)
nt, size = message_with_va_address_list.unpack(b)
self.assertEqual(nt.is_cool, 100)
def test_address_with_prefix(self):
- af = VPPEnumType('vl_api_address_family_t', [["ADDRESS_IP4", 0],
- ["ADDRESS_IP6", 1],
- {"enumtype": "u32"}])
- ip4 = VPPTypeAlias('vl_api_ip4_address_t', {'type': 'u8',
- 'length': 4})
- ip6 = VPPTypeAlias('vl_api_ip6_address_t', {'type': 'u8',
- 'length': 16})
- VPPUnionType('vl_api_address_union_t',
- [["vl_api_ip4_address_t", "ip4"],
- ["vl_api_ip6_address_t", "ip6"]])
-
- address = VPPType('vl_api_address_t',
- [['vl_api_address_family_t', 'af'],
- ['vl_api_address_union_t', 'un']])
-
- prefix = VPPType('vl_api_prefix_t',
- [['vl_api_address_t', 'address'],
- ['u8', 'len']])
- prefix4 = VPPType('vl_api_ip4_prefix_t',
- [['vl_api_ip4_address_t', 'address'],
- ['u8', 'len']])
- prefix6 = VPPType('vl_api_ip6_prefix_t',
- [['vl_api_ip6_address_t', 'address'],
- ['u8', 'len']])
-
- address_with_prefix = VPPTypeAlias('vl_api_address_with_prefix_t', {'type': 'vl_api_prefix_t' })
- address4_with_prefix = VPPTypeAlias('vl_api_ip4_address_with_prefix_t',
- {'type': 'vl_api_ip4_prefix_t' })
- address6_with_prefix = VPPTypeAlias('vl_api_ip6_address_with_prefix_t',
- {'type': 'vl_api_ip6_prefix_t' })
-
- awp_type = VPPType('foobar_t',
- [['vl_api_address_with_prefix_t', 'address']])
+ af = VPPEnumType(
+ "vl_api_address_family_t",
+ [["ADDRESS_IP4", 0], ["ADDRESS_IP6", 1], {"enumtype": "u32"}],
+ )
+ ip4 = VPPTypeAlias("vl_api_ip4_address_t", {"type": "u8", "length": 4})
+ ip6 = VPPTypeAlias("vl_api_ip6_address_t", {"type": "u8", "length": 16})
+ VPPUnionType(
+ "vl_api_address_union_t",
+ [["vl_api_ip4_address_t", "ip4"], ["vl_api_ip6_address_t", "ip6"]],
+ )
+
+ address = VPPType(
+ "vl_api_address_t",
+ [["vl_api_address_family_t", "af"], ["vl_api_address_union_t", "un"]],
+ )
+
+ prefix = VPPType(
+ "vl_api_prefix_t", [["vl_api_address_t", "address"], ["u8", "len"]]
+ )
+ prefix4 = VPPType(
+ "vl_api_ip4_prefix_t", [["vl_api_ip4_address_t", "address"], ["u8", "len"]]
+ )
+ prefix6 = VPPType(
+ "vl_api_ip6_prefix_t", [["vl_api_ip6_address_t", "address"], ["u8", "len"]]
+ )
+
+ address_with_prefix = VPPTypeAlias(
+ "vl_api_address_with_prefix_t", {"type": "vl_api_prefix_t"}
+ )
+ address4_with_prefix = VPPTypeAlias(
+ "vl_api_ip4_address_with_prefix_t", {"type": "vl_api_ip4_prefix_t"}
+ )
+ address6_with_prefix = VPPTypeAlias(
+ "vl_api_ip6_address_with_prefix_t", {"type": "vl_api_ip6_prefix_t"}
+ )
+
+ awp_type = VPPType("foobar_t", [["vl_api_address_with_prefix_t", "address"]])
# address with prefix
- b = address_with_prefix.pack(IPv4Interface('2.2.2.2/24'))
+ b = address_with_prefix.pack(IPv4Interface("2.2.2.2/24"))
self.assertEqual(len(b), 21)
nt, size = address_with_prefix.unpack(b)
self.assertTrue(isinstance(nt, IPv4Interface))
- self.assertEqual(str(nt), '2.2.2.2/24')
+ self.assertEqual(str(nt), "2.2.2.2/24")
- b = address_with_prefix.pack(IPv6Interface('2::2/64'))
+ b = address_with_prefix.pack(IPv6Interface("2::2/64"))
self.assertEqual(len(b), 21)
nt, size = address_with_prefix.unpack(b)
self.assertTrue(isinstance(nt, IPv6Interface))
- self.assertEqual(str(nt), '2::2/64')
+ self.assertEqual(str(nt), "2::2/64")
- b = address_with_prefix.pack(IPv4Network('2.2.2.2/24', strict=False))
+ b = address_with_prefix.pack(IPv4Network("2.2.2.2/24", strict=False))
self.assertEqual(len(b), 21)
nt, size = address_with_prefix.unpack(b)
self.assertTrue(isinstance(nt, IPv4Interface))
- self.assertEqual(str(nt), '2.2.2.0/24')
+ self.assertEqual(str(nt), "2.2.2.0/24")
- b = address4_with_prefix.pack('2.2.2.2/24')
+ b = address4_with_prefix.pack("2.2.2.2/24")
self.assertEqual(len(b), 5)
nt, size = address4_with_prefix.unpack(b)
self.assertTrue(isinstance(nt, IPv4Interface))
- self.assertEqual(str(nt), '2.2.2.2/24')
- b = address4_with_prefix.pack(IPv4Interface('2.2.2.2/24'))
+ self.assertEqual(str(nt), "2.2.2.2/24")
+ b = address4_with_prefix.pack(IPv4Interface("2.2.2.2/24"))
self.assertEqual(len(b), 5)
- b = address6_with_prefix.pack('2::2/64')
+ b = address6_with_prefix.pack("2::2/64")
self.assertEqual(len(b), 17)
nt, size = address6_with_prefix.unpack(b)
self.assertTrue(isinstance(nt, IPv6Interface))
- self.assertEqual(str(nt), '2::2/64')
- b = address6_with_prefix.pack(IPv6Interface('2::2/64'))
+ self.assertEqual(str(nt), "2::2/64")
+ b = address6_with_prefix.pack(IPv6Interface("2::2/64"))
self.assertEqual(len(b), 17)
- b = prefix.pack('192.168.10.0/24')
+ b = prefix.pack("192.168.10.0/24")
self.assertEqual(len(b), 21)
nt, size = prefix.unpack(b)
self.assertTrue(isinstance(nt, IPv4Network))
- self.assertEqual(str(nt), '192.168.10.0/24')
+ self.assertEqual(str(nt), "192.168.10.0/24")
- b = awp_type.pack({'address': '1.2.3.4/24'})
+ b = awp_type.pack({"address": "1.2.3.4/24"})
self.assertEqual(len(b), 21)
nt, size = awp_type.unpack(b)
self.assertTrue(isinstance(nt.address, IPv4Interface))
- self.assertEqual(str(nt.address), '1.2.3.4/24')
+ self.assertEqual(str(nt.address), "1.2.3.4/24")
- b = awp_type.pack({'address': IPv4Interface('1.2.3.4/24')})
+ b = awp_type.pack({"address": IPv4Interface("1.2.3.4/24")})
self.assertEqual(len(b), 21)
nt, size = awp_type.unpack(b)
self.assertTrue(isinstance(nt.address, IPv4Interface))
- self.assertEqual(str(nt.address), '1.2.3.4/24')
+ self.assertEqual(str(nt.address), "1.2.3.4/24")
def test_recursive_address(self):
- af = VPPEnumType('vl_api_address_family_t', [["ADDRESS_IP4", 0],
- ["ADDRESS_IP6", 1],
- {"enumtype": "u32"}])
- ip4 = VPPTypeAlias('vl_api_ip4_address_t', {'type': 'u8',
- 'length': 4})
- b = ip4.pack('1.1.1.1')
+ af = VPPEnumType(
+ "vl_api_address_family_t",
+ [["ADDRESS_IP4", 0], ["ADDRESS_IP6", 1], {"enumtype": "u32"}],
+ )
+ ip4 = VPPTypeAlias("vl_api_ip4_address_t", {"type": "u8", "length": 4})
+ b = ip4.pack("1.1.1.1")
self.assertEqual(len(b), 4)
nt, size = ip4.unpack(b)
- self.assertEqual(str(nt), '1.1.1.1')
+ self.assertEqual(str(nt), "1.1.1.1")
- ip6 = VPPTypeAlias('vl_api_ip6_address_t', {'type': 'u8',
- 'length': 16})
- VPPUnionType('vl_api_address_union_t',
- [["vl_api_ip4_address_t", "ip4"],
- ["vl_api_ip6_address_t", "ip6"]])
+ ip6 = VPPTypeAlias("vl_api_ip6_address_t", {"type": "u8", "length": 16})
+ VPPUnionType(
+ "vl_api_address_union_t",
+ [["vl_api_ip4_address_t", "ip4"], ["vl_api_ip6_address_t", "ip6"]],
+ )
- address = VPPType('vl_api_address_t',
- [['vl_api_address_family_t', 'af'],
- ['vl_api_address_union_t', 'un']])
+ address = VPPType(
+ "vl_api_address_t",
+ [["vl_api_address_family_t", "af"], ["vl_api_address_union_t", "un"]],
+ )
- prefix = VPPType('vl_api_prefix_t',
- [['vl_api_address_t', 'address'],
- ['u8', 'len']])
- message = VPPMessage('svs',
- [['vl_api_prefix_t', 'prefix']])
- message_addr = VPPMessage('svs_address',
- [['vl_api_address_t', 'address']])
+ prefix = VPPType(
+ "vl_api_prefix_t", [["vl_api_address_t", "address"], ["u8", "len"]]
+ )
+ message = VPPMessage("svs", [["vl_api_prefix_t", "prefix"]])
+ message_addr = VPPMessage("svs_address", [["vl_api_address_t", "address"]])
- b = message_addr.pack({'address': "1::1"})
+ b = message_addr.pack({"address": "1::1"})
self.assertEqual(len(b), 20)
nt, size = message_addr.unpack(b)
self.assertEqual("1::1", str(nt.address))
- b = message_addr.pack({'address': "1.1.1.1"})
+ b = message_addr.pack({"address": "1.1.1.1"})
self.assertEqual(len(b), 20)
nt, size = message_addr.unpack(b)
self.assertEqual("1.1.1.1", str(nt.address))
- b = message.pack({'prefix': "1.1.1.0/24"})
+ b = message.pack({"prefix": "1.1.1.0/24"})
self.assertEqual(len(b), 21)
nt, size = message.unpack(b)
self.assertEqual("1.1.1.0/24", str(nt.prefix))
- message_array = VPPMessage('address_array',
- [['vl_api_ip6_address_t',
- 'addresses', 2]])
- b = message_array.pack({'addresses': [IPv6Address(u"1::1"), "2::2"]})
+ message_array = VPPMessage(
+ "address_array", [["vl_api_ip6_address_t", "addresses", 2]]
+ )
+ b = message_array.pack({"addresses": [IPv6Address("1::1"), "2::2"]})
self.assertEqual(len(b), 32)
- message_array_vla = VPPMessage('address_array_vla',
- [['u32', 'num'],
- ['vl_api_ip6_address_t',
- 'addresses', 0, 'num']])
- b = message_array_vla.pack({'addresses': ["1::1", "2::2"], 'num': 2})
+ message_array_vla = VPPMessage(
+ "address_array_vla",
+ [["u32", "num"], ["vl_api_ip6_address_t", "addresses", 0, "num"]],
+ )
+ b = message_array_vla.pack({"addresses": ["1::1", "2::2"], "num": 2})
self.assertEqual(len(b), 36)
- message_array4 = VPPMessage('address_array4',
- [['vl_api_ip4_address_t',
- 'addresses', 2]])
- b = message_array4.pack({'addresses': ["1.1.1.1", "2.2.2.2"]})
+ message_array4 = VPPMessage(
+ "address_array4", [["vl_api_ip4_address_t", "addresses", 2]]
+ )
+ b = message_array4.pack({"addresses": ["1.1.1.1", "2.2.2.2"]})
self.assertEqual(len(b), 8)
- b = message_array4.pack({'addresses': [IPv4Address(u"1.1.1.1"),
- "2.2.2.2"]})
+ b = message_array4.pack({"addresses": [IPv4Address("1.1.1.1"), "2.2.2.2"]})
self.assertEqual(len(b), 8)
- message = VPPMessage('address', [['vl_api_address_t', 'address']])
- b = message.pack({'address': '1::1'})
+ message = VPPMessage("address", [["vl_api_address_t", "address"]])
+ b = message.pack({"address": "1::1"})
self.assertEqual(len(b), 20)
- b = message.pack({'address': '1.1.1.1'})
+ b = message.pack({"address": "1.1.1.1"})
self.assertEqual(len(b), 20)
- message = VPPMessage('prefix', [['vl_api_prefix_t', 'prefix']])
- b = message.pack({'prefix': '1::1/130'})
+ message = VPPMessage("prefix", [["vl_api_prefix_t", "prefix"]])
+ b = message.pack({"prefix": "1::1/130"})
self.assertEqual(len(b), 21)
- b = message.pack({'prefix': IPv6Network(u'1::/119')})
+ b = message.pack({"prefix": IPv6Network("1::/119")})
self.assertEqual(len(b), 21)
- b = message.pack({'prefix': IPv4Network(u'1.1.0.0/16')})
+ b = message.pack({"prefix": IPv4Network("1.1.0.0/16")})
self.assertEqual(len(b), 21)
def test_zero_vla(self):
- '''Default zero'ed out for VLAs'''
- list = VPPType('vl_api_list_t',
- [['u8', 'count', 10]])
+ """Default zero'ed out for VLAs"""
+ list = VPPType("vl_api_list_t", [["u8", "count", 10]])
# Define an embedded VLA type
- valist = VPPType('vl_api_valist_t',
- [['u8', 'count'],
- ['u8', 'string', 0, 'count']])
+ valist = VPPType(
+ "vl_api_valist_t", [["u8", "count"], ["u8", "string", 0, "count"]]
+ )
# Define a message
- vamessage = VPPMessage('vamsg',
- [['vl_api_valist_t', 'valist'],
- ['u8', 'is_something']])
+ vamessage = VPPMessage(
+ "vamsg", [["vl_api_valist_t", "valist"], ["u8", "is_something"]]
+ )
- message = VPPMessage('msg',
- [['vl_api_list_t', 'list'],
- ['u8', 'is_something']])
+ message = VPPMessage("msg", [["vl_api_list_t", "list"], ["u8", "is_something"]])
# Pack message without VLA specified
- b = message.pack({'is_something': 1})
- b = vamessage.pack({'is_something': 1})
+ b = message.pack({"is_something": 1})
+ b = vamessage.pack({"is_something": 1})
def test_arrays(self):
# Test cases
@@ -382,254 +380,275 @@ class TestAddType(unittest.TestCase):
# 2. Fixed list of variable length sub type
# 3. Variable length type
#
- s = VPPType('str', [['u32', 'length'],
- ['u8', 'string', 0, 'length']])
+ s = VPPType("str", [["u32", "length"], ["u8", "string", 0, "length"]])
- ip4 = VPPType('ip4_address', [['u8', 'address', 4]])
- listip4 = VPPType('list_ip4_t', [['ip4_address', 'addresses', 4]])
- valistip4 = VPPType('list_ip4_t',
- [['u8', 'count'],
- ['ip4_address', 'addresses', 0, 'count']])
+ ip4 = VPPType("ip4_address", [["u8", "address", 4]])
+ listip4 = VPPType("list_ip4_t", [["ip4_address", "addresses", 4]])
+ valistip4 = VPPType(
+ "list_ip4_t", [["u8", "count"], ["ip4_address", "addresses", 0, "count"]]
+ )
- valistip4_legacy = VPPType('list_ip4_t',
- [['u8', 'foo'],
- ['ip4_address', 'addresses', 0]])
+ valistip4_legacy = VPPType(
+ "list_ip4_t", [["u8", "foo"], ["ip4_address", "addresses", 0]]
+ )
addresses = []
for i in range(4):
- addresses.append({'address': inet_pton(AF_INET, '2.2.2.2')})
- b = listip4.pack({'addresses': addresses})
+ addresses.append({"address": inet_pton(AF_INET, "2.2.2.2")})
+ b = listip4.pack({"addresses": addresses})
self.assertEqual(len(b), 16)
nt, size = listip4.unpack(b)
- self.assertEqual(nt.addresses[0].address,
- inet_pton(AF_INET, '2.2.2.2'))
+ self.assertEqual(nt.addresses[0].address, inet_pton(AF_INET, "2.2.2.2"))
- b = valistip4.pack({'count': len(addresses), 'addresses': addresses})
+ b = valistip4.pack({"count": len(addresses), "addresses": addresses})
self.assertEqual(len(b), 17)
nt, size = valistip4.unpack(b)
self.assertEqual(nt.count, 4)
- self.assertEqual(nt.addresses[0].address,
- inet_pton(AF_INET, '2.2.2.2'))
+ self.assertEqual(nt.addresses[0].address, inet_pton(AF_INET, "2.2.2.2"))
- b = valistip4_legacy.pack({'foo': 1, 'addresses': addresses})
+ b = valistip4_legacy.pack({"foo": 1, "addresses": addresses})
self.assertEqual(len(b), 17)
nt, size = valistip4_legacy.unpack(b)
self.assertEqual(len(nt.addresses), 4)
- self.assertEqual(nt.addresses[0].address,
- inet_pton(AF_INET, '2.2.2.2'))
+ self.assertEqual(nt.addresses[0].address, inet_pton(AF_INET, "2.2.2.2"))
- string = 'foobar foobar'
- b = s.pack({'length': len(string), 'string': string.encode('utf-8')})
+ string = "foobar foobar"
+ b = s.pack({"length": len(string), "string": string.encode("utf-8")})
nt, size = s.unpack(b)
self.assertEqual(len(b), size)
def test_string(self):
- s = VPPType('str', [['u32', 'length'],
- ['u8', 'string', 0, 'length']])
+ s = VPPType("str", [["u32", "length"], ["u8", "string", 0, "length"]])
- string = ''
- b = s.pack({'length': len(string), 'string': string.encode('utf-8')})
+ string = ""
+ b = s.pack({"length": len(string), "string": string.encode("utf-8")})
nt, size = s.unpack(b)
self.assertEqual(len(b), size)
def test_message(self):
- foo = VPPMessage('foo', [['u16', '_vl_msg_id'],
- ['u8', 'client_index'],
- ['u8', 'something'],
- {"crc": "0x559b9f3c"}])
- b = foo.pack({'_vl_msg_id': 1, 'client_index': 5,
- 'something': 200})
+ foo = VPPMessage(
+ "foo",
+ [
+ ["u16", "_vl_msg_id"],
+ ["u8", "client_index"],
+ ["u8", "something"],
+ {"crc": "0x559b9f3c"},
+ ],
+ )
+ b = foo.pack({"_vl_msg_id": 1, "client_index": 5, "something": 200})
nt, size = foo.unpack(b)
self.assertEqual(len(b), size)
self.assertEqual(nt.something, 200)
def test_abf(self):
- fib_mpls_label = VPPType('vl_api_fib_mpls_label_t',
- [['u8', 'is_uniform'],
- ['u32', 'label'],
- ['u8', 'ttl'],
- ['u8', 'exp']])
+ fib_mpls_label = VPPType(
+ "vl_api_fib_mpls_label_t",
+ [["u8", "is_uniform"], ["u32", "label"], ["u8", "ttl"], ["u8", "exp"]],
+ )
- label_stack = {'is_uniform': 0,
- 'label': 0,
- 'ttl': 0,
- 'exp': 0}
+ label_stack = {"is_uniform": 0, "label": 0, "ttl": 0, "exp": 0}
b = fib_mpls_label.pack(label_stack)
self.assertEqual(len(b), 7)
- fib_path = VPPType('vl_api_fib_path_t',
- [['u32', 'sw_if_index'],
- ['u32', 'table_id'],
- ['u8', 'weight'],
- ['u8', 'preference'],
- ['u8', 'is_local'],
- ['u8', 'is_drop'],
- ['u8', 'is_udp_encap'],
- ['u8', 'is_unreach'],
- ['u8', 'is_prohibit'],
- ['u8', 'is_resolve_host'],
- ['u8', 'is_resolve_attached'],
- ['u8', 'is_dvr'],
- ['u8', 'is_source_lookup'],
- ['u8', 'afi'],
- ['u8', 'next_hop', 16],
- ['u32', 'next_hop_id'],
- ['u32', 'rpf_id'],
- ['u32', 'via_label'],
- ['u8', 'n_labels'],
- ['vl_api_fib_mpls_label_t', 'label_stack', 16]])
+ fib_path = VPPType(
+ "vl_api_fib_path_t",
+ [
+ ["u32", "sw_if_index"],
+ ["u32", "table_id"],
+ ["u8", "weight"],
+ ["u8", "preference"],
+ ["u8", "is_local"],
+ ["u8", "is_drop"],
+ ["u8", "is_udp_encap"],
+ ["u8", "is_unreach"],
+ ["u8", "is_prohibit"],
+ ["u8", "is_resolve_host"],
+ ["u8", "is_resolve_attached"],
+ ["u8", "is_dvr"],
+ ["u8", "is_source_lookup"],
+ ["u8", "afi"],
+ ["u8", "next_hop", 16],
+ ["u32", "next_hop_id"],
+ ["u32", "rpf_id"],
+ ["u32", "via_label"],
+ ["u8", "n_labels"],
+ ["vl_api_fib_mpls_label_t", "label_stack", 16],
+ ],
+ )
label_stack_list = []
for i in range(16):
label_stack_list.append(label_stack)
- paths = {'is_udp_encap': 0,
- 'next_hop': b'\x10\x02\x02\xac',
- 'table_id': 0,
- 'afi': 0,
- 'weight': 1,
- 'next_hop_id': 4294967295,
- 'label_stack': label_stack_list,
- 'n_labels': 0,
- 'sw_if_index': 4294967295,
- 'preference': 0}
+ paths = {
+ "is_udp_encap": 0,
+ "next_hop": b"\x10\x02\x02\xac",
+ "table_id": 0,
+ "afi": 0,
+ "weight": 1,
+ "next_hop_id": 4294967295,
+ "label_stack": label_stack_list,
+ "n_labels": 0,
+ "sw_if_index": 4294967295,
+ "preference": 0,
+ }
b = fib_path.pack(paths)
- self.assertEqual(len(b), (7*16) + 49)
+ self.assertEqual(len(b), (7 * 16) + 49)
- abf_policy = VPPType('vl_api_abf_policy_t',
- [['u32', 'policy_id'],
- ['u32', 'acl_index'],
- ['u8', 'n_paths'],
- ['vl_api_fib_path_t', 'paths', 0, 'n_paths']])
+ abf_policy = VPPType(
+ "vl_api_abf_policy_t",
+ [
+ ["u32", "policy_id"],
+ ["u32", "acl_index"],
+ ["u8", "n_paths"],
+ ["vl_api_fib_path_t", "paths", 0, "n_paths"],
+ ],
+ )
- policy = {
- 'n_paths': 1,
- 'paths': [paths],
- 'acl_index': 0,
- 'policy_id': 10}
+ policy = {"n_paths": 1, "paths": [paths], "acl_index": 0, "policy_id": 10}
b = abf_policy.pack(policy)
- self.assertEqual(len(b), (7*16) + 49 + 9)
-
- abf_policy_add_del = VPPMessage('abf_policy_add_del',
- [['u16', '_vl_msg_id'],
- ['u32', 'client_index'],
- ['u32', 'context'],
- ['u8', 'is_add'],
- ['vl_api_abf_policy_t', 'policy']])
-
- b = abf_policy_add_del.pack({'is_add': 1,
- 'context': 66,
- '_vl_msg_id': 1066,
- 'policy': policy})
+ self.assertEqual(len(b), (7 * 16) + 49 + 9)
+
+ abf_policy_add_del = VPPMessage(
+ "abf_policy_add_del",
+ [
+ ["u16", "_vl_msg_id"],
+ ["u32", "client_index"],
+ ["u32", "context"],
+ ["u8", "is_add"],
+ ["vl_api_abf_policy_t", "policy"],
+ ],
+ )
+
+ b = abf_policy_add_del.pack(
+ {"is_add": 1, "context": 66, "_vl_msg_id": 1066, "policy": policy}
+ )
nt, size = abf_policy_add_del.unpack(b)
- self.assertEqual(nt.policy.paths[0].next_hop,
- b'\x10\x02\x02\xac\x00\x00\x00\x00'
- b'\x00\x00\x00\x00\x00\x00\x00\x00')
+ self.assertEqual(
+ nt.policy.paths[0].next_hop,
+ b"\x10\x02\x02\xac\x00\x00\x00\x00" b"\x00\x00\x00\x00\x00\x00\x00\x00",
+ )
def test_bier(self):
- bier_table_id = VPPType('vl_api_bier_table_id_t',
- [['u8', 'bt_set'],
- ['u8', 'bt_sub_domain'],
- ['u8', 'bt_hdr_len_id']])
+ bier_table_id = VPPType(
+ "vl_api_bier_table_id_t",
+ [["u8", "bt_set"], ["u8", "bt_sub_domain"], ["u8", "bt_hdr_len_id"]],
+ )
- bier_imp_add = VPPMessage('bier_imp_add',
- [['u32', 'client_index'],
- ['u32', 'context'],
- ['vl_api_bier_table_id_t', 'bi_tbl_id'],
- ['u16', 'bi_src'],
- ['u8', 'bi_n_bytes'],
- ['u8', 'bi_bytes', 0, 'bi_n_bytes']])
+ bier_imp_add = VPPMessage(
+ "bier_imp_add",
+ [
+ ["u32", "client_index"],
+ ["u32", "context"],
+ ["vl_api_bier_table_id_t", "bi_tbl_id"],
+ ["u16", "bi_src"],
+ ["u8", "bi_n_bytes"],
+ ["u8", "bi_bytes", 0, "bi_n_bytes"],
+ ],
+ )
- table_id = {'bt_set': 0,
- 'bt_sub_domain': 0,
- 'bt_hdr_len_id': 0}
+ table_id = {"bt_set": 0, "bt_sub_domain": 0, "bt_hdr_len_id": 0}
- bibytes = b'foobar'
+ bibytes = b"foobar"
- b = bier_imp_add.pack({'bi_tbl_id': table_id,
- 'bi_n_bytes': len(bibytes),
- 'bi_bytes': bibytes})
+ b = bier_imp_add.pack(
+ {"bi_tbl_id": table_id, "bi_n_bytes": len(bibytes), "bi_bytes": bibytes}
+ )
self.assertEqual(len(b), 20)
def test_lisp(self):
- VPPEnumType('vl_api_eid_type_t',
- [["EID_TYPE_API_PREFIX", 0],
- ["EID_TYPE_API_MAC", 1],
- ["EID_TYPE_API_NSH", 2],
- {"enumtype": "u32"}])
-
- VPPTypeAlias('vl_api_mac_address_t', {'type': 'u8',
- 'length': 6})
-
- VPPType('vl_api_nsh_t',
- [["u32", "spi"],
- ["u8", "si"]])
-
- VPPEnumType('vl_api_address_family_t', [["ADDRESS_IP4", 0],
- ["ADDRESS_IP6", 1],
- {"enumtype": "u32"}])
- VPPTypeAlias('vl_api_ip4_address_t', {'type': 'u8',
- 'length': 4})
- VPPTypeAlias('vl_api_ip6_address_t', {'type': 'u8',
- 'length': 16})
- VPPUnionType('vl_api_address_union_t',
- [["vl_api_ip4_address_t", "ip4"],
- ["vl_api_ip6_address_t", "ip6"]])
-
- VPPType('vl_api_address_t',
- [['vl_api_address_family_t', 'af'],
- ['vl_api_address_union_t', 'un']])
-
- VPPType('vl_api_prefix_t',
- [['vl_api_address_t', 'address'],
- ['u8', 'len']])
-
- VPPUnionType('vl_api_eid_address_t',
- [["vl_api_prefix_t", "prefix"],
- ["vl_api_mac_address_t", "mac"],
- ["vl_api_nsh_t", "nsh"]])
-
- eid = VPPType('vl_api_eid_t',
- [["vl_api_eid_type_t", "type"],
- ["vl_api_eid_address_t", "address"]])
-
- b = eid.pack({'type':1,
- 'address': {
- 'mac': MACAddress('aa:bb:cc:dd:ee:ff')}})
+ VPPEnumType(
+ "vl_api_eid_type_t",
+ [
+ ["EID_TYPE_API_PREFIX", 0],
+ ["EID_TYPE_API_MAC", 1],
+ ["EID_TYPE_API_NSH", 2],
+ {"enumtype": "u32"},
+ ],
+ )
+
+ VPPTypeAlias("vl_api_mac_address_t", {"type": "u8", "length": 6})
+
+ VPPType("vl_api_nsh_t", [["u32", "spi"], ["u8", "si"]])
+
+ VPPEnumType(
+ "vl_api_address_family_t",
+ [["ADDRESS_IP4", 0], ["ADDRESS_IP6", 1], {"enumtype": "u32"}],
+ )
+ VPPTypeAlias("vl_api_ip4_address_t", {"type": "u8", "length": 4})
+ VPPTypeAlias("vl_api_ip6_address_t", {"type": "u8", "length": 16})
+ VPPUnionType(
+ "vl_api_address_union_t",
+ [["vl_api_ip4_address_t", "ip4"], ["vl_api_ip6_address_t", "ip6"]],
+ )
+
+ VPPType(
+ "vl_api_address_t",
+ [["vl_api_address_family_t", "af"], ["vl_api_address_union_t", "un"]],
+ )
+
+ VPPType("vl_api_prefix_t", [["vl_api_address_t", "address"], ["u8", "len"]])
+
+ VPPUnionType(
+ "vl_api_eid_address_t",
+ [
+ ["vl_api_prefix_t", "prefix"],
+ ["vl_api_mac_address_t", "mac"],
+ ["vl_api_nsh_t", "nsh"],
+ ],
+ )
+
+ eid = VPPType(
+ "vl_api_eid_t",
+ [["vl_api_eid_type_t", "type"], ["vl_api_eid_address_t", "address"]],
+ )
+
+ b = eid.pack({"type": 1, "address": {"mac": MACAddress("aa:bb:cc:dd:ee:ff")}})
self.assertEqual(len(b), 25)
nt, size = eid.unpack(b)
- self.assertEqual(str(nt.address.mac), 'aa:bb:cc:dd:ee:ff')
+ self.assertEqual(str(nt.address.mac), "aa:bb:cc:dd:ee:ff")
self.assertIsNone(nt.address.prefix)
class TestVppSerializerLogging(unittest.TestCase):
-
def test_logger(self):
# test logger name 'vpp_papi.serializer'
with self.assertRaises(VPPSerializerValueError) as ctx:
- with self.assertLogs('vpp_papi.serializer', level='DEBUG') as cm:
- u = VPPUnionType('vl_api_eid_address_t',
- [["vl_api_prefix_t", "prefix"],
- ["vl_api_mac_address_t", "mac"],
- ["vl_api_nsh_t", "nsh"]])
- self.assertEqual(cm.output, ["DEBUG:vpp_papi.serializer:Unknown union type vl_api_prefix_t"])
+ with self.assertLogs("vpp_papi.serializer", level="DEBUG") as cm:
+ u = VPPUnionType(
+ "vl_api_eid_address_t",
+ [
+ ["vl_api_prefix_t", "prefix"],
+ ["vl_api_mac_address_t", "mac"],
+ ["vl_api_nsh_t", "nsh"],
+ ],
+ )
+ self.assertEqual(
+ cm.output, ["DEBUG:vpp_papi.serializer:Unknown union type vl_api_prefix_t"]
+ )
# test parent logger name 'vpp_papi'
with self.assertRaises(VPPSerializerValueError) as ctx:
- with self.assertLogs('vpp_papi', level='DEBUG') as cm:
- u = VPPUnionType('vl_api_eid_address_t',
- [["vl_api_prefix_t", "prefix"],
- ["vl_api_mac_address_t", "mac"],
- ["vl_api_nsh_t", "nsh"]])
- self.assertEqual(cm.output, ["DEBUG:vpp_papi.serializer:Unknown union type vl_api_prefix_t"])
-
-
-if __name__ == '__main__':
+ with self.assertLogs("vpp_papi", level="DEBUG") as cm:
+ u = VPPUnionType(
+ "vl_api_eid_address_t",
+ [
+ ["vl_api_prefix_t", "prefix"],
+ ["vl_api_mac_address_t", "mac"],
+ ["vl_api_nsh_t", "nsh"],
+ ],
+ )
+ self.assertEqual(
+ cm.output, ["DEBUG:vpp_papi.serializer:Unknown union type vl_api_prefix_t"]
+ )
+
+
+if __name__ == "__main__":
unittest.main()
diff --git a/src/vpp-api/python/vpp_papi/vpp_format.py b/src/vpp-api/python/vpp_papi/vpp_format.py
index 0b85eb4fcb6..f80a781c753 100644
--- a/src/vpp-api/python/vpp_papi/vpp_format.py
+++ b/src/vpp-api/python/vpp_papi/vpp_format.py
@@ -25,8 +25,8 @@ ADDRESS_IP6 = 1
def verify_enum_hint(e):
- return (e.ADDRESS_IP4.value == ADDRESS_IP4) and\
- (e.ADDRESS_IP6.value == ADDRESS_IP6)
+ return (e.ADDRESS_IP4.value == ADDRESS_IP4) and (e.ADDRESS_IP6.value == ADDRESS_IP6)
+
#
# Type conversion for input arguments and return values
@@ -35,146 +35,128 @@ def verify_enum_hint(e):
def format_vl_api_address_t(args):
try:
- return {'un': {'ip6': inet_pton(AF_INET6, args)},
- 'af': ADDRESS_IP6}
+ return {"un": {"ip6": inet_pton(AF_INET6, args)}, "af": ADDRESS_IP6}
# PY2: raises socket.error
# PY3: raises OSError
except (socket.error, OSError):
- return {'un': {'ip4': inet_pton(AF_INET, args)},
- 'af': ADDRESS_IP4}
+ return {"un": {"ip4": inet_pton(AF_INET, args)}, "af": ADDRESS_IP4}
def format_vl_api_prefix_t(args):
if isinstance(args, (ipaddress.IPv4Network, ipaddress.IPv6Network)):
- return {'address': format_vl_api_address_t(
- str(args.network_address)),
- 'len': int(args.prefixlen)}
- p, length = args.split('/')
- return {'address': format_vl_api_address_t(p),
- 'len': int(length)}
+ return {
+ "address": format_vl_api_address_t(str(args.network_address)),
+ "len": int(args.prefixlen),
+ }
+ p, length = args.split("/")
+ return {"address": format_vl_api_address_t(p), "len": int(length)}
def format_vl_api_address_with_prefix_t(args):
if isinstance(args, (ipaddress.IPv4Interface, ipaddress.IPv6Interface)):
- return {'address': format_vl_api_address_t(
- str(args.network_address)),
- 'len': int(args.prefixlen)}
- p, length = args.split('/')
- return {'address': format_vl_api_address_t(p),
- 'len': int(length)}
+ return {
+ "address": format_vl_api_address_t(str(args.network_address)),
+ "len": int(args.prefixlen),
+ }
+ p, length = args.split("/")
+ return {"address": format_vl_api_address_t(p), "len": int(length)}
def format_vl_api_ip6_prefix_t(args):
if isinstance(args, ipaddress.IPv6Network):
- return {'address': args.network_address.packed,
- 'len': int(args.prefixlen)}
- p, length = args.split('/')
- return {'address': inet_pton(AF_INET6, p),
- 'len': int(length)}
+ return {"address": args.network_address.packed, "len": int(args.prefixlen)}
+ p, length = args.split("/")
+ return {"address": inet_pton(AF_INET6, p), "len": int(length)}
def format_vl_api_ip6_address_with_prefix_t(args):
if isinstance(args, ipaddress.IPv6Interface):
- return {'address': args.network_address.packed,
- 'len': int(args.prefixlen)}
- p, length = args.split('/')
- return {'address': inet_pton(AF_INET6, p),
- 'len': int(length)}
+ return {"address": args.network_address.packed, "len": int(args.prefixlen)}
+ p, length = args.split("/")
+ return {"address": inet_pton(AF_INET6, p), "len": int(length)}
def format_vl_api_ip4_prefix_t(args):
if isinstance(args, ipaddress.IPv4Network):
- return {'address': args.network_address.packed,
- 'len': int(args.prefixlen)}
- p, length = args.split('/')
- return {'address': inet_pton(AF_INET, p),
- 'len': int(length)}
+ return {"address": args.network_address.packed, "len": int(args.prefixlen)}
+ p, length = args.split("/")
+ return {"address": inet_pton(AF_INET, p), "len": int(length)}
def format_vl_api_ip4_address_with_prefix_t(args):
if isinstance(args, ipaddress.IPv4Interface):
- return {'address': args.network_address.packed,
- 'len': int(args.prefixlen)}
- p, length = args.split('/')
- return {'address': inet_pton(AF_INET, p),
- 'len': int(length)}
+ return {"address": args.network_address.packed, "len": int(args.prefixlen)}
+ p, length = args.split("/")
+ return {"address": inet_pton(AF_INET, p), "len": int(length)}
conversion_table = {
- 'vl_api_ip6_address_t':
- {
- 'IPv6Address': lambda o: o.packed,
- 'str': lambda s: inet_pton(AF_INET6, s)
+ "vl_api_ip6_address_t": {
+ "IPv6Address": lambda o: o.packed,
+ "str": lambda s: inet_pton(AF_INET6, s),
+ },
+ "vl_api_ip4_address_t": {
+ "IPv4Address": lambda o: o.packed,
+ "str": lambda s: inet_pton(AF_INET, s),
},
- 'vl_api_ip4_address_t':
- {
- 'IPv4Address': lambda o: o.packed,
- 'str': lambda s: inet_pton(AF_INET, s)
+ "vl_api_ip6_prefix_t": {
+ "IPv6Network": lambda o: {
+ "address": o.network_address.packed,
+ "len": o.prefixlen,
+ },
+ "str": lambda s: format_vl_api_ip6_prefix_t(s),
},
- 'vl_api_ip6_prefix_t':
- {
- 'IPv6Network': lambda o: {'address': o.network_address.packed,
- 'len': o.prefixlen},
- 'str': lambda s: format_vl_api_ip6_prefix_t(s)
+ "vl_api_ip4_prefix_t": {
+ "IPv4Network": lambda o: {
+ "address": o.network_address.packed,
+ "len": o.prefixlen,
+ },
+ "str": lambda s: format_vl_api_ip4_prefix_t(s),
},
- 'vl_api_ip4_prefix_t':
- {
- 'IPv4Network': lambda o: {'address': o.network_address.packed,
- 'len': o.prefixlen},
- 'str': lambda s: format_vl_api_ip4_prefix_t(s)
+ "vl_api_address_t": {
+ "IPv4Address": lambda o: {"af": ADDRESS_IP4, "un": {"ip4": o.packed}},
+ "IPv6Address": lambda o: {"af": ADDRESS_IP6, "un": {"ip6": o.packed}},
+ "str": lambda s: format_vl_api_address_t(s),
},
- 'vl_api_address_t':
- {
- 'IPv4Address': lambda o: {'af': ADDRESS_IP4, 'un': {'ip4': o.packed}},
- 'IPv6Address': lambda o: {'af': ADDRESS_IP6, 'un': {'ip6': o.packed}},
- 'str': lambda s: format_vl_api_address_t(s)
+ "vl_api_prefix_t": {
+ "IPv4Network": lambda o: {
+ "address": {"af": ADDRESS_IP4, "un": {"ip4": o.network_address.packed}},
+ "len": o.prefixlen,
+ },
+ "IPv6Network": lambda o: {
+ "address": {"af": ADDRESS_IP6, "un": {"ip6": o.network_address.packed}},
+ "len": o.prefixlen,
+ },
+ "str": lambda s: format_vl_api_prefix_t(s),
},
- 'vl_api_prefix_t':
- {
- 'IPv4Network': lambda o: {'address':
- {'af': ADDRESS_IP4, 'un':
- {'ip4': o.network_address.packed}},
- 'len': o.prefixlen},
- 'IPv6Network': lambda o: {'address':
- {'af': ADDRESS_IP6, 'un':
- {'ip6': o.network_address.packed}},
- 'len': o.prefixlen},
- 'str': lambda s: format_vl_api_prefix_t(s)
+ "vl_api_address_with_prefix_t": {
+ "IPv4Interface": lambda o: {
+ "address": {"af": ADDRESS_IP4, "un": {"ip4": o.packed}},
+ "len": o.network.prefixlen,
+ },
+ "IPv6Interface": lambda o: {
+ "address": {"af": ADDRESS_IP6, "un": {"ip6": o.packed}},
+ "len": o.network.prefixlen,
+ },
+ "str": lambda s: format_vl_api_address_with_prefix_t(s),
},
- 'vl_api_address_with_prefix_t':
- {
- 'IPv4Interface': lambda o: {'address':
- {'af': ADDRESS_IP4, 'un':
- {'ip4': o.packed}},
- 'len': o.network.prefixlen},
- 'IPv6Interface': lambda o: {'address':
- {'af': ADDRESS_IP6, 'un':
- {'ip6': o.packed}},
- 'len': o.network.prefixlen},
- 'str': lambda s: format_vl_api_address_with_prefix_t(s)
+ "vl_api_ip4_address_with_prefix_t": {
+ "IPv4Interface": lambda o: {"address": o.packed, "len": o.network.prefixlen},
+ "str": lambda s: format_vl_api_ip4_address_with_prefix_t(s),
},
- 'vl_api_ip4_address_with_prefix_t':
- {
- 'IPv4Interface': lambda o: {'address': o.packed,
- 'len': o.network.prefixlen},
- 'str': lambda s: format_vl_api_ip4_address_with_prefix_t(s)
+ "vl_api_ip6_address_with_prefix_t": {
+ "IPv6Interface": lambda o: {"address": o.packed, "len": o.network.prefixlen},
+ "str": lambda s: format_vl_api_ip6_address_with_prefix_t(s),
},
- 'vl_api_ip6_address_with_prefix_t':
- {
- 'IPv6Interface': lambda o: {'address': o.packed,
- 'len': o.network.prefixlen},
- 'str': lambda s: format_vl_api_ip6_address_with_prefix_t(s)
+ "vl_api_mac_address_t": {
+ "MACAddress": lambda o: o.packed,
+ "str": lambda s: macaddress.mac_pton(s),
},
- 'vl_api_mac_address_t':
- {
- 'MACAddress': lambda o: o.packed,
- 'str': lambda s: macaddress.mac_pton(s)
+ "vl_api_timestamp_t": {
+ "datetime.datetime": lambda o: (
+ o - datetime.datetime(1970, 1, 1)
+ ).total_seconds()
},
- 'vl_api_timestamp_t':
- {
- 'datetime.datetime': lambda o:
- (o - datetime.datetime(1970, 1, 1)).total_seconds()
- }
}
@@ -197,7 +179,7 @@ def unformat_api_prefix_t(o):
return ipaddress.IPv4Network((o.address, o.len), False)
if isinstance(o.address, ipaddress.IPv6Address):
return ipaddress.IPv6Network((o.address, o.len), False)
- raise ValueError('Unknown instance {}', format(o))
+ raise ValueError("Unknown instance {}", format(o))
def unformat_api_address_with_prefix_t(o):
@@ -217,16 +199,20 @@ def unformat_api_ip6_address_with_prefix_t(o):
conversion_unpacker_table = {
- 'vl_api_ip6_address_t': lambda o: ipaddress.IPv6Address(o),
- 'vl_api_ip6_prefix_t': lambda o: ipaddress.IPv6Network((o.address, o.len)),
- 'vl_api_ip4_address_t': lambda o: ipaddress.IPv4Address(o),
- 'vl_api_ip4_prefix_t': lambda o: ipaddress.IPv4Network((o.address, o.len)),
- 'vl_api_address_t': lambda o: unformat_api_address_t(o),
- 'vl_api_prefix_t': lambda o: unformat_api_prefix_t(o),
- 'vl_api_address_with_prefix_t': lambda o: unformat_api_address_with_prefix_t(o),
- 'vl_api_ip4_address_with_prefix_t': lambda o: unformat_api_ip4_address_with_prefix_t(o),
- 'vl_api_ip6_address_with_prefix_t': lambda o: unformat_api_ip6_address_with_prefix_t(o),
- 'vl_api_mac_address_t': lambda o: macaddress.MACAddress(o),
- 'vl_api_timestamp_t': lambda o: datetime.datetime.fromtimestamp(o),
- 'vl_api_timedelta_t': lambda o: datetime.timedelta(seconds=o),
+ "vl_api_ip6_address_t": lambda o: ipaddress.IPv6Address(o),
+ "vl_api_ip6_prefix_t": lambda o: ipaddress.IPv6Network((o.address, o.len)),
+ "vl_api_ip4_address_t": lambda o: ipaddress.IPv4Address(o),
+ "vl_api_ip4_prefix_t": lambda o: ipaddress.IPv4Network((o.address, o.len)),
+ "vl_api_address_t": lambda o: unformat_api_address_t(o),
+ "vl_api_prefix_t": lambda o: unformat_api_prefix_t(o),
+ "vl_api_address_with_prefix_t": lambda o: unformat_api_address_with_prefix_t(o),
+ "vl_api_ip4_address_with_prefix_t": lambda o: unformat_api_ip4_address_with_prefix_t(
+ o
+ ),
+ "vl_api_ip6_address_with_prefix_t": lambda o: unformat_api_ip6_address_with_prefix_t(
+ o
+ ),
+ "vl_api_mac_address_t": lambda o: macaddress.MACAddress(o),
+ "vl_api_timestamp_t": lambda o: datetime.datetime.fromtimestamp(o),
+ "vl_api_timedelta_t": lambda o: datetime.timedelta(seconds=o),
}
diff --git a/src/vpp-api/python/vpp_papi/vpp_papi.py b/src/vpp-api/python/vpp_papi/vpp_papi.py
index 3465f503e9e..1e5d23e59b7 100644
--- a/src/vpp-api/python/vpp_papi/vpp_papi.py
+++ b/src/vpp-api/python/vpp_papi/vpp_papi.py
@@ -30,13 +30,14 @@ import fnmatch
import weakref
import atexit
import time
-from . vpp_format import verify_enum_hint
-from . vpp_serializer import VPPType, VPPEnumType, VPPEnumFlagType, VPPUnionType
-from . vpp_serializer import VPPMessage, vpp_get_type, VPPTypeAlias
+from .vpp_format import verify_enum_hint
+from .vpp_serializer import VPPType, VPPEnumType, VPPEnumFlagType, VPPUnionType
+from .vpp_serializer import VPPMessage, vpp_get_type, VPPTypeAlias
try:
import VppTransport
except ModuleNotFoundError:
+
class V:
"""placeholder for VppTransport as the implementation is dependent on
VPPAPIClient's initialization values
@@ -44,15 +45,22 @@ except ModuleNotFoundError:
VppTransport = V
-from . vpp_transport_socket import VppTransport
+from .vpp_transport_socket import VppTransport
-logger = logging.getLogger('vpp_papi')
+logger = logging.getLogger("vpp_papi")
logger.addHandler(logging.NullHandler())
-__all__ = ('FuncWrapper', 'VppApiDynamicMethodHolder',
- 'VppEnum', 'VppEnumType', 'VppEnumFlag',
- 'VPPIOError', 'VPPRuntimeError', 'VPPValueError',
- 'VPPApiClient', )
+__all__ = (
+ "FuncWrapper",
+ "VppApiDynamicMethodHolder",
+ "VppEnum",
+ "VppEnumType",
+ "VppEnumFlag",
+ "VPPIOError",
+ "VPPRuntimeError",
+ "VPPValueError",
+ "VPPApiClient",
+)
def metaclass(metaclass):
@@ -83,7 +91,7 @@ def vpp_atexit(vpp_weakref):
"""Clean up VPP connection on shutdown."""
vpp_instance = vpp_weakref()
if vpp_instance and vpp_instance.transport.connected:
- logger.debug('Cleaning up VPP on exit')
+ logger.debug("Cleaning up VPP on exit")
vpp_instance.disconnect()
@@ -98,9 +106,9 @@ def add_convenience_methods():
def _vapi_af_name(self):
if 6 == self._version:
- return 'ip6'
+ return "ip6"
if 4 == self._version:
- return 'ip4'
+ return "ip4"
raise ValueError("Invalid _version.")
ipaddress._IPAddressBase.vapi_af = property(_vapi_af)
@@ -121,7 +129,7 @@ class FuncWrapper:
return self._func(**kwargs)
def __repr__(self):
- return '<FuncWrapper(func=<%s(%s)>)>' % (self.__name__, self.__doc__)
+ return "<FuncWrapper(func=<%s(%s)>)>" % (self.__name__, self.__doc__)
class VPPApiError(Exception):
@@ -161,7 +169,8 @@ class VPPApiJSONFiles:
# perhaps we're in the 'src/scripts' or 'src/vpp-api/python' dir;
# in which case, plot a course to likely places in the src tree
import __main__ as main
- if hasattr(main, '__file__'):
+
+ if hasattr(main, "__file__"):
# get the path of the calling script
localdir = os.path.dirname(os.path.realpath(main.__file__))
else:
@@ -171,7 +180,7 @@ class VPPApiJSONFiles:
def dmatch(dir):
"""Match dir against right-hand components of the script dir"""
- d = dir.split('/') # param 'dir' assumes a / separator
+ d = dir.split("/") # param 'dir' assumes a / separator
length = len(d)
return len(localdir_s) > length and localdir_s[-length:] == d
@@ -180,43 +189,45 @@ class VPPApiJSONFiles:
'variant' (typically '' or '_debug')"""
# Since 'core' and 'plugin' files are staged
# in separate directories, we target the parent dir.
- return os.path.sep.join((
- srcdir,
- 'build-root',
- 'install-vpp%s-native' % variant,
- 'vpp',
- 'share',
- 'vpp',
- 'api',
- ))
+ return os.path.sep.join(
+ (
+ srcdir,
+ "build-root",
+ "install-vpp%s-native" % variant,
+ "vpp",
+ "share",
+ "vpp",
+ "api",
+ )
+ )
srcdir = None
- if dmatch('src/scripts'):
+ if dmatch("src/scripts"):
srcdir = os.path.sep.join(localdir_s[:-2])
- elif dmatch('src/vpp-api/python'):
+ elif dmatch("src/vpp-api/python"):
srcdir = os.path.sep.join(localdir_s[:-3])
- elif dmatch('test'):
+ elif dmatch("test"):
# we're apparently running tests
srcdir = os.path.sep.join(localdir_s[:-1])
if srcdir:
# we're in the source tree, try both the debug and release
# variants.
- dirs.append(sdir(srcdir, '_debug'))
- dirs.append(sdir(srcdir, ''))
+ dirs.append(sdir(srcdir, "_debug"))
+ dirs.append(sdir(srcdir, ""))
# Test for staged copies of the scripts
# For these, since we explicitly know if we're running a debug versus
# release variant, target only the relevant directory
- if dmatch('build-root/install-vpp_debug-native/vpp/bin'):
+ if dmatch("build-root/install-vpp_debug-native/vpp/bin"):
srcdir = os.path.sep.join(localdir_s[:-4])
- dirs.append(sdir(srcdir, '_debug'))
- if dmatch('build-root/install-vpp-native/vpp/bin'):
+ dirs.append(sdir(srcdir, "_debug"))
+ if dmatch("build-root/install-vpp-native/vpp/bin"):
srcdir = os.path.sep.join(localdir_s[:-4])
- dirs.append(sdir(srcdir, ''))
+ dirs.append(sdir(srcdir, ""))
# finally, try the location system packages typically install into
- dirs.append(os.path.sep.join(('', 'usr', 'share', 'vpp', 'api')))
+ dirs.append(os.path.sep.join(("", "usr", "share", "vpp", "api")))
# check the directories for existence; first one wins
for dir in dirs:
@@ -226,7 +237,7 @@ class VPPApiJSONFiles:
return None
@classmethod
- def find_api_files(cls, api_dir=None, patterns='*'): # -> list
+ def find_api_files(cls, api_dir=None, patterns="*"): # -> list
"""Find API definition files from the given directory tree with the
given pattern. If no directory is given then find_api_dir() is used
to locate one. If no pattern is given then all definition files found
@@ -252,9 +263,9 @@ class VPPApiJSONFiles:
raise VPPApiError("api_dir cannot be located")
if isinstance(patterns, list) or isinstance(patterns, tuple):
- patterns = [p.strip() + '.api.json' for p in patterns]
+ patterns = [p.strip() + ".api.json" for p in patterns]
else:
- patterns = [p.strip() + '.api.json' for p in patterns.split(",")]
+ patterns = [p.strip() + ".api.json" for p in patterns.split(",")]
api_files = []
for root, dirnames, files in os.walk(api_dir):
@@ -281,39 +292,39 @@ class VPPApiJSONFiles:
services = {}
messages = {}
try:
- for t in api['enums']:
- t[0] = 'vl_api_' + t[0] + '_t'
- types[t[0]] = {'type': 'enum', 'data': t}
+ for t in api["enums"]:
+ t[0] = "vl_api_" + t[0] + "_t"
+ types[t[0]] = {"type": "enum", "data": t}
except KeyError:
pass
try:
- for t in api['enumflags']:
- t[0] = 'vl_api_' + t[0] + '_t'
- types[t[0]] = {'type': 'enum', 'data': t}
+ for t in api["enumflags"]:
+ t[0] = "vl_api_" + t[0] + "_t"
+ types[t[0]] = {"type": "enum", "data": t}
except KeyError:
pass
try:
- for t in api['unions']:
- t[0] = 'vl_api_' + t[0] + '_t'
- types[t[0]] = {'type': 'union', 'data': t}
+ for t in api["unions"]:
+ t[0] = "vl_api_" + t[0] + "_t"
+ types[t[0]] = {"type": "union", "data": t}
except KeyError:
pass
try:
- for t in api['types']:
- t[0] = 'vl_api_' + t[0] + '_t'
- types[t[0]] = {'type': 'type', 'data': t}
+ for t in api["types"]:
+ t[0] = "vl_api_" + t[0] + "_t"
+ types[t[0]] = {"type": "type", "data": t}
except KeyError:
pass
try:
- for t, v in api['aliases'].items():
- types['vl_api_' + t + '_t'] = {'type': 'alias', 'data': v}
+ for t, v in api["aliases"].items():
+ types["vl_api_" + t + "_t"] = {"type": "alias", "data": v}
except KeyError:
pass
try:
- services.update(api['services'])
+ services.update(api["services"])
except KeyError:
pass
@@ -321,30 +332,30 @@ class VPPApiJSONFiles:
while True:
unresolved = {}
for k, v in types.items():
- t = v['data']
+ t = v["data"]
if not vpp_get_type(k):
- if v['type'] == 'enum':
+ if v["type"] == "enum":
try:
VPPEnumType(t[0], t[1:])
except ValueError:
unresolved[k] = v
if not vpp_get_type(k):
- if v['type'] == 'enumflag':
+ if v["type"] == "enumflag":
try:
VPPEnumFlagType(t[0], t[1:])
except ValueError:
unresolved[k] = v
- elif v['type'] == 'union':
+ elif v["type"] == "union":
try:
VPPUnionType(t[0], t[1:])
except ValueError:
unresolved[k] = v
- elif v['type'] == 'type':
+ elif v["type"] == "type":
try:
VPPType(t[0], t[1:])
except ValueError:
unresolved[k] = v
- elif v['type'] == 'alias':
+ elif v["type"] == "alias":
try:
VPPTypeAlias(k, t)
except ValueError:
@@ -352,17 +363,16 @@ class VPPApiJSONFiles:
if len(unresolved) == 0:
break
if i > 3:
- raise VPPValueError('Unresolved type definitions {}'
- .format(unresolved))
+ raise VPPValueError("Unresolved type definitions {}".format(unresolved))
types = unresolved
i += 1
try:
- for m in api['messages']:
+ for m in api["messages"]:
try:
messages[m[0]] = VPPMessage(m[0], m[1:])
except VPPNotImplementedError:
### OLE FIXME
- logger.error('Not implemented error for {}'.format(m[0]))
+ logger.error("Not implemented error for {}".format(m[0]))
except KeyError:
pass
return messages, services
@@ -380,6 +390,7 @@ class VPPApiClient:
provides a means to register a callback function to receive
these messages in a background thread.
"""
+
apidir = None
VPPApiError = VPPApiError
VPPRuntimeError = VPPRuntimeError
@@ -387,11 +398,18 @@ class VPPApiClient:
VPPNotImplementedError = VPPNotImplementedError
VPPIOError = VPPIOError
-
- def __init__(self, *, apifiles=None, testmode=False, async_thread=True,
- logger=None, loglevel=None,
- read_timeout=5, use_socket=True,
- server_address='/run/vpp/api.sock'):
+ def __init__(
+ self,
+ *,
+ apifiles=None,
+ testmode=False,
+ async_thread=True,
+ logger=None,
+ loglevel=None,
+ read_timeout=5,
+ use_socket=True,
+ server_address="/run/vpp/api.sock",
+ ):
"""Create a VPP API object.
apifiles is a list of files containing API
@@ -406,7 +424,8 @@ class VPPApiClient:
"""
if logger is None:
logger = logging.getLogger(
- "{}.{}".format(__name__, self.__class__.__name__))
+ "{}.{}".format(__name__, self.__class__.__name__)
+ )
if loglevel is not None:
logger.setLevel(loglevel)
self.logger = logger
@@ -415,8 +434,7 @@ class VPPApiClient:
self.services = {}
self.id_names = []
self.id_msgdef = []
- self.header = VPPType('header', [['u16', 'msgid'],
- ['u32', 'client_index']])
+ self.header = VPPType("header", [["u16", "msgid"], ["u32", "client_index"]])
self.apifiles = []
self.event_callback = None
self.message_queue = queue.Queue()
@@ -449,13 +467,13 @@ class VPPApiClient:
# Basic sanity check
if len(self.messages) == 0 and not testmode:
- raise VPPValueError(1, 'Missing JSON message definitions')
- if not(verify_enum_hint(VppEnum.vl_api_address_family_t)):
- raise VPPRuntimeError("Invalid address family hints. "
- "Cannot continue.")
+ raise VPPValueError(1, "Missing JSON message definitions")
+ if not (verify_enum_hint(VppEnum.vl_api_address_family_t)):
+ raise VPPRuntimeError("Invalid address family hints. " "Cannot continue.")
- self.transport = VppTransport(self, read_timeout=read_timeout,
- server_address=server_address)
+ self.transport = VppTransport(
+ self, read_timeout=read_timeout, server_address=server_address
+ )
# Make sure we allow VPP to clean up the message rings.
atexit.register(vpp_atexit, weakref.ref(self))
@@ -466,6 +484,7 @@ class VPPApiClient:
class ContextId:
"""Multiprocessing-safe provider of unique context IDs."""
+
def __init__(self):
self.context = mp.Value(ctypes.c_uint, 0)
self.lock = mp.Lock()
@@ -475,6 +494,7 @@ class VPPApiClient:
with self.lock:
self.context.value += 1
return self.context.value
+
get_context = ContextId()
def get_type(self, name):
@@ -487,17 +507,20 @@ class VPPApiClient:
return self._api
def make_function(self, msg, i, multipart, do_async):
- if (do_async):
+ if do_async:
+
def f(**kwargs):
return self._call_vpp_async(i, msg, **kwargs)
+
else:
+
def f(**kwargs):
return self._call_vpp(i, msg, multipart, **kwargs)
f.__name__ = str(msg.name)
- f.__doc__ = ", ".join(["%s %s" %
- (msg.fieldtypes[j], k)
- for j, k in enumerate(msg.fields)])
+ f.__doc__ = ", ".join(
+ ["%s %s" % (msg.fieldtypes[j], k) for j, k in enumerate(msg.fields)]
+ )
f.msg = msg
return f
@@ -507,7 +530,7 @@ class VPPApiClient:
self.id_msgdef = [None] * (self.vpp_dictionary_maxid + 1)
self._api = VppApiDynamicMethodHolder()
for name, msg in self.messages.items():
- n = name + '_' + msg.crc[2:]
+ n = name + "_" + msg.crc[2:]
i = self.transport.get_msg_index(n)
if i > 0:
self.id_msgdef[i] = msg
@@ -518,28 +541,25 @@ class VPPApiClient:
f = self.make_function(msg, i, self.services[name], do_async)
setattr(self._api, name, FuncWrapper(f))
else:
- self.logger.debug(
- 'No such message type or failed CRC checksum: %s', n)
+ self.logger.debug("No such message type or failed CRC checksum: %s", n)
- def connect_internal(self, name, msg_handler, chroot_prefix, rx_qlen,
- do_async):
- pfx = chroot_prefix.encode('utf-8') if chroot_prefix else None
+ def connect_internal(self, name, msg_handler, chroot_prefix, rx_qlen, do_async):
+ pfx = chroot_prefix.encode("utf-8") if chroot_prefix else None
- rv = self.transport.connect(name, pfx,
- msg_handler, rx_qlen)
+ rv = self.transport.connect(name, pfx, msg_handler, rx_qlen)
if rv != 0:
- raise VPPIOError(2, 'Connect failed')
+ raise VPPIOError(2, "Connect failed")
self.vpp_dictionary_maxid = self.transport.msg_table_max_index()
self._register_functions(do_async=do_async)
# Initialise control ping
- crc = self.messages['control_ping'].crc
+ crc = self.messages["control_ping"].crc
self.control_ping_index = self.transport.get_msg_index(
- ('control_ping' + '_' + crc[2:]))
- self.control_ping_msgdef = self.messages['control_ping']
+ ("control_ping" + "_" + crc[2:])
+ )
+ self.control_ping_msgdef = self.messages["control_ping"]
if self.async_thread:
- self.event_thread = threading.Thread(
- target=self.thread_msg_handler)
+ self.event_thread = threading.Thread(target=self.thread_msg_handler)
self.event_thread.daemon = True
self.event_thread.start()
else:
@@ -556,8 +576,9 @@ class VPPApiClient:
client and server.
"""
msg_handler = self.transport.get_callback(do_async)
- return self.connect_internal(name, msg_handler, chroot_prefix, rx_qlen,
- do_async)
+ return self.connect_internal(
+ name, msg_handler, chroot_prefix, rx_qlen, do_async
+ )
def connect_sync(self, name, chroot_prefix=None, rx_qlen=32):
"""Attach to VPP in synchronous mode. Application must poll for events.
@@ -568,8 +589,7 @@ class VPPApiClient:
client and server.
"""
- return self.connect_internal(name, None, chroot_prefix, rx_qlen,
- do_async=False)
+ return self.connect_internal(name, None, chroot_prefix, rx_qlen, do_async=False)
def disconnect(self):
"""Detach from VPP."""
@@ -590,42 +610,43 @@ class VPPApiClient:
# If we have a context, then use the context to find any
# request waiting for a reply
context = 0
- if hasattr(r, 'context') and r.context > 0:
+ if hasattr(r, "context") and r.context > 0:
context = r.context
if context == 0:
# No context -> async notification that we feed to the callback
self.message_queue.put_nowait(r)
else:
- raise VPPIOError(2, 'RPC reply message received in event handler')
+ raise VPPIOError(2, "RPC reply message received in event handler")
def has_context(self, msg):
if len(msg) < 10:
return False
- header = VPPType('header_with_context', [['u16', 'msgid'],
- ['u32', 'client_index'],
- ['u32', 'context']])
+ header = VPPType(
+ "header_with_context",
+ [["u16", "msgid"], ["u32", "client_index"], ["u32", "context"]],
+ )
(i, ci, context), size = header.unpack(msg, 0)
- if self.id_names[i] == 'rx_thread_exit':
+ if self.id_names[i] == "rx_thread_exit":
return
#
# Decode message and returns a tuple.
#
msgobj = self.id_msgdef[i]
- if 'context' in msgobj.field_by_name and context >= 0:
+ if "context" in msgobj.field_by_name and context >= 0:
return True
return False
def decode_incoming_msg(self, msg, no_type_conversion=False):
if not msg:
- logger.warning('vpp_api.read failed')
+ logger.warning("vpp_api.read failed")
return
(i, ci), size = self.header.unpack(msg, 0)
- if self.id_names[i] == 'rx_thread_exit':
+ if self.id_names[i] == "rx_thread_exit":
return
#
@@ -633,7 +654,7 @@ class VPPApiClient:
#
msgobj = self.id_msgdef[i]
if not msgobj:
- raise VPPIOError(2, 'Reply message undefined')
+ raise VPPIOError(2, "Reply message undefined")
r, size = msgobj.unpack(msg, ntc=no_type_conversion)
return r
@@ -654,41 +675,39 @@ class VPPApiClient:
def _control_ping(self, context):
"""Send a ping command."""
- self._call_vpp_async(self.control_ping_index,
- self.control_ping_msgdef,
- context=context)
+ self._call_vpp_async(
+ self.control_ping_index, self.control_ping_msgdef, context=context
+ )
def validate_args(self, msg, kwargs):
d = set(kwargs.keys()) - set(msg.field_by_name.keys())
if d:
- raise VPPValueError('Invalid argument {} to {}'
- .format(list(d), msg.name))
+ raise VPPValueError("Invalid argument {} to {}".format(list(d), msg.name))
def _add_stat(self, name, ms):
if not name in self.stats:
- self.stats[name] = {'max': ms, 'count': 1, 'avg': ms}
+ self.stats[name] = {"max": ms, "count": 1, "avg": ms}
else:
- if ms > self.stats[name]['max']:
- self.stats[name]['max'] = ms
- self.stats[name]['count'] += 1
- n = self.stats[name]['count']
- self.stats[name]['avg'] = self.stats[name]['avg'] * (n - 1) / n + ms / n
+ if ms > self.stats[name]["max"]:
+ self.stats[name]["max"] = ms
+ self.stats[name]["count"] += 1
+ n = self.stats[name]["count"]
+ self.stats[name]["avg"] = self.stats[name]["avg"] * (n - 1) / n + ms / n
def get_stats(self):
- s = '\n=== API PAPI STATISTICS ===\n'
- s += '{:<30} {:>4} {:>6} {:>6}\n'.format('message', 'cnt', 'avg', 'max')
- for n in sorted(self.stats.items(), key=lambda v: v[1]['avg'], reverse=True):
- s += '{:<30} {:>4} {:>6.2f} {:>6.2f}\n'.format(n[0], n[1]['count'],
- n[1]['avg'], n[1]['max'])
+ s = "\n=== API PAPI STATISTICS ===\n"
+ s += "{:<30} {:>4} {:>6} {:>6}\n".format("message", "cnt", "avg", "max")
+ for n in sorted(self.stats.items(), key=lambda v: v[1]["avg"], reverse=True):
+ s += "{:<30} {:>4} {:>6.2f} {:>6.2f}\n".format(
+ n[0], n[1]["count"], n[1]["avg"], n[1]["max"]
+ )
return s
def get_field_options(self, msg, fld_name):
# when there is an option, the msgdef has 3 elements.
# ['u32', 'ring_size', {'default': 1024}]
for _def in self.messages[msg].msgdef:
- if isinstance(_def, list) and \
- len(_def) == 3 and \
- _def[1] == fld_name:
+ if isinstance(_def, list) and len(_def) == 3 and _def[1] == fld_name:
return _def[2]
def _call_vpp(self, i, msgdef, service, **kwargs):
@@ -707,25 +726,26 @@ class VPPApiClient:
no response within the timeout window.
"""
ts = time.time()
- if 'context' not in kwargs:
+ if "context" not in kwargs:
context = self.get_context()
- kwargs['context'] = context
+ kwargs["context"] = context
else:
- context = kwargs['context']
- kwargs['_vl_msg_id'] = i
+ context = kwargs["context"]
+ kwargs["_vl_msg_id"] = i
- no_type_conversion = kwargs.pop('_no_type_conversion', False)
- timeout = kwargs.pop('_timeout', None)
+ no_type_conversion = kwargs.pop("_no_type_conversion", False)
+ timeout = kwargs.pop("_timeout", None)
try:
if self.transport.socket_index:
- kwargs['client_index'] = self.transport.socket_index
+ kwargs["client_index"] = self.transport.socket_index
except AttributeError:
pass
self.validate_args(msgdef, kwargs)
- s = 'Calling {}({})'.format(msgdef.name,
- ','.join(['{!r}:{!r}'.format(k, v) for k, v in kwargs.items()]))
+ s = "Calling {}({})".format(
+ msgdef.name, ",".join(["{!r}:{!r}".format(k, v) for k, v in kwargs.items()])
+ )
self.logger.debug(s)
b = msgdef.pack(kwargs)
@@ -733,17 +753,17 @@ class VPPApiClient:
self.transport.write(b)
- msgreply = service['reply']
- stream = True if 'stream' in service else False
+ msgreply = service["reply"]
+ stream = True if "stream" in service else False
if stream:
- if 'stream_msg' in service:
+ if "stream_msg" in service:
# New service['reply'] = _reply and service['stream_message'] = _details
- stream_message = service['stream_msg']
- modern =True
+ stream_message = service["stream_msg"]
+ modern = True
else:
# Old service['reply'] = _details
stream_message = msgreply
- msgreply = 'control_ping_reply'
+ msgreply = "control_ping_reply"
modern = False
# Send a ping after the request - we use its response
# to detect that we have seen all results.
@@ -751,22 +771,22 @@ class VPPApiClient:
# Block until we get a reply.
rl = []
- while (True):
+ while True:
r = self.read_blocking(no_type_conversion, timeout)
if r is None:
- raise VPPIOError(2, 'VPP API client: read failed')
+ raise VPPIOError(2, "VPP API client: read failed")
msgname = type(r).__name__
if context not in r or r.context == 0 or context != r.context:
# Message being queued
self.message_queue.put_nowait(r)
continue
if msgname != msgreply and (stream and (msgname != stream_message)):
- print('REPLY MISMATCH', msgreply, msgname, stream_message, stream)
+ print("REPLY MISMATCH", msgreply, msgname, stream_message, stream)
if not stream:
rl = r
break
if msgname == msgreply:
- if modern: # Return both reply and list
+ if modern: # Return both reply and list
rl = r, rl
break
@@ -774,7 +794,7 @@ class VPPApiClient:
self.transport.resume()
- s = 'Return value: {!r}'.format(r)
+ s = "Return value: {!r}".format(r)
if len(s) > 80:
s = s[:80] + "..."
self.logger.debug(s)
@@ -795,17 +815,17 @@ class VPPApiClient:
The returned context will help with assigning which call
the reply belongs to.
"""
- if 'context' not in kwargs:
+ if "context" not in kwargs:
context = self.get_context()
- kwargs['context'] = context
+ kwargs["context"] = context
else:
- context = kwargs['context']
+ context = kwargs["context"]
try:
if self.transport.socket_index:
- kwargs['client_index'] = self.transport.socket_index
+ kwargs["client_index"] = self.transport.socket_index
except AttributeError:
- kwargs['client_index'] = 0
- kwargs['_vl_msg_id'] = i
+ kwargs["client_index"] = 0
+ kwargs["_vl_msg_id"] = i
b = msg.pack(kwargs)
self.transport.write(b)
@@ -891,26 +911,34 @@ class VPPApiClient:
"""Return VPPs API message table as name_crc dictionary,
filtered by message name list."""
- replies = [self.services[n]['reply'] for n in msglist]
+ replies = [self.services[n]["reply"] for n in msglist]
message_table_filtered = {}
for name in msglist + replies:
- for k,v in self.transport.message_table.items():
+ for k, v in self.transport.message_table.items():
if k.startswith(name):
message_table_filtered[k] = v
break
return message_table_filtered
def __repr__(self):
- return "<VPPApiClient apifiles=%s, testmode=%s, async_thread=%s, " \
- "logger=%s, read_timeout=%s, " \
- "server_address='%s'>" % (
- self._apifiles, self.testmode, self.async_thread,
- self.logger, self.read_timeout, self.server_address)
+ return (
+ "<VPPApiClient apifiles=%s, testmode=%s, async_thread=%s, "
+ "logger=%s, read_timeout=%s, "
+ "server_address='%s'>"
+ % (
+ self._apifiles,
+ self.testmode,
+ self.async_thread,
+ self.logger,
+ self.read_timeout,
+ self.server_address,
+ )
+ )
def details_iter(self, f, **kwargs):
cursor = 0
while True:
- kwargs['cursor'] = cursor
+ kwargs["cursor"] = cursor
rv, details = f(**kwargs)
for d in details:
yield d
diff --git a/src/vpp-api/python/vpp_papi/vpp_serializer.py b/src/vpp-api/python/vpp_papi/vpp_serializer.py
index 644aeac65c6..a99e16aa8f9 100644
--- a/src/vpp-api/python/vpp_papi/vpp_serializer.py
+++ b/src/vpp-api/python/vpp_papi/vpp_serializer.py
@@ -27,7 +27,7 @@ from . import vpp_format
# logger = logging.getLogger('vpp_serializer')
# logger.setLevel(logging.DEBUG)
#
-logger = logging.getLogger('vpp_papi.serializer')
+logger = logging.getLogger("vpp_papi.serializer")
def check(d):
@@ -46,8 +46,7 @@ def conversion_required(data, field_type):
def conversion_packer(data, field_type):
t = type(data).__name__
- return types[field_type].pack(vpp_format.
- conversion_table[field_type][t](data))
+ return types[field_type].pack(vpp_format.conversion_table[field_type][t](data))
def conversion_unpacker(data, field_type):
@@ -77,30 +76,33 @@ class Packer:
return c._get_packer_with_options(f_type, options)
except IndexError:
raise VPPSerializerValueError(
- "Options not supported for {}{} ({})".
- format(f_type, types[f_type].__class__,
- options))
+ "Options not supported for {}{} ({})".format(
+ f_type, types[f_type].__class__, options
+ )
+ )
class BaseTypes(Packer):
def __init__(self, type, elements=0, options=None):
self._type = type
self._elements = elements
- base_types = {'u8': '>B',
- 'i8': '>b',
- 'string': '>s',
- 'u16': '>H',
- 'i16': '>h',
- 'u32': '>I',
- 'i32': '>i',
- 'u64': '>Q',
- 'i64': '>q',
- 'f64': '=d',
- 'bool': '>?',
- 'header': '>HI'}
-
- if elements > 0 and (type == 'u8' or type == 'string'):
- self.packer = struct.Struct('>%ss' % elements)
+ base_types = {
+ "u8": ">B",
+ "i8": ">b",
+ "string": ">s",
+ "u16": ">H",
+ "i16": ">h",
+ "u32": ">I",
+ "i32": ">i",
+ "u64": ">Q",
+ "i64": ">q",
+ "f64": "=d",
+ "bool": ">?",
+ "header": ">HI",
+ }
+
+ if elements > 0 and (type == "u8" or type == "string"):
+ self.packer = struct.Struct(">%ss" % elements)
else:
self.packer = struct.Struct(base_types[type])
self.size = self.packer.size
@@ -108,8 +110,8 @@ class BaseTypes(Packer):
def pack(self, data, kwargs=None):
if data is None: # Default to zero if not specified
- if self.options and 'default' in self.options:
- data = self.options['default']
+ if self.options and "default" in self.options:
+ data = self.options["default"]
else:
data = 0
return self.packer.pack(data)
@@ -122,9 +124,11 @@ class BaseTypes(Packer):
return BaseTypes(f_type, options=options)
def __repr__(self):
- return "BaseTypes(type=%s, elements=%s, options=%s)" % (self._type,
- self._elements,
- self.options)
+ return "BaseTypes(type=%s, elements=%s, options=%s)" % (
+ self._type,
+ self._elements,
+ self.options,
+ )
class String(Packer):
@@ -132,13 +136,15 @@ class String(Packer):
self.name = name
self.num = num
self.size = 1
- self.length_field_packer = BaseTypes('u32')
- self.limit = options['limit'] if 'limit' in options else num
+ self.length_field_packer = BaseTypes("u32")
+ self.limit = options["limit"] if "limit" in options else num
self.fixed = True if num else False
if self.fixed and not self.limit:
raise VPPSerializerValueError(
- "Invalid combination for: {}, {} fixed:{} limit:{}".
- format(name, options, self.fixed, self.limit))
+ "Invalid combination for: {}, {} fixed:{} limit:{}".format(
+ name, options, self.fixed, self.limit
+ )
+ )
def pack(self, list, kwargs=None):
if not list:
@@ -147,34 +153,42 @@ class String(Packer):
return self.length_field_packer.pack(0) + b""
if self.limit and len(list) > self.limit - 1:
raise VPPSerializerValueError(
- "Invalid argument length for: {}, {} maximum {}".
- format(list, len(list), self.limit - 1))
+ "Invalid argument length for: {}, {} maximum {}".format(
+ list, len(list), self.limit - 1
+ )
+ )
if self.fixed:
- return list.encode('ascii').ljust(self.limit, b'\x00')
- return self.length_field_packer.pack(len(list)) + list.encode('ascii')
+ return list.encode("ascii").ljust(self.limit, b"\x00")
+ return self.length_field_packer.pack(len(list)) + list.encode("ascii")
def unpack(self, data, offset=0, result=None, ntc=False):
if self.fixed:
- p = BaseTypes('u8', self.num)
+ p = BaseTypes("u8", self.num)
s = p.unpack(data, offset)
- s2 = s[0].split(b'\0', 1)[0]
- return (s2.decode('ascii'), self.num)
+ s2 = s[0].split(b"\0", 1)[0]
+ return (s2.decode("ascii"), self.num)
- length, length_field_size = self.length_field_packer.unpack(data,
- offset)
+ length, length_field_size = self.length_field_packer.unpack(data, offset)
if length == 0:
- return '', 0
- p = BaseTypes('u8', length)
+ return "", 0
+ p = BaseTypes("u8", length)
x, size = p.unpack(data, offset + length_field_size)
- return (x.decode('ascii', errors='replace'), size + length_field_size)
-
-
-types = {'u8': BaseTypes('u8'), 'i8': BaseTypes('i8'),
- 'u16': BaseTypes('u16'), 'i16': BaseTypes('i16'),
- 'u32': BaseTypes('u32'), 'i32': BaseTypes('i32'),
- 'u64': BaseTypes('u64'), 'i64': BaseTypes('i64'),
- 'f64': BaseTypes('f64'),
- 'bool': BaseTypes('bool'), 'string': String}
+ return (x.decode("ascii", errors="replace"), size + length_field_size)
+
+
+types = {
+ "u8": BaseTypes("u8"),
+ "i8": BaseTypes("i8"),
+ "u16": BaseTypes("u16"),
+ "i16": BaseTypes("i16"),
+ "u32": BaseTypes("u32"),
+ "i32": BaseTypes("i32"),
+ "u64": BaseTypes("u64"),
+ "i64": BaseTypes("i64"),
+ "f64": BaseTypes("f64"),
+ "bool": BaseTypes("bool"),
+ "string": String,
+}
class_types = {}
@@ -202,32 +216,34 @@ class FixedList_u8(Packer):
"""Packs a fixed length bytestring. Left-pads with zeros
if input data is too short."""
if not data:
- return b'\x00' * self.size
+ return b"\x00" * self.size
if len(data) > self.num:
raise VPPSerializerValueError(
'Fixed list length error for "{}", got: {}'
- ' expected: {}'
- .format(self.name, len(data), self.num))
+ " expected: {}".format(self.name, len(data), self.num)
+ )
try:
return self.packer.pack(data)
except struct.error:
raise VPPSerializerValueError(
- 'Packing failed for "{}" {}'
- .format(self.name, kwargs))
+ 'Packing failed for "{}" {}'.format(self.name, kwargs)
+ )
def unpack(self, data, offset=0, result=None, ntc=False):
if len(data[offset:]) < self.num:
raise VPPSerializerValueError(
'Invalid array length for "{}" got {}'
- ' expected {}'
- .format(self.name, len(data[offset:]), self.num))
+ " expected {}".format(self.name, len(data[offset:]), self.num)
+ )
return self.packer.unpack(data, offset)
def __repr__(self):
return "FixedList_u8(name=%s, field_type=%s, num=%s)" % (
- self.name, self.field_type, self.num
+ self.name,
+ self.field_type,
+ self.num,
)
@@ -242,8 +258,10 @@ class FixedList(Packer):
def pack(self, list, kwargs):
if len(list) != self.num:
raise VPPSerializerValueError(
- 'Fixed list length error, got: {} expected: {}'
- .format(len(list), self.num))
+ "Fixed list length error, got: {} expected: {}".format(
+ len(list), self.num
+ )
+ )
b = bytes()
for e in list:
b += self.packer.pack(e)
@@ -262,7 +280,10 @@ class FixedList(Packer):
def __repr__(self):
return "FixedList(name=%s, field_type=%s, num=%s)" % (
- self.name, self.field_type, self.num)
+ self.name,
+ self.field_type,
+ self.num,
+ )
class VLAList(Packer):
@@ -279,13 +300,15 @@ class VLAList(Packer):
return b""
if len(lst) != kwargs[self.length_field]:
raise VPPSerializerValueError(
- 'Variable length error, got: {} expected: {}'
- .format(len(lst), kwargs[self.length_field]))
+ "Variable length error, got: {} expected: {}".format(
+ len(lst), kwargs[self.length_field]
+ )
+ )
# u8 array
if self.packer.size == 1:
if isinstance(lst, list):
- return b''.join(lst)
+ return b"".join(lst)
return bytes(lst)
b = bytes()
@@ -300,8 +323,8 @@ class VLAList(Packer):
# u8 array
if self.packer.size == 1:
if result[self.index] == 0:
- return b'', 0
- p = BaseTypes('u8', result[self.index])
+ return b"", 0
+ p = BaseTypes("u8", result[self.index])
return p.unpack(data, offset, ntc=ntc)
r = []
@@ -313,10 +336,12 @@ class VLAList(Packer):
return r, total
def __repr__(self):
- return "VLAList(name=%s, field_type=%s, " \
- "len_field_name=%s, index=%s)" % (
- self.name, self.field_type, self.length_field, self.index
- )
+ return "VLAList(name=%s, field_type=%s, " "len_field_name=%s, index=%s)" % (
+ self.name,
+ self.field_type,
+ self.length_field,
+ self.index,
+ )
class VLAList_legacy(Packer):
@@ -340,7 +365,8 @@ class VLAList_legacy(Packer):
# Return a list of arguments
if (len(data) - offset) % self.packer.size:
raise VPPSerializerValueError(
- 'Legacy Variable Length Array length mismatch.')
+ "Legacy Variable Length Array length mismatch."
+ )
elements = int((len(data) - offset) / self.packer.size)
r = []
for e in range(elements):
@@ -351,9 +377,7 @@ class VLAList_legacy(Packer):
return r, total
def __repr__(self):
- return "VLAList_legacy(name=%s, field_type=%s)" % (
- self.name, self.field_type
- )
+ return "VLAList_legacy(name=%s, field_type=%s)" % (self.name, self.field_type)
# Will change to IntEnum after 21.04 release
@@ -361,16 +385,16 @@ class VPPEnumType(Packer):
output_class = IntFlag
def __init__(self, name, msgdef, options=None):
- self.size = types['u32'].size
+ self.size = types["u32"].size
self.name = name
- self.enumtype = 'u32'
+ self.enumtype = "u32"
self.msgdef = msgdef
e_hash = {}
for f in msgdef:
- if type(f) is dict and 'enumtype' in f:
- if f['enumtype'] != 'u32':
- self.size = types[f['enumtype']].size
- self.enumtype = f['enumtype']
+ if type(f) is dict and "enumtype" in f:
+ if f["enumtype"] != "u32":
+ self.size = types[f["enumtype"]].size
+ self.enumtype = f["enumtype"]
continue
ename, evalue = f
e_hash[ename] = evalue
@@ -387,8 +411,8 @@ class VPPEnumType(Packer):
def pack(self, data, kwargs=None):
if data is None: # Default to zero if not specified
- if self.options and 'default' in self.options:
- data = self.options['default']
+ if self.options and "default" in self.options:
+ data = self.options["default"]
else:
data = 0
@@ -404,7 +428,10 @@ class VPPEnumType(Packer):
def __repr__(self):
return "%s(name=%s, msgdef=%s, options=%s)" % (
- self.__class__.__name__, self.name, self.msgdef, self.options
+ self.__class__.__name__,
+ self.name,
+ self.msgdef,
+ self.options,
)
@@ -424,14 +451,13 @@ class VPPUnionType(Packer):
fields = []
self.packers = collections.OrderedDict()
for i, f in enumerate(msgdef):
- if type(f) is dict and 'crc' in f:
- self.crc = f['crc']
+ if type(f) is dict and "crc" in f:
+ self.crc = f["crc"]
continue
f_type, f_name = f
if f_type not in types:
- logger.debug('Unknown union type {}'.format(f_type))
- raise VPPSerializerValueError(
- 'Unknown message type {}'.format(f_type))
+ logger.debug("Unknown union type {}".format(f_type))
+ raise VPPSerializerValueError("Unknown message type {}".format(f_type))
fields.append(f_name)
size = types[f_type].size
self.packers[f_name] = types[f_type]
@@ -445,14 +471,14 @@ class VPPUnionType(Packer):
# Union of variable length?
def pack(self, data, kwargs=None):
if not data:
- return b'\x00' * self.size
+ return b"\x00" * self.size
for k, v in data.items():
logger.debug("Key: {} Value: {}".format(k, v))
b = self.packers[k].pack(v, kwargs)
break
r = bytearray(self.size)
- r[:len(b)] = b
+ r[: len(b)] = b
return r
def unpack(self, data, offset=0, result=None, ntc=False):
@@ -466,25 +492,24 @@ class VPPUnionType(Packer):
return self.tuple._make(r), maxsize
def __repr__(self):
- return"VPPUnionType(name=%s, msgdef=%r)" % (self.name, self.msgdef)
+ return "VPPUnionType(name=%s, msgdef=%r)" % (self.name, self.msgdef)
class VPPTypeAlias(Packer):
def __init__(self, name, msgdef, options=None):
self.name = name
self.msgdef = msgdef
- t = vpp_get_type(msgdef['type'])
+ t = vpp_get_type(msgdef["type"])
if not t:
- raise ValueError('No such type: {}'.format(msgdef['type']))
- if 'length' in msgdef:
- if msgdef['length'] == 0:
+ raise ValueError("No such type: {}".format(msgdef["type"]))
+ if "length" in msgdef:
+ if msgdef["length"] == 0:
raise ValueError()
- if msgdef['type'] == 'u8':
- self.packer = FixedList_u8(name, msgdef['type'],
- msgdef['length'])
+ if msgdef["type"] == "u8":
+ self.packer = FixedList_u8(name, msgdef["type"], msgdef["length"])
self.size = self.packer.size
else:
- self.packer = FixedList(name, msgdef['type'], msgdef['length'])
+ self.packer = FixedList(name, msgdef["type"], msgdef["length"])
else:
self.packer = t
self.size = t.size
@@ -498,11 +523,11 @@ class VPPTypeAlias(Packer):
try:
return conversion_packer(data, self.name)
# Python 2 and 3 raises different exceptions from inet_pton
- except(OSError, socket.error, TypeError):
+ except (OSError, socket.error, TypeError):
pass
if data is None: # Default to zero if not specified
- if self.options and 'default' in self.options:
- data = self.options['default']
+ if self.options and "default" in self.options:
+ data = self.options["default"]
else:
data = 0
@@ -525,7 +550,10 @@ class VPPTypeAlias(Packer):
def __repr__(self):
return "VPPTypeAlias(name=%s, msgdef=%s, options=%s)" % (
- self.name, self.msgdef, self.options)
+ self.name,
+ self.msgdef,
+ self.options,
+ )
class VPPType(Packer):
@@ -539,17 +567,16 @@ class VPPType(Packer):
self.field_by_name = {}
size = 0
for i, f in enumerate(msgdef):
- if type(f) is dict and 'crc' in f:
- self.crc = f['crc']
+ if type(f) is dict and "crc" in f:
+ self.crc = f["crc"]
continue
f_type, f_name = f[:2]
self.fields.append(f_name)
self.field_by_name[f_name] = None
self.fieldtypes.append(f_type)
if f_type not in types:
- logger.debug('Unknown type {}'.format(f_type))
- raise VPPSerializerValueError(
- 'Unknown message type {}'.format(f_type))
+ logger.debug("Unknown type {}".format(f_type))
+ raise VPPSerializerValueError("Unknown message type {}".format(f_type))
fieldlen = len(f)
options = [x for x in f if type(x) is dict]
@@ -561,16 +588,16 @@ class VPPType(Packer):
if fieldlen == 3: # list
list_elements = f[2]
if list_elements == 0:
- if f_type == 'string':
+ if f_type == "string":
p = String(f_name, 0, self.options)
else:
p = VLAList_legacy(f_name, f_type)
self.packers.append(p)
- elif f_type == 'u8':
+ elif f_type == "u8":
p = FixedList_u8(f_name, f_type, list_elements)
self.packers.append(p)
size += p.size
- elif f_type == 'string':
+ elif f_type == "string":
p = String(f_name, list_elements, self.options)
self.packers.append(p)
size += p.size
@@ -584,7 +611,7 @@ class VPPType(Packer):
self.packers.append(p)
else:
# default support for types that decay to basetype
- if 'default' in self.options:
+ if "default" in self.options:
p = self.get_packer_with_options(f_type, self.options)
else:
p = types[f_type]
@@ -609,8 +636,8 @@ class VPPType(Packer):
for i, a in enumerate(self.fields):
if data and type(data) is not dict and a not in data:
raise VPPSerializerValueError(
- "Invalid argument: {} expected {}.{}".
- format(data, self.name, a))
+ "Invalid argument: {} expected {}.{}".format(data, self.name, a)
+ )
# Defaulting to zero.
if not data or a not in data: # Default to 0
@@ -651,7 +678,9 @@ class VPPType(Packer):
def __repr__(self):
return "%s(name=%s, msgdef=%s)" % (
- self.__class__.__name__, self.name, self.msgdef
+ self.__class__.__name__,
+ self.name,
+ self.msgdef,
)
diff --git a/src/vpp-api/python/vpp_papi/vpp_stats.py b/src/vpp-api/python/vpp_papi/vpp_stats.py
index 0b1c701a430..4a342b68a8f 100755
--- a/src/vpp-api/python/vpp_papi/vpp_stats.py
+++ b/src/vpp-api/python/vpp_papi/vpp_stats.py
@@ -14,7 +14,7 @@
# limitations under the License.
#
-'''
+"""
This module implement Python access to the VPP statistics segment. It
accesses the data structures directly in shared memory.
VPP uses optimistic locking, so data structures may change underneath
@@ -39,7 +39,7 @@ stat['/if/rx'][:, 1].sum_packets() - returns the sum of packet counters for
interface 1 on all threads
stat['/if/rx-miss'][:, 1].sum() - returns the sum of packet counters for
interface 1 on all threads for simple counters
-'''
+"""
import os
import socket
@@ -50,31 +50,36 @@ import time
import unittest
import re
+
def recv_fd(sock):
- '''Get file descriptor for memory map'''
- fds = array.array("i") # Array of ints
+ """Get file descriptor for memory map"""
+ fds = array.array("i") # Array of ints
_, ancdata, _, _ = sock.recvmsg(0, socket.CMSG_LEN(4))
for cmsg_level, cmsg_type, cmsg_data in ancdata:
if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS:
- fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
+ fds.frombytes(cmsg_data[: len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
return list(fds)[0]
-VEC_LEN_FMT = Struct('I')
+
+VEC_LEN_FMT = Struct("I")
+
+
def get_vec_len(stats, vector_offset):
- '''Equivalent to VPP vec_len()'''
+ """Equivalent to VPP vec_len()"""
return VEC_LEN_FMT.unpack_from(stats.statseg, vector_offset - 8)[0]
+
def get_string(stats, ptr):
- '''Get a string from a VPP vector'''
+ """Get a string from a VPP vector"""
namevector = ptr - stats.base
namevectorlen = get_vec_len(stats, namevector)
if namevector + namevectorlen >= stats.size:
- raise IOError('String overruns stats segment')
- return stats.statseg[namevector:namevector+namevectorlen-1].decode('ascii')
+ raise IOError("String overruns stats segment")
+ return stats.statseg[namevector : namevector + namevectorlen - 1].decode("ascii")
class StatsVector:
- '''A class representing a VPP vector'''
+ """A class representing a VPP vector"""
def __init__(self, stats, ptr, fmt):
self.vec_start = ptr - stats.base
@@ -86,28 +91,35 @@ class StatsVector:
self.stats = stats
if self.vec_start + self.vec_len * self.elementsize >= stats.size:
- raise IOError('Vector overruns stats segment')
+ raise IOError("Vector overruns stats segment")
def __iter__(self):
with self.stats.lock:
- return self.struct.iter_unpack(self.statseg[self.vec_start:self.vec_start +
- self.elementsize*self.vec_len])
+ return self.struct.iter_unpack(
+ self.statseg[
+ self.vec_start : self.vec_start + self.elementsize * self.vec_len
+ ]
+ )
def __getitem__(self, index):
if index > self.vec_len:
- raise IOError('Index beyond end of vector')
+ raise IOError("Index beyond end of vector")
with self.stats.lock:
if self.fmtlen == 1:
- return self.struct.unpack_from(self.statseg, self.vec_start +
- (index * self.elementsize))[0]
- return self.struct.unpack_from(self.statseg, self.vec_start +
- (index * self.elementsize))
+ return self.struct.unpack_from(
+ self.statseg, self.vec_start + (index * self.elementsize)
+ )[0]
+ return self.struct.unpack_from(
+ self.statseg, self.vec_start + (index * self.elementsize)
+ )
+
+
+class VPPStats:
+ """Main class implementing Python access to the VPP statistics segment"""
-class VPPStats():
- '''Main class implementing Python access to the VPP statistics segment'''
# pylint: disable=too-many-instance-attributes
- shared_headerfmt = Struct('QPQQPP')
- default_socketname = '/run/vpp/stats.sock'
+ shared_headerfmt = Struct("QPQQPP")
+ default_socketname = "/run/vpp/stats.sock"
def __init__(self, socketname=default_socketname, timeout=10):
self.socketname = socketname
@@ -120,7 +132,7 @@ class VPPStats():
self.statseg = 0
def connect(self):
- '''Connect to stats segment'''
+ """Connect to stats segment"""
if self.connected:
return
sock = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
@@ -130,61 +142,64 @@ class VPPStats():
sock.close()
stat_result = os.fstat(mfd)
- self.statseg = mmap.mmap(mfd, stat_result.st_size, mmap.PROT_READ, mmap.MAP_SHARED)
+ self.statseg = mmap.mmap(
+ mfd, stat_result.st_size, mmap.PROT_READ, mmap.MAP_SHARED
+ )
os.close(mfd)
self.size = stat_result.st_size
if self.version != 2:
- raise Exception('Incompatbile stat segment version {}'
- .format(self.version))
+ raise Exception("Incompatbile stat segment version {}".format(self.version))
self.refresh()
self.connected = True
def disconnect(self):
- '''Disconnect from stats segment'''
+ """Disconnect from stats segment"""
if self.connected:
self.statseg.close()
self.connected = False
@property
def version(self):
- '''Get version of stats segment'''
+ """Get version of stats segment"""
return self.shared_headerfmt.unpack_from(self.statseg)[0]
@property
def base(self):
- '''Get base pointer of stats segment'''
+ """Get base pointer of stats segment"""
return self.shared_headerfmt.unpack_from(self.statseg)[1]
@property
def epoch(self):
- '''Get current epoch value from stats segment'''
+ """Get current epoch value from stats segment"""
return self.shared_headerfmt.unpack_from(self.statseg)[2]
@property
def in_progress(self):
- '''Get value of in_progress from stats segment'''
+ """Get value of in_progress from stats segment"""
return self.shared_headerfmt.unpack_from(self.statseg)[3]
@property
def directory_vector(self):
- '''Get pointer of directory vector'''
+ """Get pointer of directory vector"""
return self.shared_headerfmt.unpack_from(self.statseg)[4]
- elementfmt = 'IQ128s'
+ elementfmt = "IQ128s"
def refresh(self, blocking=True):
- '''Refresh directory vector cache (epoch changed)'''
+ """Refresh directory vector cache (epoch changed)"""
directory = {}
directory_by_idx = {}
while True:
try:
with self.lock:
self.last_epoch = self.epoch
- for i, direntry in enumerate(StatsVector(self, self.directory_vector, self.elementfmt)):
- path_raw = direntry[2].find(b'\x00')
- path = direntry[2][:path_raw].decode('ascii')
+ for i, direntry in enumerate(
+ StatsVector(self, self.directory_vector, self.elementfmt)
+ ):
+ path_raw = direntry[2].find(b"\x00")
+ path = direntry[2][:path_raw].decode("ascii")
directory[path] = StatsEntry(direntry[0], direntry[1])
directory_by_idx[i] = path
self.directory = directory
@@ -210,14 +225,12 @@ class VPPStats():
def __iter__(self):
return iter(self.directory.items())
-
def set_errors(self, blocking=True):
- '''Return dictionary of error counters > 0'''
+ """Return dictionary of error counters > 0"""
if not self.connected:
self.connect()
- errors = {k: v for k, v in self.directory.items()
- if k.startswith("/err/")}
+ errors = {k: v for k, v in self.directory.items() if k.startswith("/err/")}
result = {}
for k in errors:
try:
@@ -229,23 +242,23 @@ class VPPStats():
return result
def set_errors_str(self, blocking=True):
- '''Return all errors counters > 0 pretty printed'''
- error_string = ['ERRORS:']
+ """Return all errors counters > 0 pretty printed"""
+ error_string = ["ERRORS:"]
error_counters = self.set_errors(blocking)
for k in sorted(error_counters):
- error_string.append('{:<60}{:>10}'.format(k, error_counters[k]))
- return '%s\n' % '\n'.join(error_string)
+ error_string.append("{:<60}{:>10}".format(k, error_counters[k]))
+ return "%s\n" % "\n".join(error_string)
def get_counter(self, name, blocking=True):
- '''Alternative call to __getitem__'''
+ """Alternative call to __getitem__"""
return self.__getitem__(name, blocking)
def get_err_counter(self, name, blocking=True):
- '''Alternative call to __getitem__'''
+ """Alternative call to __getitem__"""
return self.__getitem__(name, blocking).sum()
def ls(self, patterns):
- '''Returns list of counters matching pattern'''
+ """Returns list of counters matching pattern"""
# pylint: disable=invalid-name
if not self.connected:
self.connect()
@@ -255,20 +268,24 @@ class VPPStats():
if self.last_epoch != self.epoch:
self.refresh()
- return [k for k, v in self.directory.items()
- if any(re.match(pattern, k) for pattern in regex)]
+ return [
+ k
+ for k, v in self.directory.items()
+ if any(re.match(pattern, k) for pattern in regex)
+ ]
def dump(self, counters, blocking=True):
- '''Given a list of counters return a dictionary of results'''
+ """Given a list of counters return a dictionary of results"""
if not self.connected:
self.connect()
result = {}
for cnt in counters:
- result[cnt] = self.__getitem__(cnt,blocking)
+ result[cnt] = self.__getitem__(cnt, blocking)
return result
-class StatsLock():
- '''Stat segment optimistic locking'''
+
+class StatsLock:
+ """Stat segment optimistic locking"""
def __init__(self, stats):
self.stats = stats
@@ -283,7 +300,7 @@ class StatsLock():
self.release()
def acquire(self, blocking=True, timeout=-1):
- '''Acquire the lock. Await in progress to go false. Record epoch.'''
+ """Acquire the lock. Await in progress to go false. Record epoch."""
self.epoch = self.stats.epoch
if timeout > 0:
start = time.monotonic()
@@ -296,46 +313,49 @@ class StatsLock():
return True
def release(self):
- '''Check if data read while locked is valid'''
+ """Check if data read while locked is valid"""
if self.stats.in_progress or self.stats.epoch != self.epoch:
- raise IOError('Optimistic lock failed, retry')
+ raise IOError("Optimistic lock failed, retry")
def locked(self):
- '''Not used'''
+ """Not used"""
class StatsCombinedList(list):
- '''Column slicing for Combined counters list'''
+ """Column slicing for Combined counters list"""
def __getitem__(self, item):
- '''Supports partial numpy style 2d support. Slice by column [:,1]'''
+ """Supports partial numpy style 2d support. Slice by column [:,1]"""
if isinstance(item, int):
return list.__getitem__(self, item)
return CombinedList([row[item[1]] for row in self])
+
class CombinedList(list):
- '''Combined Counters 2-dimensional by thread by index of packets/octets'''
+ """Combined Counters 2-dimensional by thread by index of packets/octets"""
def packets(self):
- '''Return column (2nd dimension). Packets for all threads'''
+ """Return column (2nd dimension). Packets for all threads"""
return [pair[0] for pair in self]
def octets(self):
- '''Return column (2nd dimension). Octets for all threads'''
+ """Return column (2nd dimension). Octets for all threads"""
return [pair[1] for pair in self]
def sum_packets(self):
- '''Return column (2nd dimension). Sum of all packets for all threads'''
+ """Return column (2nd dimension). Sum of all packets for all threads"""
return sum(self.packets())
def sum_octets(self):
- '''Return column (2nd dimension). Sum of all octets for all threads'''
+ """Return column (2nd dimension). Sum of all octets for all threads"""
return sum(self.octets())
+
class StatsTuple(tuple):
- '''A Combined vector tuple (packets, octets)'''
+ """A Combined vector tuple (packets, octets)"""
+
def __init__(self, data):
- self.dictionary = {'packets': data[0], 'bytes': data[1]}
+ self.dictionary = {"packets": data[0], "bytes": data[1]}
super().__init__()
def __repr__(self):
@@ -344,28 +364,32 @@ class StatsTuple(tuple):
def __getitem__(self, item):
if isinstance(item, int):
return tuple.__getitem__(self, item)
- if item == 'packets':
+ if item == "packets":
return tuple.__getitem__(self, 0)
return tuple.__getitem__(self, 1)
+
class StatsSimpleList(list):
- '''Simple Counters 2-dimensional by thread by index of packets'''
+ """Simple Counters 2-dimensional by thread by index of packets"""
def __getitem__(self, item):
- '''Supports partial numpy style 2d support. Slice by column [:,1]'''
+ """Supports partial numpy style 2d support. Slice by column [:,1]"""
if isinstance(item, int):
return list.__getitem__(self, item)
return SimpleList([row[item[1]] for row in self])
+
class SimpleList(list):
- '''Simple counter'''
+ """Simple counter"""
def sum(self):
- '''Sum the vector'''
+ """Sum the vector"""
return sum(self)
-class StatsEntry():
- '''An individual stats entry'''
+
+class StatsEntry:
+ """An individual stats entry"""
+
# pylint: disable=unused-argument,no-self-use
def __init__(self, stattype, statvalue):
@@ -386,115 +410,128 @@ class StatsEntry():
self.function = self.illegal
def illegal(self, stats):
- '''Invalid or unknown counter type'''
+ """Invalid or unknown counter type"""
return None
def scalar(self, stats):
- '''Scalar counter'''
+ """Scalar counter"""
return self.value
def simple(self, stats):
- '''Simple counter'''
+ """Simple counter"""
counter = StatsSimpleList()
- for threads in StatsVector(stats, self.value, 'P'):
- clist = [v[0] for v in StatsVector(stats, threads[0], 'Q')]
+ for threads in StatsVector(stats, self.value, "P"):
+ clist = [v[0] for v in StatsVector(stats, threads[0], "Q")]
counter.append(clist)
return counter
def combined(self, stats):
- '''Combined counter'''
+ """Combined counter"""
counter = StatsCombinedList()
- for threads in StatsVector(stats, self.value, 'P'):
- clist = [StatsTuple(cnt) for cnt in StatsVector(stats, threads[0], 'QQ')]
+ for threads in StatsVector(stats, self.value, "P"):
+ clist = [StatsTuple(cnt) for cnt in StatsVector(stats, threads[0], "QQ")]
counter.append(clist)
return counter
def name(self, stats):
- '''Name counter'''
+ """Name counter"""
counter = []
- for name in StatsVector(stats, self.value, 'P'):
+ for name in StatsVector(stats, self.value, "P"):
if name[0]:
counter.append(get_string(stats, name[0]))
return counter
- SYMLINK_FMT1 = Struct('II')
- SYMLINK_FMT2 = Struct('Q')
+ SYMLINK_FMT1 = Struct("II")
+ SYMLINK_FMT2 = Struct("Q")
+
def symlink(self, stats):
- '''Symlink counter'''
+ """Symlink counter"""
b = self.SYMLINK_FMT2.pack(self.value)
index1, index2 = self.SYMLINK_FMT1.unpack(b)
name = stats.directory_by_idx[index1]
- return stats[name][:,index2]
+ return stats[name][:, index2]
def get_counter(self, stats):
- '''Return a list of counters'''
+ """Return a list of counters"""
if stats:
return self.function(stats)
+
class TestStats(unittest.TestCase):
- '''Basic statseg tests'''
+ """Basic statseg tests"""
def setUp(self):
- '''Connect to statseg'''
+ """Connect to statseg"""
self.stat = VPPStats()
self.stat.connect()
self.profile = cProfile.Profile()
self.profile.enable()
def tearDown(self):
- '''Disconnect from statseg'''
+ """Disconnect from statseg"""
self.stat.disconnect()
profile = Stats(self.profile)
profile.strip_dirs()
- profile.sort_stats('cumtime')
+ profile.sort_stats("cumtime")
profile.print_stats()
print("\n--->>>")
def test_counters(self):
- '''Test access to statseg'''
-
- print('/err/abf-input-ip4/missed', self.stat['/err/abf-input-ip4/missed'])
- print('/sys/heartbeat', self.stat['/sys/heartbeat'])
- print('/if/names', self.stat['/if/names'])
- print('/if/rx-miss', self.stat['/if/rx-miss'])
- print('/if/rx-miss', self.stat['/if/rx-miss'][1])
- print('/nat44-ed/out2in/slowpath/drops', self.stat['/nat44-ed/out2in/slowpath/drops'])
+ """Test access to statseg"""
+
+ print("/err/abf-input-ip4/missed", self.stat["/err/abf-input-ip4/missed"])
+ print("/sys/heartbeat", self.stat["/sys/heartbeat"])
+ print("/if/names", self.stat["/if/names"])
+ print("/if/rx-miss", self.stat["/if/rx-miss"])
+ print("/if/rx-miss", self.stat["/if/rx-miss"][1])
+ print(
+ "/nat44-ed/out2in/slowpath/drops",
+ self.stat["/nat44-ed/out2in/slowpath/drops"],
+ )
with self.assertRaises(KeyError):
- print('NO SUCH COUNTER', self.stat['foobar'])
- print('/if/rx', self.stat.get_counter('/if/rx'))
- print('/err/ethernet-input/no_error',
- self.stat.get_counter('/err/ethernet-input/no_error'))
+ print("NO SUCH COUNTER", self.stat["foobar"])
+ print("/if/rx", self.stat.get_counter("/if/rx"))
+ print(
+ "/err/ethernet-input/no_error",
+ self.stat.get_counter("/err/ethernet-input/no_error"),
+ )
def test_column(self):
- '''Test column slicing'''
-
- print('/if/rx-miss', self.stat['/if/rx-miss'])
- print('/if/rx', self.stat['/if/rx']) # All interfaces for thread #1
- print('/if/rx thread #1', self.stat['/if/rx'][0]) # All interfaces for thread #1
- print('/if/rx thread #1, interface #1',
- self.stat['/if/rx'][0][1]) # All interfaces for thread #1
- print('/if/rx if_index #1', self.stat['/if/rx'][:, 1])
- print('/if/rx if_index #1 packets', self.stat['/if/rx'][:, 1].packets())
- print('/if/rx if_index #1 packets', self.stat['/if/rx'][:, 1].sum_packets())
- print('/if/rx if_index #1 packets', self.stat['/if/rx'][:, 1].octets())
- print('/if/rx-miss', self.stat['/if/rx-miss'])
- print('/if/rx-miss if_index #1 packets', self.stat['/if/rx-miss'][:, 1].sum())
- print('/if/rx if_index #1 packets', self.stat['/if/rx'][0][1]['packets'])
+ """Test column slicing"""
+
+ print("/if/rx-miss", self.stat["/if/rx-miss"])
+ print("/if/rx", self.stat["/if/rx"]) # All interfaces for thread #1
+ print(
+ "/if/rx thread #1", self.stat["/if/rx"][0]
+ ) # All interfaces for thread #1
+ print(
+ "/if/rx thread #1, interface #1", self.stat["/if/rx"][0][1]
+ ) # All interfaces for thread #1
+ print("/if/rx if_index #1", self.stat["/if/rx"][:, 1])
+ print("/if/rx if_index #1 packets", self.stat["/if/rx"][:, 1].packets())
+ print("/if/rx if_index #1 packets", self.stat["/if/rx"][:, 1].sum_packets())
+ print("/if/rx if_index #1 packets", self.stat["/if/rx"][:, 1].octets())
+ print("/if/rx-miss", self.stat["/if/rx-miss"])
+ print("/if/rx-miss if_index #1 packets", self.stat["/if/rx-miss"][:, 1].sum())
+ print("/if/rx if_index #1 packets", self.stat["/if/rx"][0][1]["packets"])
def test_nat44(self):
- '''Test the nat counters'''
+ """Test the nat counters"""
- print('/nat44-ei/ha/del-event-recv', self.stat['/nat44-ei/ha/del-event-recv'])
- print('/err/nat44-ei-ha/pkts-processed', self.stat['/err/nat44-ei-ha/pkts-processed'].sum())
+ print("/nat44-ei/ha/del-event-recv", self.stat["/nat44-ei/ha/del-event-recv"])
+ print(
+ "/err/nat44-ei-ha/pkts-processed",
+ self.stat["/err/nat44-ei-ha/pkts-processed"].sum(),
+ )
def test_legacy(self):
- '''Legacy interface'''
+ """Legacy interface"""
directory = self.stat.ls(["^/if", "/err/ip4-input", "/sys/node/ip4-input"])
data = self.stat.dump(directory)
print(data)
- print('Looking up sys node')
+ print("Looking up sys node")
directory = self.stat.ls(["^/sys/node"])
- print('Dumping sys node')
+ print("Dumping sys node")
data = self.stat.dump(directory)
print(data)
directory = self.stat.ls(["^/foobar"])
@@ -502,18 +539,19 @@ class TestStats(unittest.TestCase):
print(data)
def test_sys_nodes(self):
- '''Test /sys/nodes'''
- counters = self.stat.ls('^/sys/node')
- print('COUNTERS:', counters)
- print('/sys/node', self.stat.dump(counters))
- print('/net/route/to', self.stat['/net/route/to'])
+ """Test /sys/nodes"""
+ counters = self.stat.ls("^/sys/node")
+ print("COUNTERS:", counters)
+ print("/sys/node", self.stat.dump(counters))
+ print("/net/route/to", self.stat["/net/route/to"])
def test_symlink(self):
- '''Symbolic links'''
- print('/interface/local0/rx', self.stat['/interfaces/local0/rx'])
- print('/sys/nodes/unix-epoll-input', self.stat['/nodes/unix-epoll-input/calls'])
+ """Symbolic links"""
+ print("/interface/local0/rx", self.stat["/interfaces/local0/rx"])
+ print("/sys/nodes/unix-epoll-input", self.stat["/nodes/unix-epoll-input/calls"])
+
-if __name__ == '__main__':
+if __name__ == "__main__":
import cProfile
from pstats import Stats
diff --git a/src/vpp-api/python/vpp_papi/vpp_transport_socket.py b/src/vpp-api/python/vpp_papi/vpp_transport_socket.py
index c82b8c365a1..3a8c332a00a 100644
--- a/src/vpp-api/python/vpp_papi/vpp_transport_socket.py
+++ b/src/vpp-api/python/vpp_papi/vpp_transport_socket.py
@@ -9,7 +9,7 @@ import multiprocessing
import queue
import logging
-logger = logging.getLogger('vpp_papi.transport')
+logger = logging.getLogger("vpp_papi.transport")
logger.addHandler(logging.NullHandler())
@@ -26,7 +26,7 @@ class VppTransport:
self.read_timeout = read_timeout if read_timeout > 0 else None
self.parent = parent
self.server_address = server_address
- self.header = struct.Struct('>QII')
+ self.header = struct.Struct(">QII")
self.message_table = {}
# These queues can be accessed async.
# They are always up, but replaced on connect.
@@ -41,11 +41,10 @@ class VppTransport:
def msg_thread_func(self):
while True:
try:
- rlist, _, _ = select.select([self.socket,
- self.sque._reader], [], [])
+ rlist, _, _ = select.select([self.socket, self.sque._reader], [], [])
except socket.error:
# Terminate thread
- logging.error('select failed')
+ logging.error("select failed")
self.q.put(None)
return
@@ -71,8 +70,7 @@ class VppTransport:
else:
self.parent.msg_handler_async(msg)
else:
- raise VppTransportSocketIOError(
- 2, 'Unknown response from select')
+ raise VppTransportSocketIOError(2, "Unknown response from select")
def connect(self, name, pfx, msg_handler, rx_qlen):
# TODO: Reorder the actions and add "roll-backs",
@@ -80,7 +78,8 @@ class VppTransport:
if self.message_thread is not None:
raise VppTransportSocketIOError(
- 1, "PAPI socket transport connect: Need to disconnect first.")
+ 1, "PAPI socket transport connect: Need to disconnect first."
+ )
# Create a UDS socket
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
@@ -107,19 +106,17 @@ class VppTransport:
self.message_thread = threading.Thread(target=self.msg_thread_func)
# Initialise sockclnt_create
- sockclnt_create = self.parent.messages['sockclnt_create']
- sockclnt_create_reply = self.parent.messages['sockclnt_create_reply']
+ sockclnt_create = self.parent.messages["sockclnt_create"]
+ sockclnt_create_reply = self.parent.messages["sockclnt_create_reply"]
- args = {'_vl_msg_id': 15,
- 'name': name,
- 'context': 124}
+ args = {"_vl_msg_id": 15, "name": name, "context": 124}
b = sockclnt_create.pack(args)
self.write(b)
msg = self._read()
hdr, length = self.parent.header.unpack(msg, 0)
if hdr.msgid != 16:
# TODO: Add first numeric argument.
- raise VppTransportSocketIOError('Invalid reply message')
+ raise VppTransportSocketIOError("Invalid reply message")
r, length = sockclnt_create_reply.unpack(msg)
self.socket_index = r.index
@@ -184,7 +181,7 @@ class VppTransport:
def write(self, buf):
"""Send a binary-packed message to VPP."""
if not self.connected:
- raise VppTransportSocketIOError(1, 'Not connected')
+ raise VppTransportSocketIOError(1, "Not connected")
# Send header
header = self.header.pack(0, len(buf), 0)
@@ -192,8 +189,7 @@ class VppTransport:
self.socket.sendall(header)
self.socket.sendall(buf)
except socket.error as err:
- raise VppTransportSocketIOError(1, 'Sendall error: {err!r}'.format(
- err=err))
+ raise VppTransportSocketIOError(1, "Sendall error: {err!r}".format(err=err))
def _read_fixed(self, size):
"""Repeat receive until fixed size is read. Return empty on error."""
@@ -223,11 +219,11 @@ class VppTransport:
msg = self._read_fixed(hdrlen)
if hdrlen == len(msg):
return msg
- raise VppTransportSocketIOError(1, 'Unknown socket read error')
+ raise VppTransportSocketIOError(1, "Unknown socket read error")
def read(self, timeout=None):
if not self.connected:
- raise VppTransportSocketIOError(1, 'Not connected')
+ raise VppTransportSocketIOError(1, "Not connected")
if timeout is None:
timeout = self.read_timeout
try:
diff --git a/src/vpp-api/vapi/vapi_c_gen.py b/src/vpp-api/vapi/vapi_c_gen.py
index debd7345f60..2978ebd2077 100755
--- a/src/vpp-api/vapi/vapi_c_gen.py
+++ b/src/vpp-api/vapi/vapi_c_gen.py
@@ -5,8 +5,17 @@ import inspect
import os
import sys
import logging
-from vapi_json_parser import Field, Struct, Enum, Union, Message, JsonParser,\
- SimpleType, StructType, Alias
+from vapi_json_parser import (
+ Field,
+ Struct,
+ Enum,
+ Union,
+ Message,
+ JsonParser,
+ SimpleType,
+ StructType,
+ Alias,
+)
class CField(Field):
@@ -14,54 +23,63 @@ class CField(Field):
return "vapi_type_%s" % self.name
def get_c_def(self):
- if self.type.get_c_name() == 'vl_api_string_t':
+ if self.type.get_c_name() == "vl_api_string_t":
if self.len:
return "u8 %s[%d];" % (self.name, self.len)
else:
return "vl_api_string_t %s;" % (self.name)
else:
if self.len is not None and type(self.len) != dict:
- return "%s %s[%d];" % (self.type.get_c_name(), self.name,
- self.len)
+ return "%s %s[%d];" % (self.type.get_c_name(), self.name, self.len)
else:
return "%s %s;" % (self.type.get_c_name(), self.name)
def get_swap_to_be_code(self, struct, var):
if self.len is not None and type(self.len) != dict:
if self.len > 0:
- return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
- " while(0);" % (
- self.len,
- self.type.get_swap_to_be_code(struct, "%s[i]" % var))
+ return (
+ "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"
+ " while(0);"
+ % (self.len, self.type.get_swap_to_be_code(struct, "%s[i]" % var))
+ )
else:
if self.nelem_field.needs_byte_swap():
nelem_field = "%s(%s%s)" % (
self.nelem_field.type.get_swap_to_host_func_name(),
- struct, self.nelem_field.name)
+ struct,
+ self.nelem_field.name,
+ )
else:
nelem_field = "%s%s" % (struct, self.nelem_field.name)
return (
"do { unsigned i; for (i = 0; i < %s; ++i) { %s } }"
- " while(0);" %
- (nelem_field, self.type.get_swap_to_be_code(
- struct, "%s[i]" % var)))
+ " while(0);"
+ % (
+ nelem_field,
+ self.type.get_swap_to_be_code(struct, "%s[i]" % var),
+ )
+ )
return self.type.get_swap_to_be_code(struct, "%s" % var)
def get_swap_to_host_code(self, struct, var):
if self.len is not None and type(self.len) != dict:
if self.len > 0:
- return "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"\
- " while(0);" % (
- self.len,
- self.type.get_swap_to_host_code(struct, "%s[i]" % var))
+ return (
+ "do { unsigned i; for (i = 0; i < %d; ++i) { %s } }"
+ " while(0);"
+ % (self.len, self.type.get_swap_to_host_code(struct, "%s[i]" % var))
+ )
else:
# nelem_field already swapped to host here...
return (
"do { unsigned i; for (i = 0; i < %s%s; ++i) { %s } }"
- " while(0);" %
- (struct, self.nelem_field.name,
- self.type.get_swap_to_host_code(
- struct, "%s[i]" % var)))
+ " while(0);"
+ % (
+ struct,
+ self.nelem_field.name,
+ self.type.get_swap_to_host_code(struct, "%s[i]" % var),
+ )
+ )
return self.type.get_swap_to_host_code(struct, "%s" % var)
def needs_byte_swap(self):
@@ -82,10 +100,14 @@ class CField(Field):
def get_vla_calc_size_code(self, prefix, path):
if self.is_vla():
- result = ["sizeof(%s.%s[0]) * %s" % (
- ".".join([prefix] + path),
- self.name,
- self.get_vla_field_length_name(path))]
+ result = [
+ "sizeof(%s.%s[0]) * %s"
+ % (
+ ".".join([prefix] + path),
+ self.name,
+ self.get_vla_field_length_name(path),
+ )
+ ]
else:
result = []
if self.type.has_vla():
@@ -96,10 +118,14 @@ class CField(Field):
def get_vla_assign_code(self, prefix, path):
result = []
if self.is_vla():
- result.append("%s.%s = %s" % (
- ".".join([prefix] + path),
- self.nelem_field.name,
- self.get_vla_field_length_name(path)))
+ result.append(
+ "%s.%s = %s"
+ % (
+ ".".join([prefix] + path),
+ self.nelem_field.name,
+ self.get_vla_field_length_name(path),
+ )
+ )
if self.type.has_vla():
t = self.type.get_vla_assign_code(prefix, path + [self.name])
result.extend(t)
@@ -113,52 +139,75 @@ class CAlias(CField):
def get_c_def(self):
if self.len is not None:
return "typedef %s vapi_type_%s[%d];" % (
- self.type.get_c_name(), self.name, self.len)
+ self.type.get_c_name(),
+ self.name,
+ self.len,
+ )
else:
- return "typedef %s vapi_type_%s;" % (
- self.type.get_c_name(), self.name)
+ return "typedef %s vapi_type_%s;" % (self.type.get_c_name(), self.name)
class CStruct(Struct):
def get_c_def(self):
- return "\n".join([
- "typedef struct __attribute__((__packed__)) {\n%s" % (
- "\n".join([" %s" % x.get_c_def()
- for x in self.fields])),
- "} %s;" % self.get_c_name()])
+ return "\n".join(
+ [
+ "typedef struct __attribute__((__packed__)) {\n%s"
+ % ("\n".join([" %s" % x.get_c_def() for x in self.fields])),
+ "} %s;" % self.get_c_name(),
+ ]
+ )
def get_vla_assign_code(self, prefix, path):
- return [x for f in self.fields if f.has_vla()
- for x in f.get_vla_assign_code(prefix, path)]
+ return [
+ x
+ for f in self.fields
+ if f.has_vla()
+ for x in f.get_vla_assign_code(prefix, path)
+ ]
def get_alloc_vla_param_names(self, path):
- return [x for f in self.fields
- if f.has_vla()
- for x in f.get_alloc_vla_param_names(path)]
+ return [
+ x
+ for f in self.fields
+ if f.has_vla()
+ for x in f.get_alloc_vla_param_names(path)
+ ]
def get_vla_calc_size_code(self, prefix, path):
- return [x for f in self.fields if f.has_vla()
- for x in f.get_vla_calc_size_code(prefix, path)]
+ return [
+ x
+ for f in self.fields
+ if f.has_vla()
+ for x in f.get_vla_calc_size_code(prefix, path)
+ ]
-class CSimpleType (SimpleType):
+class CSimpleType(SimpleType):
swap_to_be_dict = {
- 'i16': 'htobe16', 'u16': 'htobe16',
- 'i32': 'htobe32', 'u32': 'htobe32',
- 'i64': 'htobe64', 'u64': 'htobe64',
+ "i16": "htobe16",
+ "u16": "htobe16",
+ "i32": "htobe32",
+ "u32": "htobe32",
+ "i64": "htobe64",
+ "u64": "htobe64",
}
swap_to_host_dict = {
- 'i16': 'be16toh', 'u16': 'be16toh',
- 'i32': 'be32toh', 'u32': 'be32toh',
- 'i64': 'be64toh', 'u64': 'be64toh',
+ "i16": "be16toh",
+ "u16": "be16toh",
+ "i32": "be32toh",
+ "u32": "be32toh",
+ "i64": "be64toh",
+ "u64": "be64toh",
}
__packed = "__attribute__((packed))"
pack_dict = {
- 'i8': __packed, 'u8': __packed,
- 'i16': __packed, 'u16': __packed,
+ "i8": __packed,
+ "u8": __packed,
+ "i16": __packed,
+ "u16": __packed,
}
def get_c_name(self):
@@ -175,15 +224,21 @@ class CSimpleType (SimpleType):
def get_swap_to_be_code(self, struct, var, cast=None):
x = "%s%s" % (struct, var)
- return "%s = %s%s(%s);" % (x,
- "(%s)" % cast if cast else "",
- self.get_swap_to_be_func_name(), x)
+ return "%s = %s%s(%s);" % (
+ x,
+ "(%s)" % cast if cast else "",
+ self.get_swap_to_be_func_name(),
+ x,
+ )
def get_swap_to_host_code(self, struct, var, cast=None):
x = "%s%s" % (struct, var)
- return "%s = %s%s(%s);" % (x,
- "(%s)" % cast if cast else "",
- self.get_swap_to_host_func_name(), x)
+ return "%s = %s%s(%s);" % (
+ x,
+ "(%s)" % cast if cast else "",
+ self.get_swap_to_host_func_name(),
+ x,
+ )
def needs_byte_swap(self):
try:
@@ -205,7 +260,7 @@ class CEnum(Enum):
return "typedef enum {\n%s\n} %s %s;" % (
"\n".join([" %s = %s," % (i, j) for i, j in self.value_pairs]),
self.type.get_packed(),
- self.get_c_name()
+ self.get_c_name(),
)
def needs_byte_swap(self):
@@ -224,16 +279,15 @@ class CUnion(Union):
def get_c_def(self):
return "typedef union {\n%s\n} %s;" % (
- "\n".join([" %s %s;" % (i.get_c_name(), j)
- for i, j in self.type_pairs]),
- self.get_c_name()
+ "\n".join([" %s %s;" % (i.get_c_name(), j) for i, j in self.type_pairs]),
+ self.get_c_name(),
)
def needs_byte_swap(self):
return False
-class CStructType (StructType, CStruct):
+class CStructType(StructType, CStruct):
def get_c_name(self):
return "vapi_type_%s" % self.name
@@ -244,27 +298,36 @@ class CStructType (StructType, CStruct):
return "%s_ntoh" % self.get_c_name()
def get_swap_to_be_func_decl(self):
- return "void %s(%s *msg)" % (
- self.get_swap_to_be_func_name(), self.get_c_name())
+ return "void %s(%s *msg)" % (self.get_swap_to_be_func_name(), self.get_c_name())
def get_swap_to_be_func_def(self):
return "%s\n{\n%s\n}" % (
self.get_swap_to_be_func_decl(),
- "\n".join([
- " %s" % p.get_swap_to_be_code("msg->", "%s" % p.name)
- for p in self.fields if p.needs_byte_swap()]),
+ "\n".join(
+ [
+ " %s" % p.get_swap_to_be_code("msg->", "%s" % p.name)
+ for p in self.fields
+ if p.needs_byte_swap()
+ ]
+ ),
)
def get_swap_to_host_func_decl(self):
return "void %s(%s *msg)" % (
- self.get_swap_to_host_func_name(), self.get_c_name())
+ self.get_swap_to_host_func_name(),
+ self.get_c_name(),
+ )
def get_swap_to_host_func_def(self):
return "%s\n{\n%s\n}" % (
self.get_swap_to_host_func_decl(),
- "\n".join([
- " %s" % p.get_swap_to_host_code("msg->", "%s" % p.name)
- for p in self.fields if p.needs_byte_swap()]),
+ "\n".join(
+ [
+ " %s" % p.get_swap_to_host_code("msg->", "%s" % p.name)
+ for p in self.fields
+ if p.needs_byte_swap()
+ ]
+ ),
)
def get_swap_to_be_code(self, struct, var):
@@ -280,13 +343,11 @@ class CStructType (StructType, CStruct):
return False
-class CMessage (Message):
+class CMessage(Message):
def __init__(self, logger, definition, json_parser):
super(CMessage, self).__init__(logger, definition, json_parser)
self.payload_members = [
- " %s" % p.get_c_def()
- for p in self.fields
- if p.type != self.header
+ " %s" % p.get_c_def() for p in self.fields if p.type != self.header
]
def has_payload(self):
@@ -305,46 +366,65 @@ class CMessage (Message):
return "vapi_alloc_%s" % self.name
def get_alloc_vla_param_names(self):
- return [x for f in self.fields
- if f.has_vla()
- for x in f.get_alloc_vla_param_names([])]
+ return [
+ x
+ for f in self.fields
+ if f.has_vla()
+ for x in f.get_alloc_vla_param_names([])
+ ]
def get_alloc_func_decl(self):
return "%s* %s(struct vapi_ctx_s *ctx%s)" % (
self.get_c_name(),
self.get_alloc_func_name(),
- "".join([", size_t %s" % n for n in
- self.get_alloc_vla_param_names()]))
+ "".join([", size_t %s" % n for n in self.get_alloc_vla_param_names()]),
+ )
def get_alloc_func_def(self):
extra = []
- if self.header.has_field('client_index'):
- extra.append(
- " msg->header.client_index = vapi_get_client_index(ctx);")
- if self.header.has_field('context'):
+ if self.header.has_field("client_index"):
+ extra.append(" msg->header.client_index = vapi_get_client_index(ctx);")
+ if self.header.has_field("context"):
extra.append(" msg->header.context = 0;")
- return "\n".join([
- "%s" % self.get_alloc_func_decl(),
- "{",
- " %s *msg = NULL;" % self.get_c_name(),
- " const size_t size = sizeof(%s)%s;" % (
- self.get_c_name(),
- "".join([" + %s" % x for f in self.fields if f.has_vla()
- for x in f.get_vla_calc_size_code("msg->payload",
- [])])),
- " /* cast here required to play nicely with C++ world ... */",
- " msg = (%s*)vapi_msg_alloc(ctx, size);" % self.get_c_name(),
- " if (!msg) {",
- " return NULL;",
- " }",
- ] + extra + [
- " msg->header._vl_msg_id = vapi_lookup_vl_msg_id(ctx, %s);" %
- self.get_msg_id_name(),
- "".join([" %s;\n" % line
- for f in self.fields if f.has_vla()
- for line in f.get_vla_assign_code("msg->payload", [])]),
- " return msg;",
- "}"])
+ return "\n".join(
+ [
+ "%s" % self.get_alloc_func_decl(),
+ "{",
+ " %s *msg = NULL;" % self.get_c_name(),
+ " const size_t size = sizeof(%s)%s;"
+ % (
+ self.get_c_name(),
+ "".join(
+ [
+ " + %s" % x
+ for f in self.fields
+ if f.has_vla()
+ for x in f.get_vla_calc_size_code("msg->payload", [])
+ ]
+ ),
+ ),
+ " /* cast here required to play nicely with C++ world ... */",
+ " msg = (%s*)vapi_msg_alloc(ctx, size);" % self.get_c_name(),
+ " if (!msg) {",
+ " return NULL;",
+ " }",
+ ]
+ + extra
+ + [
+ " msg->header._vl_msg_id = vapi_lookup_vl_msg_id(ctx, %s);"
+ % self.get_msg_id_name(),
+ "".join(
+ [
+ " %s;\n" % line
+ for f in self.fields
+ if f.has_vla()
+ for line in f.get_vla_assign_code("msg->payload", [])
+ ]
+ ),
+ " return msg;",
+ "}",
+ ]
+ )
def get_calc_msg_size_func_name(self):
return "vapi_calc_%s_msg_size" % self.name
@@ -352,21 +432,26 @@ class CMessage (Message):
def get_calc_msg_size_func_decl(self):
return "uword %s(%s *msg)" % (
self.get_calc_msg_size_func_name(),
- self.get_c_name())
+ self.get_c_name(),
+ )
def get_calc_msg_size_func_def(self):
- return "\n".join([
- "%s" % self.get_calc_msg_size_func_decl(),
- "{",
- " return sizeof(*msg)%s;" %
- "".join(["+ msg->payload.%s * sizeof(msg->payload.%s[0])" % (
- f.nelem_field.name,
- f.name)
- for f in self.fields
- if f.nelem_field is not None
- ]),
- "}",
- ])
+ return "\n".join(
+ [
+ "%s" % self.get_calc_msg_size_func_decl(),
+ "{",
+ " return sizeof(*msg)%s;"
+ % "".join(
+ [
+ "+ msg->payload.%s * sizeof(msg->payload.%s[0])"
+ % (f.nelem_field.name, f.name)
+ for f in self.fields
+ if f.nelem_field is not None
+ ]
+ ),
+ "}",
+ ]
+ )
def get_verify_msg_size_func_name(self):
return f"vapi_verify_{self.name}_msg_size"
@@ -374,7 +459,8 @@ class CMessage (Message):
def get_verify_msg_size_func_decl(self):
return "int %s(%s *msg, uword buf_size)" % (
self.get_verify_msg_size_func_name(),
- self.get_c_name())
+ self.get_c_name(),
+ )
def get_verify_msg_size_func_def(self):
return inspect.cleandoc(
@@ -397,29 +483,39 @@ class CMessage (Message):
}}
return 0;
}}
- """)
+ """
+ )
def get_c_def(self):
if self.has_payload():
- return "\n".join([
- "typedef struct __attribute__ ((__packed__)) {",
- "%s " %
- "\n".join(self.payload_members),
- "} %s;" % self.get_payload_struct_name(),
- "",
- "typedef struct __attribute__ ((__packed__)) {",
- (" %s %s;" % (self.header.get_c_name(),
- self.fields[0].name)
- if self.header is not None else ""),
- " %s payload;" % self.get_payload_struct_name(),
- "} %s;" % self.get_c_name(), ])
+ return "\n".join(
+ [
+ "typedef struct __attribute__ ((__packed__)) {",
+ "%s " % "\n".join(self.payload_members),
+ "} %s;" % self.get_payload_struct_name(),
+ "",
+ "typedef struct __attribute__ ((__packed__)) {",
+ (
+ " %s %s;" % (self.header.get_c_name(), self.fields[0].name)
+ if self.header is not None
+ else ""
+ ),
+ " %s payload;" % self.get_payload_struct_name(),
+ "} %s;" % self.get_c_name(),
+ ]
+ )
else:
- return "\n".join([
- "typedef struct __attribute__ ((__packed__)) {",
- (" %s %s;" % (self.header.get_c_name(),
- self.fields[0].name)
- if self.header is not None else ""),
- "} %s;" % self.get_c_name(), ])
+ return "\n".join(
+ [
+ "typedef struct __attribute__ ((__packed__)) {",
+ (
+ " %s %s;" % (self.header.get_c_name(), self.fields[0].name)
+ if self.header is not None
+ else ""
+ ),
+ "} %s;" % self.get_c_name(),
+ ]
+ )
def get_swap_payload_to_host_func_name(self):
return "%s_payload_ntoh" % self.get_c_name()
@@ -430,29 +526,37 @@ class CMessage (Message):
def get_swap_payload_to_host_func_decl(self):
return "void %s(%s *payload)" % (
self.get_swap_payload_to_host_func_name(),
- self.get_payload_struct_name())
+ self.get_payload_struct_name(),
+ )
def get_swap_payload_to_be_func_decl(self):
return "void %s(%s *payload)" % (
self.get_swap_payload_to_be_func_name(),
- self.get_payload_struct_name())
+ self.get_payload_struct_name(),
+ )
def get_swap_payload_to_be_func_def(self):
return "%s\n{\n%s\n}" % (
self.get_swap_payload_to_be_func_decl(),
- "\n".join([
- " %s" % p.get_swap_to_be_code("payload->", "%s" % p.name)
- for p in self.fields
- if p.needs_byte_swap() and p.type != self.header]),
+ "\n".join(
+ [
+ " %s" % p.get_swap_to_be_code("payload->", "%s" % p.name)
+ for p in self.fields
+ if p.needs_byte_swap() and p.type != self.header
+ ]
+ ),
)
def get_swap_payload_to_host_func_def(self):
return "%s\n{\n%s\n}" % (
self.get_swap_payload_to_host_func_decl(),
- "\n".join([
- " %s" % p.get_swap_to_host_code("payload->", "%s" % p.name)
- for p in self.fields
- if p.needs_byte_swap() and p.type != self.header]),
+ "\n".join(
+ [
+ " %s" % p.get_swap_to_host_code("payload->", "%s" % p.name)
+ for p in self.fields
+ if p.needs_byte_swap() and p.type != self.header
+ ]
+ ),
)
def get_swap_to_host_func_name(self):
@@ -463,37 +567,50 @@ class CMessage (Message):
def get_swap_to_host_func_decl(self):
return "void %s(%s *msg)" % (
- self.get_swap_to_host_func_name(), self.get_c_name())
+ self.get_swap_to_host_func_name(),
+ self.get_c_name(),
+ )
def get_swap_to_be_func_decl(self):
- return "void %s(%s *msg)" % (
- self.get_swap_to_be_func_name(), self.get_c_name())
+ return "void %s(%s *msg)" % (self.get_swap_to_be_func_name(), self.get_c_name())
def get_swap_to_be_func_def(self):
- return "\n".join([
- "%s" % self.get_swap_to_be_func_decl(),
- "{",
- (" VAPI_DBG(\"Swapping `%s'@%%p to big endian\", msg);" %
- self.get_c_name()),
- " %s(&msg->header);" % self.header.get_swap_to_be_func_name()
- if self.header is not None else "",
- " %s(&msg->payload);" % self.get_swap_payload_to_be_func_name()
- if self.has_payload() else "",
- "}",
- ])
+ return "\n".join(
+ [
+ "%s" % self.get_swap_to_be_func_decl(),
+ "{",
+ (
+ ' VAPI_DBG("Swapping `%s\'@%%p to big endian", msg);'
+ % self.get_c_name()
+ ),
+ " %s(&msg->header);" % self.header.get_swap_to_be_func_name()
+ if self.header is not None
+ else "",
+ " %s(&msg->payload);" % self.get_swap_payload_to_be_func_name()
+ if self.has_payload()
+ else "",
+ "}",
+ ]
+ )
def get_swap_to_host_func_def(self):
- return "\n".join([
- "%s" % self.get_swap_to_host_func_decl(),
- "{",
- (" VAPI_DBG(\"Swapping `%s'@%%p to host byte order\", msg);" %
- self.get_c_name()),
- " %s(&msg->header);" % self.header.get_swap_to_host_func_name()
- if self.header is not None else "",
- " %s(&msg->payload);" % self.get_swap_payload_to_host_func_name()
- if self.has_payload() else "",
- "}",
- ])
+ return "\n".join(
+ [
+ "%s" % self.get_swap_to_host_func_decl(),
+ "{",
+ (
+ ' VAPI_DBG("Swapping `%s\'@%%p to host byte order", msg);'
+ % self.get_c_name()
+ ),
+ " %s(&msg->header);" % self.header.get_swap_to_host_func_name()
+ if self.header is not None
+ else "",
+ " %s(&msg->payload);" % self.get_swap_payload_to_host_func_name()
+ if self.has_payload()
+ else "",
+ "}",
+ ]
+ )
def get_op_func_name(self):
return "vapi_%s" % self.name
@@ -502,111 +619,126 @@ class CMessage (Message):
if self.reply.has_payload():
return "vapi_error_e %s(%s)" % (
self.get_op_func_name(),
- ",\n ".join([
- 'struct vapi_ctx_s *ctx',
- '%s *msg' % self.get_c_name(),
- 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
- ' void *callback_ctx',
- ' vapi_error_e rv',
- ' bool is_last',
- ' %s *reply)' %
- self.reply.get_payload_struct_name(),
- 'void *callback_ctx',
- ])
+ ",\n ".join(
+ [
+ "struct vapi_ctx_s *ctx",
+ "%s *msg" % self.get_c_name(),
+ "vapi_error_e (*callback)(struct vapi_ctx_s *ctx",
+ " void *callback_ctx",
+ " vapi_error_e rv",
+ " bool is_last",
+ " %s *reply)"
+ % self.reply.get_payload_struct_name(),
+ "void *callback_ctx",
+ ]
+ ),
)
else:
return "vapi_error_e %s(%s)" % (
self.get_op_func_name(),
- ",\n ".join([
- 'struct vapi_ctx_s *ctx',
- '%s *msg' % self.get_c_name(),
- 'vapi_error_e (*callback)(struct vapi_ctx_s *ctx',
- ' void *callback_ctx',
- ' vapi_error_e rv',
- ' bool is_last)',
- 'void *callback_ctx',
- ])
+ ",\n ".join(
+ [
+ "struct vapi_ctx_s *ctx",
+ "%s *msg" % self.get_c_name(),
+ "vapi_error_e (*callback)(struct vapi_ctx_s *ctx",
+ " void *callback_ctx",
+ " vapi_error_e rv",
+ " bool is_last)",
+ "void *callback_ctx",
+ ]
+ ),
)
def get_op_func_def(self):
- return "\n".join([
- "%s" % self.get_op_func_decl(),
- "{",
- " if (!msg || !callback) {",
- " return VAPI_EINVAL;",
- " }",
- " if (vapi_is_nonblocking(ctx) && vapi_requests_full(ctx)) {",
- " return VAPI_EAGAIN;",
- " }",
- " vapi_error_e rv;",
- " if (VAPI_OK != (rv = vapi_producer_lock (ctx))) {",
- " return rv;",
- " }",
- " u32 req_context = vapi_gen_req_context(ctx);",
- " msg->header.context = req_context;",
- " %s(msg);" % self.get_swap_to_be_func_name(),
- (" if (VAPI_OK == (rv = vapi_send_with_control_ping "
- "(ctx, msg, req_context))) {"
- if self.reply_is_stream else
- " if (VAPI_OK == (rv = vapi_send (ctx, msg))) {"
- ),
- (" vapi_store_request(ctx, req_context, %s, "
- "(vapi_cb_t)callback, callback_ctx);" %
- ("true" if self.reply_is_stream else "false")),
- " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
- " abort (); /* this really shouldn't happen */",
- " }",
- " if (vapi_is_nonblocking(ctx)) {",
- " rv = VAPI_OK;",
- " } else {",
- " rv = vapi_dispatch(ctx);",
- " }",
- " } else {",
- " %s(msg);" % self.get_swap_to_host_func_name(),
- " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
- " abort (); /* this really shouldn't happen */",
- " }",
- " }",
- " return rv;",
- "}",
- "",
- ])
+ return "\n".join(
+ [
+ "%s" % self.get_op_func_decl(),
+ "{",
+ " if (!msg || !callback) {",
+ " return VAPI_EINVAL;",
+ " }",
+ " if (vapi_is_nonblocking(ctx) && vapi_requests_full(ctx)) {",
+ " return VAPI_EAGAIN;",
+ " }",
+ " vapi_error_e rv;",
+ " if (VAPI_OK != (rv = vapi_producer_lock (ctx))) {",
+ " return rv;",
+ " }",
+ " u32 req_context = vapi_gen_req_context(ctx);",
+ " msg->header.context = req_context;",
+ " %s(msg);" % self.get_swap_to_be_func_name(),
+ (
+ " if (VAPI_OK == (rv = vapi_send_with_control_ping "
+ "(ctx, msg, req_context))) {"
+ if self.reply_is_stream
+ else " if (VAPI_OK == (rv = vapi_send (ctx, msg))) {"
+ ),
+ (
+ " vapi_store_request(ctx, req_context, %s, "
+ "(vapi_cb_t)callback, callback_ctx);"
+ % ("true" if self.reply_is_stream else "false")
+ ),
+ " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
+ " abort (); /* this really shouldn't happen */",
+ " }",
+ " if (vapi_is_nonblocking(ctx)) {",
+ " rv = VAPI_OK;",
+ " } else {",
+ " rv = vapi_dispatch(ctx);",
+ " }",
+ " } else {",
+ " %s(msg);" % self.get_swap_to_host_func_name(),
+ " if (VAPI_OK != vapi_producer_unlock (ctx)) {",
+ " abort (); /* this really shouldn't happen */",
+ " }",
+ " }",
+ " return rv;",
+ "}",
+ "",
+ ]
+ )
def get_event_cb_func_decl(self):
if not self.is_reply and not self.is_event:
- raise Exception(
- "Cannot register event callback for non-reply message")
+ raise Exception("Cannot register event callback for non-reply message")
if self.has_payload():
- return "\n".join([
- "void vapi_set_%s_event_cb (" %
- self.get_c_name(),
- " struct vapi_ctx_s *ctx, ",
- (" vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
- "void *callback_ctx, %s *payload)," %
- self.get_payload_struct_name()),
- " void *callback_ctx)",
- ])
+ return "\n".join(
+ [
+ "void vapi_set_%s_event_cb (" % self.get_c_name(),
+ " struct vapi_ctx_s *ctx, ",
+ (
+ " vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
+ "void *callback_ctx, %s *payload),"
+ % self.get_payload_struct_name()
+ ),
+ " void *callback_ctx)",
+ ]
+ )
else:
- return "\n".join([
- "void vapi_set_%s_event_cb (" %
- self.get_c_name(),
- " struct vapi_ctx_s *ctx, ",
- " vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
- "void *callback_ctx),",
- " void *callback_ctx)",
- ])
+ return "\n".join(
+ [
+ "void vapi_set_%s_event_cb (" % self.get_c_name(),
+ " struct vapi_ctx_s *ctx, ",
+ " vapi_error_e (*callback)(struct vapi_ctx_s *ctx, "
+ "void *callback_ctx),",
+ " void *callback_ctx)",
+ ]
+ )
def get_event_cb_func_def(self):
if not self.is_reply and not self.is_event:
- raise Exception(
- "Cannot register event callback for non-reply function")
- return "\n".join([
- "%s" % self.get_event_cb_func_decl(),
- "{",
- (" vapi_set_event_cb(ctx, %s, (vapi_event_cb)callback, "
- "callback_ctx);" %
- self.get_msg_id_name()),
- "}"])
+ raise Exception("Cannot register event callback for non-reply function")
+ return "\n".join(
+ [
+ "%s" % self.get_event_cb_func_decl(),
+ "{",
+ (
+ " vapi_set_event_cb(ctx, %s, (vapi_event_cb)callback, "
+ "callback_ctx);" % self.get_msg_id_name()
+ ),
+ "}",
+ ]
+ )
def get_c_metadata_struct_name(self):
return "__vapi_metadata_%s" % self.name
@@ -614,38 +746,41 @@ class CMessage (Message):
def get_c_constructor(self):
has_context = False
if self.header is not None:
- has_context = self.header.has_field('context')
- return '\n'.join([
- 'static void __attribute__((constructor)) __vapi_constructor_%s()'
- % self.name,
- '{',
- ' static const char name[] = "%s";' % self.name,
- ' static const char name_with_crc[] = "%s_%s";'
- % (self.name, self.crc[2:]),
- ' static vapi_message_desc_t %s = {' %
- self.get_c_metadata_struct_name(),
- ' name,',
- ' sizeof(name) - 1,',
- ' name_with_crc,',
- ' sizeof(name_with_crc) - 1,',
- ' true,' if has_context else ' false,',
- ' offsetof(%s, context),' % self.header.get_c_name()
- if has_context else ' 0,',
- (' offsetof(%s, payload),' % self.get_c_name())
- if self.has_payload() else ' VAPI_INVALID_MSG_ID,',
- ' (verify_msg_size_fn_t)%s,' %
- self.get_verify_msg_size_func_name(),
- ' (generic_swap_fn_t)%s,' % self.get_swap_to_be_func_name(),
- ' (generic_swap_fn_t)%s,' % self.get_swap_to_host_func_name(),
- ' VAPI_INVALID_MSG_ID,',
- ' };',
- '',
- ' %s = vapi_register_msg(&%s);' %
- (self.get_msg_id_name(), self.get_c_metadata_struct_name()),
- ' VAPI_DBG("Assigned msg id %%d to %s", %s);' %
- (self.name, self.get_msg_id_name()),
- '}',
- ])
+ has_context = self.header.has_field("context")
+ return "\n".join(
+ [
+ "static void __attribute__((constructor)) __vapi_constructor_%s()"
+ % self.name,
+ "{",
+ ' static const char name[] = "%s";' % self.name,
+ ' static const char name_with_crc[] = "%s_%s";'
+ % (self.name, self.crc[2:]),
+ " static vapi_message_desc_t %s = {"
+ % self.get_c_metadata_struct_name(),
+ " name,",
+ " sizeof(name) - 1,",
+ " name_with_crc,",
+ " sizeof(name_with_crc) - 1,",
+ " true," if has_context else " false,",
+ " offsetof(%s, context)," % self.header.get_c_name()
+ if has_context
+ else " 0,",
+ (" offsetof(%s, payload)," % self.get_c_name())
+ if self.has_payload()
+ else " VAPI_INVALID_MSG_ID,",
+ " (verify_msg_size_fn_t)%s," % self.get_verify_msg_size_func_name(),
+ " (generic_swap_fn_t)%s," % self.get_swap_to_be_func_name(),
+ " (generic_swap_fn_t)%s," % self.get_swap_to_host_func_name(),
+ " VAPI_INVALID_MSG_ID,",
+ " };",
+ "",
+ " %s = vapi_register_msg(&%s);"
+ % (self.get_msg_id_name(), self.get_c_metadata_struct_name()),
+ ' VAPI_DBG("Assigned msg id %%d to %s", %s);'
+ % (self.name, self.get_msg_id_name()),
+ "}",
+ ]
+ )
def emit_definition(parser, json_file, emitted, o):
@@ -659,11 +794,13 @@ def emit_definition(parser, json_file, emitted, o):
if hasattr(o, "reply"):
emit_definition(parser, json_file, emitted, o.reply)
if hasattr(o, "get_c_def"):
- if (o not in parser.enums_by_json[json_file] and
- o not in parser.types_by_json[json_file] and
- o not in parser.unions_by_json[json_file] and
- o.name not in parser.messages_by_json[json_file] and
- o not in parser.aliases_by_json[json_file]):
+ if (
+ o not in parser.enums_by_json[json_file]
+ and o not in parser.types_by_json[json_file]
+ and o not in parser.unions_by_json[json_file]
+ and o.name not in parser.messages_by_json[json_file]
+ and o not in parser.aliases_by_json[json_file]
+ ):
return
guard = "defined_%s" % o.get_c_name()
print("#ifndef %s" % guard)
@@ -673,11 +810,9 @@ def emit_definition(parser, json_file, emitted, o):
function_attrs = "static inline "
if o.name in parser.messages_by_json[json_file]:
if o.has_payload():
- print("%s%s" % (function_attrs,
- o.get_swap_payload_to_be_func_def()))
+ print("%s%s" % (function_attrs, o.get_swap_payload_to_be_func_def()))
print("")
- print("%s%s" % (function_attrs,
- o.get_swap_payload_to_host_func_def()))
+ print("%s%s" % (function_attrs, o.get_swap_payload_to_host_func_def()))
print("")
print("%s%s" % (function_attrs, o.get_swap_to_be_func_def()))
print("")
@@ -711,8 +846,12 @@ def gen_json_unified_header(parser, logger, j, io, name):
orig_stdout = sys.stdout
sys.stdout = io
include_guard = "__included_%s" % (
- j.replace(".", "_").replace("/", "_").replace("-", "_").replace(
- "+", "_").replace("@", "_"))
+ j.replace(".", "_")
+ .replace("/", "_")
+ .replace("-", "_")
+ .replace("+", "_")
+ .replace("@", "_")
+ )
print("#ifndef %s" % include_guard)
print("#define %s" % include_guard)
print("")
@@ -724,12 +863,14 @@ def gen_json_unified_header(parser, logger, j, io, name):
print("#include <vapi/vapi_dbg.h>")
print("")
print("#ifdef __cplusplus")
- print("extern \"C\" {")
+ print('extern "C" {')
print("#endif")
if name == "memclnt.api.vapi.h":
print("")
- print("static inline vapi_error_e vapi_send_with_control_ping "
- "(vapi_ctx_t ctx, void * msg, u32 context);")
+ print(
+ "static inline vapi_error_e vapi_send_with_control_ping "
+ "(vapi_ctx_t ctx, void * msg, u32 context);"
+ )
elif name == "vlib.api.vapi.h":
print("#include <vapi/memclnt.api.vapi.h>")
else:
@@ -738,12 +879,18 @@ def gen_json_unified_header(parser, logger, j, io, name):
for m in parser.messages_by_json[j].values():
print("extern vapi_msg_id_t %s;" % m.get_msg_id_name())
print("")
- print("#define DEFINE_VAPI_MSG_IDS_%s\\" %
- f.replace(".", "_").replace("/", "_").replace("-", "_").upper())
- print("\\\n".join([
- " vapi_msg_id_t %s;" % m.get_msg_id_name()
- for m in parser.messages_by_json[j].values()
- ]))
+ print(
+ "#define DEFINE_VAPI_MSG_IDS_%s\\"
+ % f.replace(".", "_").replace("/", "_").replace("-", "_").upper()
+ )
+ print(
+ "\\\n".join(
+ [
+ " vapi_msg_id_t %s;" % m.get_msg_id_name()
+ for m in parser.messages_by_json[j].values()
+ ]
+ )
+ )
print("")
print("")
emitted = []
@@ -802,12 +949,11 @@ def gen_c_unified_headers(parser, logger, prefix, remove_path):
d, f = os.path.split(j)
else:
f = j
- with open('%s%s' % (prefix, json_to_c_header_name(f)), "w") as io:
- gen_json_unified_header(
- parser, logger, j, io, json_to_c_header_name(f))
+ with open("%s%s" % (prefix, json_to_c_header_name(f)), "w") as io:
+ gen_json_unified_header(parser, logger, j, io, json_to_c_header_name(f))
-if __name__ == '__main__':
+if __name__ == "__main__":
try:
verbose = int(os.getenv("V", 0))
except:
@@ -825,23 +971,30 @@ if __name__ == '__main__':
logger.setLevel(log_level)
argparser = argparse.ArgumentParser(description="VPP C API generator")
- argparser.add_argument('files', metavar='api-file', action='append',
- type=str, help='json api file'
- '(may be specified multiple times)')
- argparser.add_argument('--prefix', action='store', default=None,
- help='path prefix')
- argparser.add_argument('--remove-path', action='store_true',
- help='remove path from filename')
+ argparser.add_argument(
+ "files",
+ metavar="api-file",
+ action="append",
+ type=str,
+ help="json api file" "(may be specified multiple times)",
+ )
+ argparser.add_argument("--prefix", action="store", default=None, help="path prefix")
+ argparser.add_argument(
+ "--remove-path", action="store_true", help="remove path from filename"
+ )
args = argparser.parse_args()
- jsonparser = JsonParser(logger, args.files,
- simple_type_class=CSimpleType,
- enum_class=CEnum,
- union_class=CUnion,
- struct_type_class=CStructType,
- field_class=CField,
- message_class=CMessage,
- alias_class=CAlias)
+ jsonparser = JsonParser(
+ logger,
+ args.files,
+ simple_type_class=CSimpleType,
+ enum_class=CEnum,
+ union_class=CUnion,
+ struct_type_class=CStructType,
+ field_class=CField,
+ message_class=CMessage,
+ alias_class=CAlias,
+ )
# not using the model of having separate generated header and code files
# with generated symbols present in shared library (per discussion with
diff --git a/src/vpp-api/vapi/vapi_cpp_gen.py b/src/vpp-api/vapi/vapi_cpp_gen.py
index 7bc2e7fecf0..33744a3d58c 100755
--- a/src/vpp-api/vapi/vapi_cpp_gen.py
+++ b/src/vpp-api/vapi/vapi_cpp_gen.py
@@ -4,8 +4,16 @@ import argparse
import os
import sys
import logging
-from vapi_c_gen import CField, CEnum, CStruct, CSimpleType, CStructType,\
- CMessage, json_to_c_header_name, CAlias
+from vapi_c_gen import (
+ CField,
+ CEnum,
+ CStruct,
+ CSimpleType,
+ CStructType,
+ CMessage,
+ json_to_c_header_name,
+ CAlias,
+)
from vapi_json_parser import JsonParser
@@ -25,53 +33,64 @@ class CppAlias(CAlias):
pass
-class CppSimpleType (CSimpleType):
+class CppSimpleType(CSimpleType):
pass
-class CppStructType (CStructType, CppStruct):
+class CppStructType(CStructType, CppStruct):
pass
-class CppMessage (CMessage):
+class CppMessage(CMessage):
def get_swap_to_be_template_instantiation(self):
- return "\n".join([
- "template <> inline void vapi_swap_to_be<%s>(%s *msg)" %
- (self.get_c_name(), self.get_c_name()),
- "{",
- " %s(msg);" % self.get_swap_to_be_func_name(),
- "}",
- ])
+ return "\n".join(
+ [
+ "template <> inline void vapi_swap_to_be<%s>(%s *msg)"
+ % (self.get_c_name(), self.get_c_name()),
+ "{",
+ " %s(msg);" % self.get_swap_to_be_func_name(),
+ "}",
+ ]
+ )
def get_swap_to_host_template_instantiation(self):
- return "\n".join([
- "template <> inline void vapi_swap_to_host<%s>(%s *msg)" %
- (self.get_c_name(), self.get_c_name()),
- "{",
- " %s(msg);" % self.get_swap_to_host_func_name(),
- "}",
- ])
+ return "\n".join(
+ [
+ "template <> inline void vapi_swap_to_host<%s>(%s *msg)"
+ % (self.get_c_name(), self.get_c_name()),
+ "{",
+ " %s(msg);" % self.get_swap_to_host_func_name(),
+ "}",
+ ]
+ )
def get_alloc_template_instantiation(self):
- return "\n".join([
- "template <> inline %s* vapi_alloc<%s%s>"
- "(Connection &con%s)" %
- (self.get_c_name(), self.get_c_name(),
- ", size_t" * len(self.get_alloc_vla_param_names()),
- "".join([", size_t %s" % n for n in
- self.get_alloc_vla_param_names()])
- ),
- "{",
- " %s* result = %s(con.vapi_ctx%s);" %
- (self.get_c_name(), self.get_alloc_func_name(),
- "".join([", %s" % n
- for n in self.get_alloc_vla_param_names()])),
- "#if VAPI_CPP_DEBUG_LEAKS",
- " con.on_shm_data_alloc(result);",
- "#endif",
- " return result;",
- "}",
- ])
+ return "\n".join(
+ [
+ "template <> inline %s* vapi_alloc<%s%s>"
+ "(Connection &con%s)"
+ % (
+ self.get_c_name(),
+ self.get_c_name(),
+ ", size_t" * len(self.get_alloc_vla_param_names()),
+ "".join(
+ [", size_t %s" % n for n in self.get_alloc_vla_param_names()]
+ ),
+ ),
+ "{",
+ " %s* result = %s(con.vapi_ctx%s);"
+ % (
+ self.get_c_name(),
+ self.get_alloc_func_name(),
+ "".join([", %s" % n for n in self.get_alloc_vla_param_names()]),
+ ),
+ "#if VAPI_CPP_DEBUG_LEAKS",
+ " con.on_shm_data_alloc(result);",
+ "#endif",
+ " return result;",
+ "}",
+ ]
+ )
def get_cpp_name(self):
return "%s%s" % (self.name[0].upper(), self.name[1:])
@@ -86,51 +105,60 @@ class CppMessage (CMessage):
template,
self.get_c_name(),
self.reply.get_c_name(),
- "".join([", size_t"] * len(self.get_alloc_vla_param_names()))
+ "".join([", size_t"] * len(self.get_alloc_vla_param_names())),
)
def get_req_template_instantiation(self):
return "template class %s;" % self.get_req_template_name()
def get_type_alias(self):
- return "using %s = %s;" % (
- self.get_cpp_name(), self.get_req_template_name())
+ return "using %s = %s;" % (self.get_cpp_name(), self.get_req_template_name())
def get_reply_template_name(self):
return "Msg<%s>" % (self.get_c_name())
def get_reply_type_alias(self):
- return "using %s = %s;" % (
- self.get_cpp_name(), self.get_reply_template_name())
+ return "using %s = %s;" % (self.get_cpp_name(), self.get_reply_template_name())
def get_msg_class_instantiation(self):
return "template class Msg<%s>;" % self.get_c_name()
def get_get_msg_id_t_instantiation(self):
- return "\n".join([
- ("template <> inline vapi_msg_id_t vapi_get_msg_id_t<%s>()"
- % self.get_c_name()),
- "{",
- " return ::%s; " % self.get_msg_id_name(),
- "}",
- "",
- ("template <> inline vapi_msg_id_t "
- "vapi_get_msg_id_t<Msg<%s>>()" % self.get_c_name()),
- "{",
- " return ::%s; " % self.get_msg_id_name(),
- "}",
- ])
+ return "\n".join(
+ [
+ (
+ "template <> inline vapi_msg_id_t vapi_get_msg_id_t<%s>()"
+ % self.get_c_name()
+ ),
+ "{",
+ " return ::%s; " % self.get_msg_id_name(),
+ "}",
+ "",
+ (
+ "template <> inline vapi_msg_id_t "
+ "vapi_get_msg_id_t<Msg<%s>>()" % self.get_c_name()
+ ),
+ "{",
+ " return ::%s; " % self.get_msg_id_name(),
+ "}",
+ ]
+ )
def get_cpp_constructor(self):
- return '\n'.join([
- ('static void __attribute__((constructor)) '
- '__vapi_cpp_constructor_%s()'
- % self.name),
- '{',
- (' vapi::vapi_msg_set_msg_id<%s>(%s);' % (
- self.get_c_name(), self.get_msg_id_name())),
- '}',
- ])
+ return "\n".join(
+ [
+ (
+ "static void __attribute__((constructor)) "
+ "__vapi_cpp_constructor_%s()" % self.name
+ ),
+ "{",
+ (
+ " vapi::vapi_msg_set_msg_id<%s>(%s);"
+ % (self.get_c_name(), self.get_msg_id_name())
+ ),
+ "}",
+ ]
+ )
def gen_json_header(parser, logger, j, io, gen_h_prefix, add_debug_comments):
@@ -139,8 +167,8 @@ def gen_json_header(parser, logger, j, io, gen_h_prefix, add_debug_comments):
sys.stdout = io
d, f = os.path.split(j)
include_guard = "__included_hpp_%s" % (
- f.replace(".", "_").replace("/", "_").replace("-", "_").replace(
- "@", "_"))
+ f.replace(".", "_").replace("/", "_").replace("-", "_").replace("@", "_")
+ )
print("#ifndef %s" % include_guard)
print("#define %s" % include_guard)
print("")
@@ -202,8 +230,9 @@ def json_to_cpp_header_name(json_name):
raise Exception("Unexpected json name `%s'!" % json_name)
-def gen_cpp_headers(parser, logger, prefix, gen_h_prefix, remove_path,
- add_debug_comments=False):
+def gen_cpp_headers(
+ parser, logger, prefix, gen_h_prefix, remove_path, add_debug_comments=False
+):
if prefix == "" or prefix is None:
prefix = ""
else:
@@ -217,12 +246,11 @@ def gen_cpp_headers(parser, logger, prefix, gen_h_prefix, remove_path,
d, f = os.path.split(j)
else:
f = j
- with open('%s%s' % (prefix, json_to_cpp_header_name(f)), "w") as io:
- gen_json_header(parser, logger, j, io,
- gen_h_prefix, add_debug_comments)
+ with open("%s%s" % (prefix, json_to_cpp_header_name(f)), "w") as io:
+ gen_json_header(parser, logger, j, io, gen_h_prefix, add_debug_comments)
-if __name__ == '__main__':
+if __name__ == "__main__":
try:
verbose = int(os.getenv("V", 0))
except:
@@ -240,27 +268,36 @@ if __name__ == '__main__':
logger.setLevel(log_level)
argparser = argparse.ArgumentParser(description="VPP C++ API generator")
- argparser.add_argument('files', metavar='api-file', action='append',
- type=str, help='json api file'
- '(may be specified multiple times)')
- argparser.add_argument('--prefix', action='store', default=None,
- help='path prefix')
- argparser.add_argument('--gen-h-prefix', action='store', default=None,
- help='generated C header prefix')
- argparser.add_argument('--remove-path', action='store_true',
- help='remove path from filename')
+ argparser.add_argument(
+ "files",
+ metavar="api-file",
+ action="append",
+ type=str,
+ help="json api file" "(may be specified multiple times)",
+ )
+ argparser.add_argument("--prefix", action="store", default=None, help="path prefix")
+ argparser.add_argument(
+ "--gen-h-prefix", action="store", default=None, help="generated C header prefix"
+ )
+ argparser.add_argument(
+ "--remove-path", action="store_true", help="remove path from filename"
+ )
args = argparser.parse_args()
- jsonparser = JsonParser(logger, args.files,
- simple_type_class=CppSimpleType,
- struct_type_class=CppStructType,
- field_class=CppField,
- enum_class=CppEnum,
- message_class=CppMessage,
- alias_class=CppAlias)
-
- gen_cpp_headers(jsonparser, logger, args.prefix, args.gen_h_prefix,
- args.remove_path)
+ jsonparser = JsonParser(
+ logger,
+ args.files,
+ simple_type_class=CppSimpleType,
+ struct_type_class=CppStructType,
+ field_class=CppField,
+ enum_class=CppEnum,
+ message_class=CppMessage,
+ alias_class=CppAlias,
+ )
+
+ gen_cpp_headers(
+ jsonparser, logger, args.prefix, args.gen_h_prefix, args.remove_path
+ )
for e in jsonparser.exceptions:
logger.warning(e)
diff --git a/src/vpp-api/vapi/vapi_json_parser.py b/src/vpp-api/vapi/vapi_json_parser.py
index 1383d456bf1..a323f15e7b6 100644
--- a/src/vpp-api/vapi/vapi_json_parser.py
+++ b/src/vpp-api/vapi/vapi_json_parser.py
@@ -3,7 +3,7 @@
import json
-class ParseError (Exception):
+class ParseError(Exception):
pass
@@ -13,14 +13,12 @@ magic_suffix = "_t"
def remove_magic(what):
if what.startswith(magic_prefix) and what.endswith(magic_suffix):
- return what[len(magic_prefix): - len(magic_suffix)]
+ return what[len(magic_prefix) : -len(magic_suffix)]
return what
class Field(object):
-
- def __init__(self, field_name, field_type, array_len=None,
- nelem_field=None):
+ def __init__(self, field_name, field_type, array_len=None, nelem_field=None):
self.name = field_name
self.type = field_type
self.len = array_len
@@ -30,17 +28,23 @@ class Field(object):
if self.len is None:
return "Field(name: %s, type: %s)" % (self.name, self.type)
elif type(self.len) == dict:
- return "Field(name: %s, type: %s, length: %s)" % (self.name,
- self.type,
- self.len)
+ return "Field(name: %s, type: %s, length: %s)" % (
+ self.name,
+ self.type,
+ self.len,
+ )
elif self.len > 0:
- return "Field(name: %s, type: %s, length: %s)" % (self.name,
- self.type,
- self.len)
+ return "Field(name: %s, type: %s, length: %s)" % (
+ self.name,
+ self.type,
+ self.len,
+ )
else:
- return (
- "Field(name: %s, type: %s, variable length stored in: %s)" %
- (self.name, self.type, self.nelem_field))
+ return "Field(name: %s, type: %s, variable length stored in: %s)" % (
+ self.name,
+ self.type,
+ self.nelem_field,
+ )
def is_vla(self):
return self.nelem_field is not None
@@ -61,32 +65,38 @@ class Type(object):
return self.name
-class SimpleType (Type):
-
+class SimpleType(Type):
def has_vla(self):
return False
def get_msg_header_defs(struct_type_class, field_class, json_parser, logger):
return [
- struct_type_class(['msg_header1_t',
- ['u16', '_vl_msg_id'],
- ['u32', 'context'],
- ],
- json_parser, field_class, logger
- ),
- struct_type_class(['msg_header2_t',
- ['u16', '_vl_msg_id'],
- ['u32', 'client_index'],
- ['u32', 'context'],
- ],
- json_parser, field_class, logger
- ),
+ struct_type_class(
+ [
+ "msg_header1_t",
+ ["u16", "_vl_msg_id"],
+ ["u32", "context"],
+ ],
+ json_parser,
+ field_class,
+ logger,
+ ),
+ struct_type_class(
+ [
+ "msg_header2_t",
+ ["u16", "_vl_msg_id"],
+ ["u32", "client_index"],
+ ["u32", "context"],
+ ],
+ json_parser,
+ field_class,
+ logger,
+ ),
]
class Struct(object):
-
def __init__(self, name, fields):
self.name = name
self.fields = fields
@@ -112,7 +122,7 @@ class Enum(SimpleType):
def __str__(self):
return "Enum(%s, [%s])" % (
self.name,
- "], [" .join(["%s => %s" % (i, j) for i, j in self.value_pairs])
+ "], [".join(["%s => %s" % (i, j) for i, j in self.value_pairs]),
)
@@ -126,7 +136,7 @@ class Union(Type):
def __str__(self):
return "Union(%s, [%s])" % (
self.name,
- "], [" .join(["%s %s" % (i, j) for i, j in self.type_pairs])
+ "], [".join(["%s %s" % (i, j) for i, j in self.type_pairs]),
)
def has_vla(self):
@@ -134,7 +144,6 @@ class Union(Type):
class Message(object):
-
def __init__(self, logger, definition, json_parser):
struct_type_class = json_parser.struct_type_class
field_class = json_parser.field_class
@@ -150,22 +159,24 @@ class Message(object):
self.is_reply = json_parser.is_reply(self.name)
self.is_event = json_parser.is_event(self.name)
fields = []
- for header in get_msg_header_defs(struct_type_class, field_class,
- json_parser, logger):
+ for header in get_msg_header_defs(
+ struct_type_class, field_class, json_parser, logger
+ ):
logger.debug("Probing header `%s'" % header.name)
if header.is_part_of_def(m[1:]):
self.header = header
logger.debug("Found header `%s'" % header.name)
- fields.append(field_class(field_name='header',
- field_type=self.header))
+ fields.append(field_class(field_name="header", field_type=self.header))
ignore = False
break
if ignore and not self.is_event and not self.is_reply:
- raise ParseError("While parsing message `%s': could not find all "
- "common header fields" % name)
+ raise ParseError(
+ "While parsing message `%s': could not find all "
+ "common header fields" % name
+ )
for field in m[1:]:
- if isinstance(field, dict) and 'crc' in field:
- self.crc = field['crc']
+ if isinstance(field, dict) and "crc" in field:
+ self.crc = field["crc"]
logger.debug("Found CRC `%s'" % self.crc)
continue
else:
@@ -175,25 +186,22 @@ class Message(object):
if any(type(n) is dict for n in field):
l -= 1
if l == 2:
- if self.header is not None and\
- self.header.has_field(field[1]):
+ if self.header is not None and self.header.has_field(field[1]):
continue
- p = field_class(field_name=field[1],
- field_type=field_type)
+ p = field_class(field_name=field[1], field_type=field_type)
elif l == 3:
- if field[2] == 0 and field[0] != 'string':
+ if field[2] == 0 and field[0] != "string":
raise ParseError(
"While parsing message `%s': variable length "
"array `%s' doesn't have reference to member "
- "containing the actual length" % (
- name, field[1]))
- if field[0] == 'string' and field[2] > 0:
- field_type = json_parser.lookup_type_like_id('u8')
+ "containing the actual length" % (name, field[1])
+ )
+ if field[0] == "string" and field[2] > 0:
+ field_type = json_parser.lookup_type_like_id("u8")
p = field_class(
- field_name=field[1],
- field_type=field_type,
- array_len=field[2])
+ field_name=field[1], field_type=field_type, array_len=field[2]
+ )
elif l == 4:
nelem_field = None
for f in fields:
@@ -203,17 +211,19 @@ class Message(object):
raise ParseError(
"While parsing message `%s': couldn't find "
"variable length array `%s' member containing "
- "the actual length `%s'" % (
- name, field[1], field[3]))
+ "the actual length `%s'" % (name, field[1], field[3])
+ )
p = field_class(
field_name=field[1],
field_type=field_type,
array_len=field[2],
- nelem_field=nelem_field)
+ nelem_field=nelem_field,
+ )
else:
- raise Exception("Don't know how to parse message "
- "definition for message `%s': `%s'" %
- (m, m[1:]))
+ raise Exception(
+ "Don't know how to parse message "
+ "definition for message `%s': `%s'" % (m, m[1:])
+ )
logger.debug("Parsed field `%s'" % p)
fields.append(p)
self.fields = fields
@@ -221,35 +231,36 @@ class Message(object):
logger.debug("Parsed message: %s" % self)
def __str__(self):
- return "Message(%s, [%s], {crc: %s}" % \
- (self.name,
- "], [".join([str(f) for f in self.fields]),
- self.crc)
-
+ return "Message(%s, [%s], {crc: %s}" % (
+ self.name,
+ "], [".join([str(f) for f in self.fields]),
+ self.crc,
+ )
-class StructType (Type, Struct):
+class StructType(Type, Struct):
def __init__(self, definition, json_parser, field_class, logger):
t = definition
logger.debug("Parsing struct definition `%s'" % t)
name = t[0]
fields = []
for field in t[1:]:
- if len(field) == 1 and 'crc' in field:
- self.crc = field['crc']
+ if len(field) == 1 and "crc" in field:
+ self.crc = field["crc"]
continue
field_type = json_parser.lookup_type_like_id(field[0])
logger.debug("Parsing type field `%s'" % field)
if len(field) == 2:
- p = field_class(field_name=field[1],
- field_type=field_type)
+ p = field_class(field_name=field[1], field_type=field_type)
elif len(field) == 3:
if field[2] == 0:
- raise ParseError("While parsing type `%s': array `%s' has "
- "variable length" % (name, field[1]))
- p = field_class(field_name=field[1],
- field_type=field_type,
- array_len=field[2])
+ raise ParseError(
+ "While parsing type `%s': array `%s' has "
+ "variable length" % (name, field[1])
+ )
+ p = field_class(
+ field_name=field[1], field_type=field_type, array_len=field[2]
+ )
elif len(field) == 4:
nelem_field = None
for f in fields:
@@ -259,23 +270,25 @@ class StructType (Type, Struct):
raise ParseError(
"While parsing message `%s': couldn't find "
"variable length array `%s' member containing "
- "the actual length `%s'" % (
- name, field[1], field[3]))
- p = field_class(field_name=field[1],
- field_type=field_type,
- array_len=field[2],
- nelem_field=nelem_field)
+ "the actual length `%s'" % (name, field[1], field[3])
+ )
+ p = field_class(
+ field_name=field[1],
+ field_type=field_type,
+ array_len=field[2],
+ nelem_field=nelem_field,
+ )
else:
raise ParseError(
"Don't know how to parse field `%s' of type definition "
- "for type `%s'" % (field, t))
+ "for type `%s'" % (field, t)
+ )
fields.append(p)
Type.__init__(self, name)
Struct.__init__(self, name, fields)
def __str__(self):
- return "StructType(%s, %s)" % (Type.__str__(self),
- Struct.__str__(self))
+ return "StructType(%s, %s)" % (Type.__str__(self), Struct.__str__(self))
def has_field(self, name):
return name in self.field_names
@@ -289,30 +302,47 @@ class StructType (Type, Struct):
if field[0] != p.type.name:
raise ParseError(
"Unexpected field type `%s' (should be `%s'), "
- "while parsing msg/def/field `%s/%s/%s'" %
- (field[0], p.type, p.name, definition, field))
+ "while parsing msg/def/field `%s/%s/%s'"
+ % (field[0], p.type, p.name, definition, field)
+ )
return True
class JsonParser(object):
- def __init__(self, logger, files, simple_type_class=SimpleType,
- enum_class=Enum, union_class=Union,
- struct_type_class=StructType, field_class=Field,
- message_class=Message, alias_class=Alias):
+ def __init__(
+ self,
+ logger,
+ files,
+ simple_type_class=SimpleType,
+ enum_class=Enum,
+ union_class=Union,
+ struct_type_class=StructType,
+ field_class=Field,
+ message_class=Message,
+ alias_class=Alias,
+ ):
self.services = {}
self.messages = {}
self.enums = {}
self.unions = {}
self.aliases = {}
self.types = {
- x: simple_type_class(x) for x in [
- 'i8', 'i16', 'i32', 'i64',
- 'u8', 'u16', 'u32', 'u64',
- 'f64', 'bool'
+ x: simple_type_class(x)
+ for x in [
+ "i8",
+ "i16",
+ "i32",
+ "i64",
+ "u8",
+ "u16",
+ "u32",
+ "u64",
+ "f64",
+ "bool",
]
}
- self.types['string'] = simple_type_class('vl_api_string_t')
+ self.types["string"] = simple_type_class("vl_api_string_t")
self.replies = set()
self.events = set()
self.simple_type_class = simple_type_class
@@ -345,15 +375,15 @@ class JsonParser(object):
self.messages_by_json[path] = {}
with open(path) as f:
j = json.load(f)
- for k in j['services']:
+ for k in j["services"]:
if k in self.services:
raise ParseError("Duplicate service `%s'" % k)
- self.services[k] = j['services'][k]
+ self.services[k] = j["services"][k]
self.replies.add(self.services[k]["reply"])
if "events" in self.services[k]:
for x in self.services[k]["events"]:
self.events.add(x)
- for e in j['enums']:
+ for e in j["enums"]:
name = e[0]
value_pairs = e[1:-1]
enumtype = self.types[e[-1]["enumtype"]]
@@ -365,14 +395,15 @@ class JsonParser(object):
progress = 0
last_progress = 0
while True:
- for u in j['unions']:
+ for u in j["unions"]:
name = u[0]
if name in self.unions:
progress = progress + 1
continue
try:
- type_pairs = [[self.lookup_type_like_id(t), n]
- for t, n in u[1:]]
+ type_pairs = [
+ [self.lookup_type_like_id(t), n] for t, n in u[1:]
+ ]
union = self.union_class(name, type_pairs, 0)
progress = progress + 1
except ParseError as e:
@@ -381,17 +412,16 @@ class JsonParser(object):
self.unions[union.name] = union
self.logger.debug("Parsed union: %s" % union)
self.unions_by_json[path].append(union)
- for t in j['types']:
+ for t in j["types"]:
if t[0] in self.types:
progress = progress + 1
continue
try:
- type_ = self.struct_type_class(t, self,
- self.field_class,
- self.logger)
+ type_ = self.struct_type_class(
+ t, self, self.field_class, self.logger
+ )
if type_.name in self.types:
- raise ParseError(
- "Duplicate type `%s'" % type_.name)
+ raise ParseError("Duplicate type `%s'" % type_.name)
progress = progress + 1
except ParseError as e:
exceptions.append(e)
@@ -399,16 +429,16 @@ class JsonParser(object):
self.types[type_.name] = type_
self.types_by_json[path].append(type_)
self.logger.debug("Parsed type: %s" % type_)
- for name, body in j['aliases'].items():
+ for name, body in j["aliases"].items():
if name in self.aliases:
progress = progress + 1
continue
- if 'length' in body:
- array_len = body['length']
+ if "length" in body:
+ array_len = body["length"]
else:
array_len = None
try:
- t = self.lookup_type_like_id(body['type'])
+ t = self.lookup_type_like_id(body["type"])
except ParseError as e:
exceptions.append(e)
continue
@@ -430,14 +460,13 @@ class JsonParser(object):
processed = []
while True:
exceptions = []
- for m in j['messages']:
+ for m in j["messages"]:
if m in processed:
continue
try:
msg = self.message_class(self.logger, m, self)
if msg.name in self.messages:
- raise ParseError(
- "Duplicate message `%s'" % msg.name)
+ raise ParseError("Duplicate message `%s'" % msg.name)
except ParseError as e:
exceptions.append(e)
continue
@@ -470,7 +499,8 @@ class JsonParser(object):
return self.aliases[mundane_name]
raise ParseError(
"Could not find type, enum or union by magic name `%s' nor by "
- "mundane name `%s'" % (name, mundane_name))
+ "mundane name `%s'" % (name, mundane_name)
+ )
def is_reply(self, message):
return message in self.replies
@@ -479,7 +509,7 @@ class JsonParser(object):
return message in self.events
def get_reply(self, message):
- return self.messages[self.services[message]['reply']]
+ return self.messages[self.services[message]["reply"]]
def finalize_parsing(self):
if len(self.messages) == 0:
@@ -493,17 +523,14 @@ class JsonParser(object):
try:
m.reply = self.get_reply(n)
if "stream" in self.services[m.name]:
- m.reply_is_stream = \
- self.services[m.name]["stream"]
+ m.reply_is_stream = self.services[m.name]["stream"]
else:
m.reply_is_stream = False
m.reply.request = m
except:
- raise ParseError(
- "Cannot find reply to message `%s'" % n)
+ raise ParseError("Cannot find reply to message `%s'" % n)
except ParseError as e:
self.exceptions.append(e)
remove.append(n)
- self.messages_by_json[jn] = {
- k: v for k, v in j.items() if k not in remove}
+ self.messages_by_json[jn] = {k: v for k, v in j.items() if k not in remove}
diff --git a/test/Makefile b/test/Makefile
index 82cef838978..b416bc3f5a3 100644
--- a/test/Makefile
+++ b/test/Makefile
@@ -73,10 +73,10 @@ V=0
endif
PYTHON_VERSION=$(shell $(PYTHON_INTERP) -c 'import sys; print(sys.version_info.major)')
-PIP_VERSION=22.0.3
+PIP_VERSION=22.0.4
# Keep in sync with requirements.txt
-PIP_TOOLS_VERSION=6.5.0
-PIP_SETUPTOOLS_VERSION=60.7.1
+PIP_TOOLS_VERSION=6.6.0
+PIP_SETUPTOOLS_VERSION=62.1.0
PYTHON_DEPENDS=requirements-$(PYTHON_VERSION).txt
SCAPY_SOURCE=$(shell find $(VENV_PATH)/lib/python* -name site-packages)
BUILD_COV_DIR=$(TEST_BR)/coverage
@@ -344,37 +344,35 @@ wipe-papi:
wipe-all: wipe wipe-papi wipe-cov
@rm -rf $(TEST_BR)
-.PHONY: checkstyle-diff
-checkstyle-diff: $(PIP_INSTALL_DONE)
- @bash -c "source $(VENV_PATH)/bin/activate &&\
- python3 -m pip install pycodestyle"
- @bash -c "source $(VENV_PATH)/bin/activate &&\
- cd $(WS_ROOT) && git diff --name-only --no-color --relative HEAD~1 ':!*.patch' | grep '.py$$' | xargs -I XXX \
- pycodestyle --show-source --ignore=W504,E126,E241,E226,E305,E704,E741,E722 -v XXX ||\
- (echo \"*********************************************************************\" &&\
- echo \"* Test framework PEP8 compliance check FAILED (checked changed files)\" &&\
- echo \"*********************************************************************\" &&\
- false)"
- @echo "*********************************************************************"
- @echo "* Test framework PEP8 compliance check passed (checked changed files)"
- @echo "*********************************************************************"
-
.PHONY: start-gdb
start-gdb: sanity
@bash -c "source $(VENV_PATH)/bin/activate && python3 -c 'from debug import start_vpp_in_gdb; start_vpp_in_gdb()' $(RUN_TESTS_ARGS)"
-.PHONY: checkstyle
-checkstyle: $(PIP_INSTALL_DONE)
+.PHONY: checkstyle-python-all
+checkstyle-python-all: $(PIP_INSTALL_DONE)
@bash -c "source $(VENV_PATH)/bin/activate &&\
- python3 -m pip install pycodestyle"
+ black -t py39 --diff $(WS_ROOT) ||\
+ (echo \"*************************************************************************\" &&\
+ echo \"* Test framework PEP8 compliance check FAILED (maybe: make fixstyle-python)\" &&\
+ echo \"*************************************************************************\" &&\
+ false)"
+ @echo "*******************************************************************"
+ @echo "* Test framework PEP8 compliance check passed"
+ @echo "*******************************************************************"
+
+.PHONY: checkstyle
+checkstyle: checkstyle-python-all
+
+.PHONY: fixstyle-python-all
+fixstyle-python-all: $(PIP_INSTALL_DONE)
@bash -c "source $(VENV_PATH)/bin/activate &&\
- pycodestyle --show-source --ignore=W504,E126,E241,E226,E305,E704,E741,E722 -v *.py ||\
- (echo \"*******************************************************************\" &&\
- echo \"* Test framework PEP8 compliance check FAILED (checked all files)\" &&\
- echo \"*******************************************************************\" &&\
- false)"
+ black -t py39 $(WS_ROOT) ||\
+ (echo \"*************************************************************************\" &&\
+ echo \"* Test framework PEP8 compliance check FAILED (maybe: make fixstyle-python)\" &&\
+ echo \"*************************************************************************\" &&\
+ false)"
@echo "*******************************************************************"
- @echo "* Test framework PEP8 compliance check passed (checked all files)"
+ @echo "* Test framework PEP8 compliance check passed"
@echo "*******************************************************************"
.PHONY: help
@@ -397,7 +395,6 @@ help:
@echo " test-wipe-all - wipe (temporary) files generated by unit tests, and coverage"
@echo " test-shell - enter shell with test environment"
@echo " test-shell-debug - enter shell with test environment (debug build)"
- @echo " test-checkstyle - check PEP8 compliance for test framework"
@echo " test-refresh-deps - refresh the Python dependencies for the tests"
@echo ""
@echo "Arguments controlling test runs:"
@@ -456,8 +453,3 @@ help:
@echo ""
@echo " test-cov - generate code coverage report for test framework"
@echo " test-wipe-cov - wipe code coverage report for test framework"
- @echo ""
- @echo "Verifying code-style:"
- @echo ""
- @echo " test-checkstyle - check PEP8 compliance"
- @echo ""
diff --git a/test/bfd.py b/test/bfd.py
index bbfa5945593..4189983b430 100644
--- a/test/bfd.py
+++ b/test/bfd.py
@@ -5,15 +5,22 @@ from socket import AF_INET, AF_INET6, inet_pton
from scapy.all import bind_layers
from scapy.layers.inet import UDP
from scapy.packet import Packet
-from scapy.fields import BitField, BitEnumField, XByteField, FlagsField,\
- ConditionalField, StrField
+from scapy.fields import (
+ BitField,
+ BitEnumField,
+ XByteField,
+ FlagsField,
+ ConditionalField,
+ StrField,
+)
from vpp_object import VppObject
from util import NumericConstant
from vpp_papi import VppEnum
class BFDDiagCode(NumericConstant):
- """ BFD Diagnostic Code """
+ """BFD Diagnostic Code"""
+
no_diagnostic = 0
control_detection_time_expired = 1
echo_function_failed = 2
@@ -38,7 +45,8 @@ class BFDDiagCode(NumericConstant):
class BFDState(NumericConstant):
- """ BFD State """
+ """BFD State"""
+
admin_down = 0
down = 1
init = 2
@@ -53,7 +61,8 @@ class BFDState(NumericConstant):
class BFDAuthType(NumericConstant):
- """ BFD Authentication Type """
+ """BFD Authentication Type"""
+
no_auth = 0
simple_pwd = 1
keyed_md5 = 2
@@ -72,34 +81,38 @@ class BFDAuthType(NumericConstant):
def bfd_is_auth_used(pkt):
- """ is packet authenticated? """
+ """is packet authenticated?"""
return "A" in pkt.sprintf("%BFD.flags%")
def bfd_is_simple_pwd_used(pkt):
- """ is simple password authentication used? """
+ """is simple password authentication used?"""
return bfd_is_auth_used(pkt) and pkt.auth_type == BFDAuthType.simple_pwd
def bfd_is_sha1_used(pkt):
- """ is sha1 authentication used? """
- return bfd_is_auth_used(pkt) and pkt.auth_type in \
- (BFDAuthType.keyed_sha1, BFDAuthType.meticulous_keyed_sha1)
+ """is sha1 authentication used?"""
+ return bfd_is_auth_used(pkt) and pkt.auth_type in (
+ BFDAuthType.keyed_sha1,
+ BFDAuthType.meticulous_keyed_sha1,
+ )
def bfd_is_md5_used(pkt):
- """ is md5 authentication used? """
- return bfd_is_auth_used(pkt) and pkt.auth_type in \
- (BFDAuthType.keyed_md5, BFDAuthType.meticulous_keyed_md5)
+ """is md5 authentication used?"""
+ return bfd_is_auth_used(pkt) and pkt.auth_type in (
+ BFDAuthType.keyed_md5,
+ BFDAuthType.meticulous_keyed_md5,
+ )
def bfd_is_md5_or_sha1_used(pkt):
- """ is md5 or sha1 used? """
+ """is md5 or sha1 used?"""
return bfd_is_md5_used(pkt) or bfd_is_sha1_used(pkt)
class BFD(Packet):
- """ BFD protocol layer for scapy """
+ """BFD protocol layer for scapy"""
udp_dport = 3784 #: BFD destination port per RFC 5881
udp_dport_echo = 3785 # : BFD destination port for ECHO per RFC 5881
@@ -114,7 +127,7 @@ class BFD(Packet):
BitField("version", 1, 3),
BitEnumField("diag", 0, 5, BFDDiagCode.desc_dict),
BitEnumField("state", 0, 2, BFDState.desc_dict),
- FlagsField("flags", 0, 6, ['M', 'D', 'A', 'C', 'F', 'P']),
+ FlagsField("flags", 0, 6, ["M", "D", "A", "C", "F", "P"]),
XByteField("detect_mult", 0),
BitField("length", bfd_pkt_len, 8),
BitField("my_discriminator", 0, 32),
@@ -123,22 +136,20 @@ class BFD(Packet):
BitField("required_min_rx_interval", 0, 32),
BitField("required_min_echo_rx_interval", 0, 32),
ConditionalField(
- BitEnumField("auth_type", 0, 8, BFDAuthType.desc_dict),
- bfd_is_auth_used),
+ BitEnumField("auth_type", 0, 8, BFDAuthType.desc_dict), bfd_is_auth_used
+ ),
ConditionalField(BitField("auth_len", 0, 8), bfd_is_auth_used),
ConditionalField(BitField("auth_key_id", 0, 8), bfd_is_auth_used),
- ConditionalField(BitField("auth_reserved", 0, 8),
- bfd_is_md5_or_sha1_used),
- ConditionalField(
- BitField("auth_seq_num", 0, 32), bfd_is_md5_or_sha1_used),
+ ConditionalField(BitField("auth_reserved", 0, 8), bfd_is_md5_or_sha1_used),
+ ConditionalField(BitField("auth_seq_num", 0, 32), bfd_is_md5_or_sha1_used),
ConditionalField(StrField("auth_key_hash", "0" * 16), bfd_is_md5_used),
- ConditionalField(
- StrField("auth_key_hash", "0" * 20), bfd_is_sha1_used),
+ ConditionalField(StrField("auth_key_hash", "0" * 20), bfd_is_sha1_used),
]
def mysummary(self):
- return self.sprintf("BFD(my_disc=%BFD.my_discriminator%,"
- "your_disc=%BFD.your_discriminator%)")
+ return self.sprintf(
+ "BFD(my_disc=%BFD.my_discriminator%, your_disc=%BFD.your_discriminator%)"
+ )
# glue the BFD packet class to scapy parser
@@ -146,7 +157,7 @@ bind_layers(UDP, BFD, dport=BFD.udp_dport)
class BFD_vpp_echo(Packet):
- """ BFD echo packet as used by VPP (non-rfc, as rfc doesn't define one) """
+ """BFD echo packet as used by VPP (non-rfc, as rfc doesn't define one)"""
udp_dport = 3785 #: BFD echo destination port per RFC 5881
name = "BFD_VPP_ECHO"
@@ -154,13 +165,14 @@ class BFD_vpp_echo(Packet):
fields_desc = [
BitField("discriminator", 0, 32),
BitField("expire_time_clocks", 0, 64),
- BitField("checksum", 0, 64)
+ BitField("checksum", 0, 64),
]
def mysummary(self):
return self.sprintf(
"BFD_VPP_ECHO(disc=%BFD_VPP_ECHO.discriminator%,"
- "expire_time_clocks=%BFD_VPP_ECHO.expire_time_clocks%)")
+ "expire_time_clocks=%BFD_VPP_ECHO.expire_time_clocks%)"
+ )
# glue the BFD echo packet class to scapy parser
@@ -168,7 +180,7 @@ bind_layers(UDP, BFD_vpp_echo, dport=BFD_vpp_echo.udp_dport)
class VppBFDAuthKey(VppObject):
- """ Represents BFD authentication key in VPP """
+ """Represents BFD authentication key in VPP"""
def __init__(self, test, conf_key_id, auth_type, key):
self._test = test
@@ -179,17 +191,17 @@ class VppBFDAuthKey(VppObject):
@property
def test(self):
- """ Test which created this key """
+ """Test which created this key"""
return self._test
@property
def auth_type(self):
- """ Authentication type for this key """
+ """Authentication type for this key"""
return self._auth_type
@property
def key(self):
- """ key data """
+ """key data"""
return self._key
@key.setter
@@ -198,17 +210,20 @@ class VppBFDAuthKey(VppObject):
@property
def conf_key_id(self):
- """ configuration key ID """
+ """configuration key ID"""
return self._conf_key_id
def add_vpp_config(self):
self.test.vapi.bfd_auth_set_key(
- conf_key_id=self._conf_key_id, auth_type=self._auth_type,
- key=self._key, key_len=len(self._key))
+ conf_key_id=self._conf_key_id,
+ auth_type=self._auth_type,
+ key=self._key,
+ key_len=len(self._key),
+ )
self._test.registry.register(self, self.test.logger)
def get_bfd_auth_keys_dump_entry(self):
- """ get the entry in the auth keys dump corresponding to this key """
+ """get the entry in the auth keys dump corresponding to this key"""
result = self.test.vapi.bfd_auth_keys_dump()
for k in result:
if k.conf_key_id == self._conf_key_id:
@@ -226,11 +241,22 @@ class VppBFDAuthKey(VppObject):
class VppBFDUDPSession(VppObject):
- """ Represents BFD UDP session in VPP """
-
- def __init__(self, test, interface, peer_addr, local_addr=None, af=AF_INET,
- desired_min_tx=300000, required_min_rx=300000, detect_mult=3,
- sha1_key=None, bfd_key_id=None, is_tunnel=False):
+ """Represents BFD UDP session in VPP"""
+
+ def __init__(
+ self,
+ test,
+ interface,
+ peer_addr,
+ local_addr=None,
+ af=AF_INET,
+ desired_min_tx=300000,
+ required_min_rx=300000,
+ detect_mult=3,
+ sha1_key=None,
+ bfd_key_id=None,
+ is_tunnel=False,
+ ):
self._test = test
self._interface = interface
self._af = af
@@ -251,22 +277,22 @@ class VppBFDUDPSession(VppObject):
@property
def test(self):
- """ Test which created this session """
+ """Test which created this session"""
return self._test
@property
def interface(self):
- """ Interface on which this session lives """
+ """Interface on which this session lives"""
return self._interface
@property
def af(self):
- """ Address family - AF_INET or AF_INET6 """
+ """Address family - AF_INET or AF_INET6"""
return self._af
@property
def local_addr(self):
- """ BFD session local address (VPP address) """
+ """BFD session local address (VPP address)"""
if self._local_addr is None:
if self.af == AF_INET:
return self._interface.local_ip4
@@ -278,28 +304,32 @@ class VppBFDUDPSession(VppObject):
@property
def peer_addr(self):
- """ BFD session peer address """
+ """BFD session peer address"""
return self._peer_addr
def get_bfd_udp_session_dump_entry(self):
- """ get the namedtuple entry from bfd udp session dump """
+ """get the namedtuple entry from bfd udp session dump"""
result = self.test.vapi.bfd_udp_session_dump()
for s in result:
self.test.logger.debug("session entry: %s" % str(s))
if s.sw_if_index == self.interface.sw_if_index:
- if self.af == AF_INET \
- and self.interface.local_ip4 == str(s.local_addr) \
- and self.interface.remote_ip4 == str(s.peer_addr):
+ if (
+ self.af == AF_INET
+ and self.interface.local_ip4 == str(s.local_addr)
+ and self.interface.remote_ip4 == str(s.peer_addr)
+ ):
return s
- if self.af == AF_INET6 \
- and self.interface.local_ip6 == str(s.local_addr) \
- and self.interface.remote_ip6 == str(s.peer_addr):
+ if (
+ self.af == AF_INET6
+ and self.interface.local_ip6 == str(s.local_addr)
+ and self.interface.remote_ip6 == str(s.peer_addr)
+ ):
return s
return None
@property
def state(self):
- """ BFD session state """
+ """BFD session state"""
session = self.get_bfd_udp_session_dump_entry()
if session is None:
raise Exception("Could not find BFD session in VPP response")
@@ -307,27 +337,27 @@ class VppBFDUDPSession(VppObject):
@property
def desired_min_tx(self):
- """ desired minimum tx interval """
+ """desired minimum tx interval"""
return self._desired_min_tx
@property
def required_min_rx(self):
- """ required minimum rx interval """
+ """required minimum rx interval"""
return self._required_min_rx
@property
def detect_mult(self):
- """ detect multiplier """
+ """detect multiplier"""
return self._detect_mult
@property
def sha1_key(self):
- """ sha1 key """
+ """sha1 key"""
return self._sha1_key
@property
def bfd_key_id(self):
- """ bfd key id in use """
+ """bfd key id in use"""
return self._bfd_key_id
@property
@@ -335,7 +365,7 @@ class VppBFDUDPSession(VppObject):
return self._is_tunnel
def activate_auth(self, key, bfd_key_id=None, delayed=False):
- """ activate authentication for this session """
+ """activate authentication for this session"""
self._bfd_key_id = bfd_key_id if bfd_key_id else randint(0, 255)
self._sha1_key = key
conf_key_id = self._sha1_key.conf_key_id
@@ -346,10 +376,11 @@ class VppBFDUDPSession(VppObject):
peer_addr=self.peer_addr,
bfd_key_id=self._bfd_key_id,
conf_key_id=conf_key_id,
- is_delayed=is_delayed)
+ is_delayed=is_delayed,
+ )
def deactivate_auth(self, delayed=False):
- """ deactivate authentication """
+ """deactivate authentication"""
self._bfd_key_id = None
self._sha1_key = None
is_delayed = 1 if delayed else 0
@@ -357,45 +388,48 @@ class VppBFDUDPSession(VppObject):
sw_if_index=self._interface.sw_if_index,
local_addr=self.local_addr,
peer_addr=self.peer_addr,
- is_delayed=is_delayed)
+ is_delayed=is_delayed,
+ )
- def modify_parameters(self,
- detect_mult=None,
- desired_min_tx=None,
- required_min_rx=None):
- """ modify session parameters """
+ def modify_parameters(
+ self, detect_mult=None, desired_min_tx=None, required_min_rx=None
+ ):
+ """modify session parameters"""
if detect_mult:
self._detect_mult = detect_mult
if desired_min_tx:
self._desired_min_tx = desired_min_tx
if required_min_rx:
self._required_min_rx = required_min_rx
- self.test.vapi.bfd_udp_mod(sw_if_index=self._interface.sw_if_index,
- desired_min_tx=self.desired_min_tx,
- required_min_rx=self.required_min_rx,
- detect_mult=self.detect_mult,
- local_addr=self.local_addr,
- peer_addr=self.peer_addr)
+ self.test.vapi.bfd_udp_mod(
+ sw_if_index=self._interface.sw_if_index,
+ desired_min_tx=self.desired_min_tx,
+ required_min_rx=self.required_min_rx,
+ detect_mult=self.detect_mult,
+ local_addr=self.local_addr,
+ peer_addr=self.peer_addr,
+ )
def add_vpp_config(self):
bfd_key_id = self._bfd_key_id if self._sha1_key else None
conf_key_id = self._sha1_key.conf_key_id if self._sha1_key else None
is_authenticated = True if self._sha1_key else False
- self.test.vapi.bfd_udp_add(sw_if_index=self._interface.sw_if_index,
- desired_min_tx=self.desired_min_tx,
- required_min_rx=self.required_min_rx,
- detect_mult=self.detect_mult,
- local_addr=self.local_addr,
- peer_addr=self.peer_addr,
- bfd_key_id=bfd_key_id,
- conf_key_id=conf_key_id,
- is_authenticated=is_authenticated)
+ self.test.vapi.bfd_udp_add(
+ sw_if_index=self._interface.sw_if_index,
+ desired_min_tx=self.desired_min_tx,
+ required_min_rx=self.required_min_rx,
+ detect_mult=self.detect_mult,
+ local_addr=self.local_addr,
+ peer_addr=self.peer_addr,
+ bfd_key_id=bfd_key_id,
+ conf_key_id=conf_key_id,
+ is_authenticated=is_authenticated,
+ )
self._test.registry.register(self, self.test.logger)
- def upd_vpp_config(self,
- detect_mult=None,
- desired_min_tx=None,
- required_min_rx=None):
+ def upd_vpp_config(
+ self, detect_mult=None, desired_min_tx=None, required_min_rx=None
+ ):
if desired_min_tx:
self._desired_min_tx = desired_min_tx
if required_min_rx:
@@ -405,15 +439,17 @@ class VppBFDUDPSession(VppObject):
bfd_key_id = self._bfd_key_id if self._sha1_key else None
conf_key_id = self._sha1_key.conf_key_id if self._sha1_key else None
is_authenticated = True if self._sha1_key else False
- self.test.vapi.bfd_udp_upd(sw_if_index=self._interface.sw_if_index,
- desired_min_tx=self.desired_min_tx,
- required_min_rx=self.required_min_rx,
- detect_mult=self.detect_mult,
- local_addr=self.local_addr,
- peer_addr=self.peer_addr,
- bfd_key_id=bfd_key_id,
- conf_key_id=conf_key_id,
- is_authenticated=is_authenticated)
+ self.test.vapi.bfd_udp_upd(
+ sw_if_index=self._interface.sw_if_index,
+ desired_min_tx=self.desired_min_tx,
+ required_min_rx=self.required_min_rx,
+ detect_mult=self.detect_mult,
+ local_addr=self.local_addr,
+ peer_addr=self.peer_addr,
+ bfd_key_id=bfd_key_id,
+ conf_key_id=conf_key_id,
+ is_authenticated=is_authenticated,
+ )
self._test.registry.register(self, self.test.logger)
def query_vpp_config(self):
@@ -421,27 +457,34 @@ class VppBFDUDPSession(VppObject):
return session is not None
def remove_vpp_config(self):
- self.test.vapi.bfd_udp_del(self._interface.sw_if_index,
- local_addr=self.local_addr,
- peer_addr=self.peer_addr)
+ self.test.vapi.bfd_udp_del(
+ self._interface.sw_if_index,
+ local_addr=self.local_addr,
+ peer_addr=self.peer_addr,
+ )
def object_id(self):
- return "bfd-udp-%s-%s-%s-%s" % (self._interface.sw_if_index,
- self.local_addr,
- self.peer_addr,
- self.af)
+ return "bfd-udp-%s-%s-%s-%s" % (
+ self._interface.sw_if_index,
+ self.local_addr,
+ self.peer_addr,
+ self.af,
+ )
def admin_up(self):
- """ set bfd session admin-up """
+ """set bfd session admin-up"""
self.test.vapi.bfd_udp_session_set_flags(
flags=VppEnum.vl_api_if_status_flags_t.IF_STATUS_API_FLAG_ADMIN_UP,
sw_if_index=self._interface.sw_if_index,
local_addr=self.local_addr,
- peer_addr=self.peer_addr)
+ peer_addr=self.peer_addr,
+ )
def admin_down(self):
- """ set bfd session admin-down """
+ """set bfd session admin-down"""
self.test.vapi.bfd_udp_session_set_flags(
- flags=0, sw_if_index=self._interface.sw_if_index,
+ flags=0,
+ sw_if_index=self._interface.sw_if_index,
local_addr=self.local_addr,
- peer_addr=self.peer_addr)
+ peer_addr=self.peer_addr,
+ )
diff --git a/test/config.py b/test/config.py
index dd3b9c1f9ea..c99d1ca66a6 100644
--- a/test/config.py
+++ b/test/config.py
@@ -12,6 +12,7 @@ def positive_int_or_default(default):
if int(v) <= 0:
raise ValueError("value must be positive")
return int(v)
+
return positive_integer
@@ -22,6 +23,7 @@ def positive_float_or_default(default):
if float(v) <= 0:
raise ValueError("value must be positive")
return float(v)
+
return positive_float
@@ -50,6 +52,7 @@ def int_choice_or_default(options, default):
if int(v) in options:
return int(v)
raise ValueError("invalid choice")
+
return choice
@@ -57,14 +60,13 @@ def worker_config(v):
if v is None or v == "":
return 0
if v.startswith("workers "):
- return(int(v.split(" ")[1]))
+ return int(v.split(" ")[1])
return int(v)
def directory(v):
if not os.path.isdir(v):
- raise ValueError(f"provided path '{v}' doesn't exist "
- "or is not a directory")
+ raise ValueError(f"provided path '{v}' doesn't exist or is not a directory")
return v
@@ -74,35 +76,51 @@ def directory_verify_or_create(v):
return v
-parser = argparse.ArgumentParser(description="VPP unit tests",
- formatter_class=argparse.RawTextHelpFormatter)
+parser = argparse.ArgumentParser(
+ description="VPP unit tests", formatter_class=argparse.RawTextHelpFormatter
+)
-parser.add_argument("--failfast", action="store_true",
- help="stop running tests on first failure")
+parser.add_argument(
+ "--failfast", action="store_true", help="stop running tests on first failure"
+)
-parser.add_argument("--test-src-dir", action="append", type=directory,
- help="directory containing test files "
- "(may be specified multiple times) "
- "(VPP_WS_DIR/test is added automatically to the set)")
+parser.add_argument(
+ "--test-src-dir",
+ action="append",
+ type=directory,
+ help="directory containing test files "
+ "(may be specified multiple times) "
+ "(VPP_WS_DIR/test is added automatically to the set)",
+)
default_verbose = 0
-parser.add_argument("--verbose", action="store", default=default_verbose,
- type=int_choice_or_default((0, 1, 2), default_verbose),
- help="verbosity setting - 0 - least verbose, "
- "2 - most verbose (default: 0)")
+parser.add_argument(
+ "--verbose",
+ action="store",
+ default=default_verbose,
+ type=int_choice_or_default((0, 1, 2), default_verbose),
+ help="verbosity setting - 0 - least verbose, 2 - most verbose (default: 0)",
+)
default_test_run_timeout = 600
-parser.add_argument("--timeout", action="store",
- type=positive_int_or_default(default_test_run_timeout),
- default=default_test_run_timeout,
- metavar="TEST_RUN_TIMEOUT",
- help="test run timeout in seconds - per test "
- f"(default: {default_test_run_timeout})")
-
-parser.add_argument("--failed-dir", action="store", type=directory,
- help="directory containing failed tests")
+parser.add_argument(
+ "--timeout",
+ action="store",
+ type=positive_int_or_default(default_test_run_timeout),
+ default=default_test_run_timeout,
+ metavar="TEST_RUN_TIMEOUT",
+ help="test run timeout in seconds - per test "
+ f"(default: {default_test_run_timeout})",
+)
+
+parser.add_argument(
+ "--failed-dir",
+ action="store",
+ type=directory,
+ help="directory containing failed tests",
+)
filter_help_string = """\
expression consists of 3 string selectors separated by '.' separators:
@@ -126,17 +144,23 @@ examples:
4. '.*.test_add_bfd' selects all test functions named test_add_bfd
from all files/classes
"""
-parser.add_argument("--filter", action="store",
- metavar="FILTER_EXPRESSION", help=filter_help_string)
+parser.add_argument(
+ "--filter", action="store", metavar="FILTER_EXPRESSION", help=filter_help_string
+)
default_retries = 0
-parser.add_argument("--retries", action="store", default=default_retries,
- type=positive_int_or_default(default_retries),
- help="retry failed tests RETRIES times")
+parser.add_argument(
+ "--retries",
+ action="store",
+ default=default_retries,
+ type=positive_int_or_default(default_retries),
+ help="retry failed tests RETRIES times",
+)
-parser.add_argument("--step", action="store_true", default=False,
- help="enable stepping through tests")
+parser.add_argument(
+ "--step", action="store_true", default=False, help="enable stepping through tests"
+)
debug_help_string = """\
attach - attach to already running vpp
@@ -145,80 +169,153 @@ gdb - print VPP PID and pause allowing attaching gdb
gdbserver - same as above, but run gdb in gdbserver
"""
-parser.add_argument("--debug", action="store",
- choices=["attach", "core", "gdb", "gdbserver"],
- help=debug_help_string)
-
-parser.add_argument("--debug-framework", action="store_true",
- help="enable internal test framework debugging")
-
-parser.add_argument("--compress-core", action="store_true",
- help="compress core files if not debugging them")
-
-parser.add_argument("--extended", action="store_true",
- help="run extended tests")
-
-parser.add_argument("--sanity", action="store_true",
- help="perform sanity vpp run before running tests")
-
-parser.add_argument("--force-foreground", action="store_true",
- help="force running in foreground - don't fork")
-
-parser.add_argument("--jobs", action="store", type=positive_int_or_auto,
- default="auto", help="maximum concurrent test jobs")
-
-parser.add_argument("--venv-dir", action="store",
- type=directory, help="path to virtual environment")
+parser.add_argument(
+ "--debug",
+ action="store",
+ choices=["attach", "core", "gdb", "gdbserver"],
+ help=debug_help_string,
+)
+
+parser.add_argument(
+ "--debug-framework",
+ action="store_true",
+ help="enable internal test framework debugging",
+)
+
+parser.add_argument(
+ "--compress-core",
+ action="store_true",
+ help="compress core files if not debugging them",
+)
+
+parser.add_argument("--extended", action="store_true", help="run extended tests")
+
+parser.add_argument(
+ "--sanity", action="store_true", help="perform sanity vpp run before running tests"
+)
+
+parser.add_argument(
+ "--force-foreground",
+ action="store_true",
+ help="force running in foreground - don't fork",
+)
+
+parser.add_argument(
+ "--jobs",
+ action="store",
+ type=positive_int_or_auto,
+ default="auto",
+ help="maximum concurrent test jobs",
+)
+
+parser.add_argument(
+ "--venv-dir", action="store", type=directory, help="path to virtual environment"
+)
default_rnd_seed = time.time()
-parser.add_argument("--rnd-seed", action="store", default=default_rnd_seed,
- type=positive_float_or_default(default_rnd_seed),
- help="random generator seed (default: current time)")
-
-parser.add_argument("--vpp-worker-count", action="store", type=worker_config,
- default=0, help="number of vpp workers")
-
-parser.add_argument("--gcov", action="store_true",
- default=False, help="running gcov tests")
-
-parser.add_argument("--cache-vpp-output", action="store_true", default=False,
- help="cache VPP stdout/stderr and log as one block "
- "after test finishes")
-
-parser.add_argument("--vpp-ws-dir", action="store", required=True,
- type=directory, help="vpp workspace directory")
-
-parser.add_argument("--vpp-tag", action="store", default="vpp_debug",
- metavar="VPP_TAG", required=True,
- help="vpp tag (e.g. vpp, vpp_debug, vpp_gcov)")
-
-parser.add_argument("--vpp", action="store", help="path to vpp binary "
- "(default: derive from VPP_WS_DIR and VPP_TAG)")
-
-parser.add_argument("--vpp-install-dir", type=directory,
- action="store", help="path to vpp install directory"
- "(default: derive from VPP_WS_DIR and VPP_TAG)")
-
-parser.add_argument("--vpp-build-dir", action="store", type=directory,
- help="vpp build directory"
- "(default: derive from VPP_WS_DIR and VPP_TAG)")
-
-parser.add_argument("--vpp-plugin-dir", action="append", type=directory,
- help="directory containing vpp plugins"
- "(default: derive from VPP_WS_DIR and VPP_TAG)")
-
-parser.add_argument("--vpp-test-plugin-dir", action="append", type=directory,
- help="directory containing vpp api test plugins"
- "(default: derive from VPP_WS_DIR and VPP_TAG)")
-
-parser.add_argument("--extern-plugin-dir", action="append", type=directory,
- default=[], help="directory containing external plugins")
-
-parser.add_argument("--coredump-size", action="store", default="unlimited",
- help="specify vpp coredump size")
-
-parser.add_argument("--max-vpp-cpus", action="store", type=int_or_auto,
- default=0, help="max cpus used by vpp")
+parser.add_argument(
+ "--rnd-seed",
+ action="store",
+ default=default_rnd_seed,
+ type=positive_float_or_default(default_rnd_seed),
+ help="random generator seed (default: current time)",
+)
+
+parser.add_argument(
+ "--vpp-worker-count",
+ action="store",
+ type=worker_config,
+ default=0,
+ help="number of vpp workers",
+)
+
+parser.add_argument(
+ "--gcov", action="store_true", default=False, help="running gcov tests"
+)
+
+parser.add_argument(
+ "--cache-vpp-output",
+ action="store_true",
+ default=False,
+ help="cache VPP stdout/stderr and log as one block after test finishes",
+)
+
+parser.add_argument(
+ "--vpp-ws-dir",
+ action="store",
+ required=True,
+ type=directory,
+ help="vpp workspace directory",
+)
+
+parser.add_argument(
+ "--vpp-tag",
+ action="store",
+ default="vpp_debug",
+ metavar="VPP_TAG",
+ required=True,
+ help="vpp tag (e.g. vpp, vpp_debug, vpp_gcov)",
+)
+
+parser.add_argument(
+ "--vpp",
+ action="store",
+ help="path to vpp binary (default: derive from VPP_WS_DIR and VPP_TAG)",
+)
+
+parser.add_argument(
+ "--vpp-install-dir",
+ type=directory,
+ action="store",
+ help="path to vpp install directory"
+ "(default: derive from VPP_WS_DIR and VPP_TAG)",
+)
+
+parser.add_argument(
+ "--vpp-build-dir",
+ action="store",
+ type=directory,
+ help="vpp build directory (default: derive from VPP_WS_DIR and VPP_TAG)",
+)
+
+parser.add_argument(
+ "--vpp-plugin-dir",
+ action="append",
+ type=directory,
+ help="directory containing vpp plugins"
+ "(default: derive from VPP_WS_DIR and VPP_TAG)",
+)
+
+parser.add_argument(
+ "--vpp-test-plugin-dir",
+ action="append",
+ type=directory,
+ help="directory containing vpp api test plugins"
+ "(default: derive from VPP_WS_DIR and VPP_TAG)",
+)
+
+parser.add_argument(
+ "--extern-plugin-dir",
+ action="append",
+ type=directory,
+ default=[],
+ help="directory containing external plugins",
+)
+
+parser.add_argument(
+ "--coredump-size",
+ action="store",
+ default="unlimited",
+ help="specify vpp coredump size",
+)
+
+parser.add_argument(
+ "--max-vpp-cpus",
+ action="store",
+ type=int_or_auto,
+ default=0,
+ help="max cpus used by vpp",
+)
variant_help_string = """\
specify which march node variant to unit test
@@ -228,26 +325,41 @@ specify which march node variant to unit test
parser.add_argument("--variant", action="store", help=variant_help_string)
-parser.add_argument("--api-fuzz", action="store", default=None,
- help="specify api fuzzing parameters")
-
-parser.add_argument("--wipe-tmp-dir", action="store_true", default=True,
- help="remove test tmp directory before running test")
-
-parser.add_argument("--tmp-dir", action="store", default="/tmp",
- type=directory_verify_or_create,
- help="directory where to store test temporary directories")
-
-parser.add_argument("--log-dir", action="store",
- type=directory_verify_or_create,
- help="directory where to store directories "
- "containing log files (default: --tmp-dir)")
+parser.add_argument(
+ "--api-fuzz", action="store", default=None, help="specify api fuzzing parameters"
+)
+
+parser.add_argument(
+ "--wipe-tmp-dir",
+ action="store_true",
+ default=True,
+ help="remove test tmp directory before running test",
+)
+
+parser.add_argument(
+ "--tmp-dir",
+ action="store",
+ default="/tmp",
+ type=directory_verify_or_create,
+ help="directory where to store test temporary directories",
+)
+
+parser.add_argument(
+ "--log-dir",
+ action="store",
+ type=directory_verify_or_create,
+ help="directory where to store directories "
+ "containing log files (default: --tmp-dir)",
+)
default_keep_pcaps = False
-parser.add_argument("--keep-pcaps", action="store_true",
- default=default_keep_pcaps,
- help="if set, keep all pcap files from a test run"
- f" (default: {default_keep_pcaps})")
+parser.add_argument(
+ "--keep-pcaps",
+ action="store_true",
+ default=default_keep_pcaps,
+ help="if set, keep all pcap files from a test run"
+ f" (default: {default_keep_pcaps})",
+)
config = parser.parse_args()
@@ -268,12 +380,13 @@ libs = ["lib", "lib64"]
if config.vpp_plugin_dir is None:
config.vpp_plugin_dir = [
- f"{config.vpp_install_dir}/vpp/{lib}/vpp_plugins" for lib in libs]
+ f"{config.vpp_install_dir}/vpp/{lib}/vpp_plugins" for lib in libs
+ ]
if config.vpp_test_plugin_dir is None:
config.vpp_test_plugin_dir = [
- f"{config.vpp_install_dir}/vpp/{lib}/vpp_api_test_plugins"
- for lib in libs]
+ f"{config.vpp_install_dir}/vpp/{lib}/vpp_api_test_plugins" for lib in libs
+ ]
test_dirs = [f"{ws}/test"]
@@ -289,7 +402,7 @@ if config.venv_dir is None:
available_cpus = psutil.Process().cpu_affinity()
num_cpus = len(available_cpus)
-if config.max_vpp_cpus == 'auto':
+if config.max_vpp_cpus == "auto":
max_vpp_cpus = num_cpus
elif config.max_vpp_cpus > 0:
max_vpp_cpus = min(config.max_vpp_cpus, num_cpus)
diff --git a/test/debug.py b/test/debug.py
index 0ab143201c8..d77fd87f3e5 100644
--- a/test/debug.py
+++ b/test/debug.py
@@ -8,7 +8,7 @@ from sanity_run_vpp import SanityTestCase
from shutil import rmtree
from config import available_cpus
-gdb_path = '/usr/bin/gdb'
+gdb_path = "/usr/bin/gdb"
def spawn_gdb(binary_path, core_path):
@@ -24,8 +24,9 @@ def spawn_gdb(binary_path, core_path):
if gdb.isalive():
raise Exception("GDB refused to die...")
else:
- sys.stderr.write("Debugger '%s' does not exist or is not "
- "an executable..\n" % gdb_path)
+ sys.stderr.write(
+ "Debugger '%s' does not exist or is not an executable..\n" % gdb_path
+ )
def start_vpp_in_gdb():
@@ -33,8 +34,7 @@ def start_vpp_in_gdb():
# but any test case class could be used ...
SanityTestCase.set_debug_flags("attach")
SanityTestCase.tempdir = SanityTestCase.get_tempdir()
- SanityTestCase.assign_cpus(
- available_cpus[:SanityTestCase.get_cpus_required()])
+ SanityTestCase.assign_cpus(available_cpus[: SanityTestCase.get_cpus_required()])
SanityTestCase.setUpConstants()
vpp_cmdline = SanityTestCase.vpp_cmdline
print("Hacking cmdline to make VPP interactive.")
@@ -54,5 +54,6 @@ def start_vpp_in_gdb():
if gdb.isalive():
raise Exception("GDB refused to die...")
else:
- sys.stderr.write("Debugger '%s' does not exist or is not "
- "an executable..\n" % gdb_path)
+ sys.stderr.write(
+ "Debugger '%s' does not exist or is not an executable..\n" % gdb_path
+ )
diff --git a/test/debug_internal.py b/test/debug_internal.py
index 2cbee27ec81..fe10db7ee7f 100644
--- a/test/debug_internal.py
+++ b/test/debug_internal.py
@@ -4,6 +4,7 @@ import vpp_papi
from vpp_papi_provider import VppPapiProvider
import objgraph
from pympler import tracker
+
tr = tracker.SummaryTracker()
"""
@@ -18,16 +19,16 @@ def on_tear_down_class(cls):
tr.print_diff()
objects = gc.get_objects()
counter = 0
- with open(cls.tempdir + '/python_objects.txt', 'w') as f:
+ with open(cls.tempdir + "/python_objects.txt", "w") as f:
interesting = [
- o for o in objects
- if isinstance(o, (VppPapiProvider, vpp_papi.VPP))]
+ o for o in objects if isinstance(o, (VppPapiProvider, vpp_papi.VPP))
+ ]
del objects
gc.collect()
for o in interesting:
- objgraph.show_backrefs([o], max_depth=5,
- filename="%s/%s.png" %
- (cls.tempdir, counter))
+ objgraph.show_backrefs(
+ [o], max_depth=5, filename="%s/%s.png" % (cls.tempdir, counter)
+ )
counter += 1
refs = gc.get_referrers(o)
pp = pprint.PrettyPrinter(indent=2)
diff --git a/test/framework.py b/test/framework.py
index 8065518ff7a..05e59b577cb 100644
--- a/test/framework.py
+++ b/test/framework.py
@@ -37,8 +37,15 @@ from vpp_papi import VppEnum
import vpp_papi
from vpp_papi.vpp_stats import VPPStats
from vpp_papi.vpp_transport_socket import VppTransportSocketIOError
-from log import RED, GREEN, YELLOW, double_line_delim, single_line_delim, \
- get_logger, colorize
+from log import (
+ RED,
+ GREEN,
+ YELLOW,
+ double_line_delim,
+ single_line_delim,
+ get_logger,
+ colorize,
+)
from vpp_object import VppObjectRegistry
from util import ppp, is_core_present
from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror
@@ -49,7 +56,7 @@ from scapy.layers.inet6 import ICMPv6EchoReply
logger = logging.getLogger(__name__)
# Set up an empty logger for the testcase that can be overridden as necessary
-null_logger = logging.getLogger('VppTestCase')
+null_logger = logging.getLogger("VppTestCase")
null_logger.addHandler(logging.NullHandler())
PASS = 0
@@ -72,10 +79,13 @@ if config.debug_framework:
class VppDiedError(Exception):
- """ exception for reporting that the subprocess has died."""
+ """exception for reporting that the subprocess has died."""
- signals_by_value = {v: k for k, v in signal.__dict__.items() if
- k.startswith('SIG') and not k.startswith('SIG_')}
+ signals_by_value = {
+ v: k
+ for k, v in signal.__dict__.items()
+ if k.startswith("SIG") and not k.startswith("SIG_")
+ }
def __init__(self, rv=None, testcase=None, method_name=None):
self.rv = rv
@@ -89,15 +99,16 @@ class VppDiedError(Exception):
pass
if testcase is None and method_name is None:
- in_msg = ''
+ in_msg = ""
else:
- in_msg = ' while running %s.%s' % (testcase, method_name)
+ in_msg = " while running %s.%s" % (testcase, method_name)
if self.rv:
- msg = "VPP subprocess died unexpectedly%s with return code: %d%s."\
- % (in_msg, self.rv, ' [%s]' %
- (self.signal_name if
- self.signal_name is not None else ''))
+ msg = "VPP subprocess died unexpectedly%s with return code: %d%s." % (
+ in_msg,
+ self.rv,
+ " [%s]" % (self.signal_name if self.signal_name is not None else ""),
+ )
else:
msg = "VPP subprocess died unexpectedly%s." % in_msg
@@ -110,6 +121,7 @@ class _PacketInfo(object):
Help process information about the next packet.
Set variables to default values.
"""
+
#: Store the index of the packet.
index = -1
#: Store the index of the source packet generator interface of the packet.
@@ -133,19 +145,23 @@ class _PacketInfo(object):
def pump_output(testclass):
- """ pump output from vpp stdout/stderr to proper queues """
+ """pump output from vpp stdout/stderr to proper queues"""
stdout_fragment = ""
stderr_fragment = ""
while not testclass.pump_thread_stop_flag.is_set():
- readable = select.select([testclass.vpp.stdout.fileno(),
- testclass.vpp.stderr.fileno(),
- testclass.pump_thread_wakeup_pipe[0]],
- [], [])[0]
+ readable = select.select(
+ [
+ testclass.vpp.stdout.fileno(),
+ testclass.vpp.stderr.fileno(),
+ testclass.pump_thread_wakeup_pipe[0],
+ ],
+ [],
+ [],
+ )[0]
if testclass.vpp.stdout.fileno() in readable:
read = os.read(testclass.vpp.stdout.fileno(), 102400)
if len(read) > 0:
- split = read.decode('ascii',
- errors='backslashreplace').splitlines(True)
+ split = read.decode("ascii", errors="backslashreplace").splitlines(True)
if len(stdout_fragment) > 0:
split[0] = "%s%s" % (stdout_fragment, split[0])
if len(split) > 0 and split[-1].endswith("\n"):
@@ -156,13 +172,11 @@ def pump_output(testclass):
testclass.vpp_stdout_deque.extend(split[:limit])
if not config.cache_vpp_output:
for line in split[:limit]:
- testclass.logger.info(
- "VPP STDOUT: %s" % line.rstrip("\n"))
+ testclass.logger.info("VPP STDOUT: %s" % line.rstrip("\n"))
if testclass.vpp.stderr.fileno() in readable:
read = os.read(testclass.vpp.stderr.fileno(), 102400)
if len(read) > 0:
- split = read.decode('ascii',
- errors='backslashreplace').splitlines(True)
+ split = read.decode("ascii", errors="backslashreplace").splitlines(True)
if len(stderr_fragment) > 0:
split[0] = "%s%s" % (stderr_fragment, split[0])
if len(split) > 0 and split[-1].endswith("\n"):
@@ -174,14 +188,13 @@ def pump_output(testclass):
testclass.vpp_stderr_deque.extend(split[:limit])
if not config.cache_vpp_output:
for line in split[:limit]:
- testclass.logger.error(
- "VPP STDERR: %s" % line.rstrip("\n"))
+ testclass.logger.error("VPP STDERR: %s" % line.rstrip("\n"))
# ignoring the dummy pipe here intentionally - the
# flag will take care of properly terminating the loop
def _is_platform_aarch64():
- return platform.machine() == 'aarch64'
+ return platform.machine() == "aarch64"
is_platform_aarch64 = _is_platform_aarch64()
@@ -191,6 +204,7 @@ class KeepAliveReporter(object):
"""
Singleton object which reports test start to parent process
"""
+
_shared_state = {}
def __init__(self):
@@ -216,7 +230,7 @@ class KeepAliveReporter(object):
return
if isclass(test):
- desc = '%s (%s)' % (desc, unittest.util.strclass(test))
+ desc = "%s (%s)" % (desc, unittest.util.strclass(test))
else:
desc = test.id()
@@ -240,6 +254,7 @@ def create_tag_decorator(e):
except AttributeError:
cls.test_tags = [e]
return cls
+
return decorator
@@ -250,7 +265,7 @@ tag_fixme_asan = create_tag_decorator(TestCaseTag.FIXME_ASAN)
class DummyVpp:
returncode = None
- pid = 0xcafebafe
+ pid = 0xCAFEBAFE
def poll(self):
pass
@@ -300,7 +315,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
@classmethod
def has_tag(cls, tag):
- """ if the test case has a given tag - return true """
+ """if the test case has a given tag - return true"""
try:
return tag in cls.test_tags
except AttributeError:
@@ -309,15 +324,15 @@ class VppTestCase(CPUInterface, unittest.TestCase):
@classmethod
def is_tagged_run_solo(cls):
- """ if the test case class is timing-sensitive - return true """
+ """if the test case class is timing-sensitive - return true"""
return cls.has_tag(TestCaseTag.RUN_SOLO)
@classmethod
def skip_fixme_asan(cls):
- """ if @tag_fixme_asan & ASan is enabled - mark for skip """
+ """if @tag_fixme_asan & ASan is enabled - mark for skip"""
if cls.has_tag(TestCaseTag.FIXME_ASAN):
- vpp_extra_cmake_args = os.environ.get('VPP_EXTRA_CMAKE_ARGS', '')
- if 'DVPP_ENABLE_SANITIZE_ADDR=ON' in vpp_extra_cmake_args:
+ vpp_extra_cmake_args = os.environ.get("VPP_EXTRA_CMAKE_ARGS", "")
+ if "DVPP_ENABLE_SANITIZE_ADDR=ON" in vpp_extra_cmake_args:
cls = unittest.skip("Skipping @tag_fixme_asan tests")(cls)
@classmethod
@@ -364,7 +379,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
@classmethod
def setUpConstants(cls):
- """ Set-up the test case class based on environment variables """
+ """Set-up the test case class based on environment variables"""
cls.step = config.step
cls.plugin_path = ":".join(config.vpp_plugin_dir)
cls.test_plugin_path = ":".join(config.vpp_test_plugin_dir)
@@ -385,34 +400,92 @@ class VppTestCase(CPUInterface, unittest.TestCase):
api_fuzzing = config.api_fuzz
if api_fuzzing is None:
- api_fuzzing = 'off'
+ api_fuzzing = "off"
cls.vpp_cmdline = [
config.vpp,
- "unix", "{", "nodaemon", debug_cli, "full-coredump",
- coredump_size, "runtime-dir", cls.tempdir, "}",
- "api-trace", "{", "on", "}",
- "api-segment", "{", "prefix", cls.get_api_segment_prefix(), "}",
- "cpu", "{", "main-core", str(cls.cpus[0]), ]
+ "unix",
+ "{",
+ "nodaemon",
+ debug_cli,
+ "full-coredump",
+ coredump_size,
+ "runtime-dir",
+ cls.tempdir,
+ "}",
+ "api-trace",
+ "{",
+ "on",
+ "}",
+ "api-segment",
+ "{",
+ "prefix",
+ cls.get_api_segment_prefix(),
+ "}",
+ "cpu",
+ "{",
+ "main-core",
+ str(cls.cpus[0]),
+ ]
if cls.extern_plugin_path not in (None, ""):
- cls.extra_vpp_plugin_config.append(
- "add-path %s" % cls.extern_plugin_path)
+ cls.extra_vpp_plugin_config.append("add-path %s" % cls.extern_plugin_path)
if cls.get_vpp_worker_count():
- cls.vpp_cmdline.extend([
- "corelist-workers", ",".join([str(x) for x in cls.cpus[1:]])])
- cls.vpp_cmdline.extend([
- "}",
- "physmem", "{", "max-size", "32m", "}",
- "statseg", "{", "socket-name", cls.get_stats_sock_path(),
- cls.extra_vpp_statseg_config, "}",
- "socksvr", "{", "socket-name", cls.get_api_sock_path(), "}",
- "node { ", default_variant, "}",
- "api-fuzz {", api_fuzzing, "}",
- "plugins", "{", "plugin", "dpdk_plugin.so", "{", "disable", "}",
- "plugin", "rdma_plugin.so", "{", "disable", "}",
- "plugin", "lisp_unittest_plugin.so", "{", "enable", "}",
- "plugin", "unittest_plugin.so", "{", "enable", "}"
- ] + cls.extra_vpp_plugin_config + ["}", ])
+ cls.vpp_cmdline.extend(
+ ["corelist-workers", ",".join([str(x) for x in cls.cpus[1:]])]
+ )
+ cls.vpp_cmdline.extend(
+ [
+ "}",
+ "physmem",
+ "{",
+ "max-size",
+ "32m",
+ "}",
+ "statseg",
+ "{",
+ "socket-name",
+ cls.get_stats_sock_path(),
+ cls.extra_vpp_statseg_config,
+ "}",
+ "socksvr",
+ "{",
+ "socket-name",
+ cls.get_api_sock_path(),
+ "}",
+ "node { ",
+ default_variant,
+ "}",
+ "api-fuzz {",
+ api_fuzzing,
+ "}",
+ "plugins",
+ "{",
+ "plugin",
+ "dpdk_plugin.so",
+ "{",
+ "disable",
+ "}",
+ "plugin",
+ "rdma_plugin.so",
+ "{",
+ "disable",
+ "}",
+ "plugin",
+ "lisp_unittest_plugin.so",
+ "{",
+ "enable",
+ "}",
+ "plugin",
+ "unittest_plugin.so",
+ "{",
+ "enable",
+ "}",
+ ]
+ + cls.extra_vpp_plugin_config
+ + [
+ "}",
+ ]
+ )
if cls.extra_vpp_punt_config is not None:
cls.vpp_cmdline.extend(cls.extra_vpp_punt_config)
@@ -435,17 +508,23 @@ class VppTestCase(CPUInterface, unittest.TestCase):
print(single_line_delim)
print("You can debug VPP using:")
if cls.debug_gdbserver:
- print(f"sudo gdb {config.vpp} "
- f"-ex 'target remote localhost:{cls.gdbserver_port}'")
- print("Now is the time to attach gdb by running the above "
- "command, set up breakpoints etc., then resume VPP from "
- "within gdb by issuing the 'continue' command")
+ print(
+ f"sudo gdb {config.vpp} "
+ f"-ex 'target remote localhost:{cls.gdbserver_port}'"
+ )
+ print(
+ "Now is the time to attach gdb by running the above "
+ "command, set up breakpoints etc., then resume VPP from "
+ "within gdb by issuing the 'continue' command"
+ )
cls.gdbserver_port += 1
elif cls.debug_gdb:
print(f"sudo gdb {config.vpp} -ex 'attach {cls.vpp.pid}'")
- print("Now is the time to attach gdb by running the above "
- "command and set up breakpoints etc., then resume VPP from"
- " within gdb by issuing the 'continue' command")
+ print(
+ "Now is the time to attach gdb by running the above "
+ "command and set up breakpoints etc., then resume VPP from"
+ " within gdb by issuing the 'continue' command"
+ )
print(single_line_delim)
input("Press ENTER to continue running the testcase...")
@@ -459,31 +538,35 @@ class VppTestCase(CPUInterface, unittest.TestCase):
cmdline = cls.vpp_cmdline
if cls.debug_gdbserver:
- gdbserver = '/usr/bin/gdbserver'
- if not os.path.isfile(gdbserver) or\
- not os.access(gdbserver, os.X_OK):
- raise Exception("gdbserver binary '%s' does not exist or is "
- "not executable" % gdbserver)
-
- cmdline = [gdbserver, 'localhost:{port}'
- .format(port=cls.gdbserver_port)] + cls.vpp_cmdline
+ gdbserver = "/usr/bin/gdbserver"
+ if not os.path.isfile(gdbserver) or not os.access(gdbserver, os.X_OK):
+ raise Exception(
+ "gdbserver binary '%s' does not exist or is "
+ "not executable" % gdbserver
+ )
+
+ cmdline = [
+ gdbserver,
+ "localhost:{port}".format(port=cls.gdbserver_port),
+ ] + cls.vpp_cmdline
cls.logger.info("Gdbserver cmdline is %s", " ".join(cmdline))
try:
- cls.vpp = subprocess.Popen(cmdline,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
+ cls.vpp = subprocess.Popen(
+ cmdline, stdout=subprocess.PIPE, stderr=subprocess.PIPE
+ )
except subprocess.CalledProcessError as e:
- cls.logger.critical("Subprocess returned with non-0 return code: ("
- "%s)", e.returncode)
+ cls.logger.critical(
+ "Subprocess returned with non-0 return code: (%s)", e.returncode
+ )
raise
except OSError as e:
- cls.logger.critical("Subprocess returned with OS error: "
- "(%s) %s", e.errno, e.strerror)
+ cls.logger.critical(
+ "Subprocess returned with OS error: (%s) %s", e.errno, e.strerror
+ )
raise
except Exception as e:
- cls.logger.exception("Subprocess returned unexpected from "
- "%s:", cmdline)
+ cls.logger.exception("Subprocess returned unexpected from %s:", cmdline)
raise
cls.wait_for_enter()
@@ -504,11 +587,11 @@ class VppTestCase(CPUInterface, unittest.TestCase):
ok = True
break
if not ok:
- cls.logger.error("Timed out waiting for coredump to complete:"
- " %s", corefile)
+ cls.logger.error(
+ "Timed out waiting for coredump to complete: %s", corefile
+ )
else:
- cls.logger.error("Coredump complete: %s, size %d",
- corefile, curr_size)
+ cls.logger.error("Coredump complete: %s, size %d", corefile, curr_size)
@classmethod
def get_stats_sock_path(cls):
@@ -554,21 +637,24 @@ class VppTestCase(CPUInterface, unittest.TestCase):
super(VppTestCase, cls).setUpClass()
cls.logger = get_logger(cls.__name__)
random.seed(config.rnd_seed)
- if hasattr(cls, 'parallel_handler'):
+ if hasattr(cls, "parallel_handler"):
cls.logger.addHandler(cls.parallel_handler)
cls.logger.propagate = False
cls.set_debug_flags(config.debug)
cls.tempdir = cls.get_tempdir()
cls.create_file_handler()
cls.file_handler.setFormatter(
- Formatter(fmt='%(asctime)s,%(msecs)03d %(message)s',
- datefmt="%H:%M:%S"))
+ Formatter(fmt="%(asctime)s,%(msecs)03d %(message)s", datefmt="%H:%M:%S")
+ )
cls.file_handler.setLevel(DEBUG)
cls.logger.addHandler(cls.file_handler)
cls.logger.debug("--- setUpClass() for %s called ---" % cls.__name__)
os.chdir(cls.tempdir)
- cls.logger.info("Temporary dir is %s, api socket is %s",
- cls.tempdir, cls.get_api_sock_path())
+ cls.logger.info(
+ "Temporary dir is %s, api socket is %s",
+ cls.tempdir,
+ cls.get_api_sock_path(),
+ )
cls.logger.debug("Random seed is %s", config.rnd_seed)
cls.setUpConstants()
cls.reset_packet_infos()
@@ -586,9 +672,10 @@ class VppTestCase(CPUInterface, unittest.TestCase):
cls.attach_vpp()
else:
cls.run_vpp()
- cls.reporter.send_keep_alive(cls, 'setUpClass')
+ cls.reporter.send_keep_alive(cls, "setUpClass")
VppTestResult.current_test_case_info = TestCaseInfo(
- cls.logger, cls.tempdir, cls.vpp.pid, config.vpp)
+ cls.logger, cls.tempdir, cls.vpp.pid, config.vpp
+ )
cls.vpp_stdout_deque = deque()
cls.vpp_stderr_deque = deque()
if not cls.debug_attach:
@@ -599,8 +686,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
cls.pump_thread.start()
if cls.debug_gdb or cls.debug_gdbserver or cls.debug_attach:
cls.vapi_response_timeout = 0
- cls.vapi = VppPapiProvider(cls.__name__, cls,
- cls.vapi_response_timeout)
+ cls.vapi = VppPapiProvider(cls.__name__, cls, cls.vapi_response_timeout)
if cls.step:
hook = hookmodule.StepHook(cls)
else:
@@ -613,7 +699,8 @@ class VppTestCase(CPUInterface, unittest.TestCase):
cls.vpp_startup_failed = True
cls.logger.critical(
"VPP died shortly after startup, check the"
- " output to standard error for possible cause")
+ " output to standard error for possible cause"
+ )
raise
try:
cls.vapi.connect()
@@ -622,9 +709,14 @@ class VppTestCase(CPUInterface, unittest.TestCase):
cls.vapi.disconnect()
if cls.debug_gdbserver:
- print(colorize("You're running VPP inside gdbserver but "
- "VPP-API connection failed, did you forget "
- "to 'continue' VPP from within gdb?", RED))
+ print(
+ colorize(
+ "You're running VPP inside gdbserver but "
+ "VPP-API connection failed, did you forget "
+ "to 'continue' VPP from within gdb?",
+ RED,
+ )
+ )
raise e
if cls.debug_attach:
last_line = cls.vapi.cli("show thread").split("\n")[-2]
@@ -641,7 +733,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
@classmethod
def _debug_quit(cls):
- if (cls.debug_gdbserver or cls.debug_gdb):
+ if cls.debug_gdbserver or cls.debug_gdb:
try:
cls.vpp.poll()
@@ -650,8 +742,10 @@ class VppTestCase(CPUInterface, unittest.TestCase):
print(double_line_delim)
print("VPP or GDB server is still running")
print(single_line_delim)
- input("When done debugging, press ENTER to kill the "
- "process and finish running the testcase...")
+ input(
+ "When done debugging, press ENTER to kill the "
+ "process and finish running the testcase..."
+ )
except AttributeError:
pass
@@ -663,25 +757,23 @@ class VppTestCase(CPUInterface, unittest.TestCase):
cls._debug_quit()
# first signal that we want to stop the pump thread, then wake it up
- if hasattr(cls, 'pump_thread_stop_flag'):
+ if hasattr(cls, "pump_thread_stop_flag"):
cls.pump_thread_stop_flag.set()
- if hasattr(cls, 'pump_thread_wakeup_pipe'):
- os.write(cls.pump_thread_wakeup_pipe[1], b'ding dong wake up')
- if hasattr(cls, 'pump_thread'):
+ if hasattr(cls, "pump_thread_wakeup_pipe"):
+ os.write(cls.pump_thread_wakeup_pipe[1], b"ding dong wake up")
+ if hasattr(cls, "pump_thread"):
cls.logger.debug("Waiting for pump thread to stop")
cls.pump_thread.join()
- if hasattr(cls, 'vpp_stderr_reader_thread'):
+ if hasattr(cls, "vpp_stderr_reader_thread"):
cls.logger.debug("Waiting for stderr pump to stop")
cls.vpp_stderr_reader_thread.join()
- if hasattr(cls, 'vpp'):
- if hasattr(cls, 'vapi'):
+ if hasattr(cls, "vpp"):
+ if hasattr(cls, "vapi"):
cls.logger.debug(cls.vapi.vpp.get_stats())
- cls.logger.debug("Disconnecting class vapi client on %s",
- cls.__name__)
+ cls.logger.debug("Disconnecting class vapi client on %s", cls.__name__)
cls.vapi.disconnect()
- cls.logger.debug("Deleting class vapi attribute on %s",
- cls.__name__)
+ cls.logger.debug("Deleting class vapi attribute on %s", cls.__name__)
del cls.vapi
cls.vpp.poll()
if not cls.debug_attach and cls.vpp.returncode is None:
@@ -694,8 +786,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
except subprocess.TimeoutExpired:
cls.vpp.kill()
outs, errs = cls.vpp.communicate()
- cls.logger.debug("Deleting class vpp attribute on %s",
- cls.__name__)
+ cls.logger.debug("Deleting class vpp attribute on %s", cls.__name__)
if not cls.debug_attach:
cls.vpp.stdout.close()
cls.vpp.stderr.close()
@@ -708,32 +799,31 @@ class VppTestCase(CPUInterface, unittest.TestCase):
stdout_log = cls.logger.info
stderr_log = cls.logger.info
- if hasattr(cls, 'vpp_stdout_deque'):
+ if hasattr(cls, "vpp_stdout_deque"):
stdout_log(single_line_delim)
- stdout_log('VPP output to stdout while running %s:', cls.__name__)
+ stdout_log("VPP output to stdout while running %s:", cls.__name__)
stdout_log(single_line_delim)
vpp_output = "".join(cls.vpp_stdout_deque)
- with open(cls.tempdir + '/vpp_stdout.txt', 'w') as f:
+ with open(cls.tempdir + "/vpp_stdout.txt", "w") as f:
f.write(vpp_output)
- stdout_log('\n%s', vpp_output)
+ stdout_log("\n%s", vpp_output)
stdout_log(single_line_delim)
- if hasattr(cls, 'vpp_stderr_deque'):
+ if hasattr(cls, "vpp_stderr_deque"):
stderr_log(single_line_delim)
- stderr_log('VPP output to stderr while running %s:', cls.__name__)
+ stderr_log("VPP output to stderr while running %s:", cls.__name__)
stderr_log(single_line_delim)
vpp_output = "".join(cls.vpp_stderr_deque)
- with open(cls.tempdir + '/vpp_stderr.txt', 'w') as f:
+ with open(cls.tempdir + "/vpp_stderr.txt", "w") as f:
f.write(vpp_output)
- stderr_log('\n%s', vpp_output)
+ stderr_log("\n%s", vpp_output)
stderr_log(single_line_delim)
@classmethod
def tearDownClass(cls):
- """ Perform final cleanup after running all tests in this test-case """
- cls.logger.debug("--- tearDownClass() for %s called ---" %
- cls.__name__)
- cls.reporter.send_keep_alive(cls, 'tearDownClass')
+ """Perform final cleanup after running all tests in this test-case"""
+ cls.logger.debug("--- tearDownClass() for %s called ---" % cls.__name__)
+ cls.reporter.send_keep_alive(cls, "tearDownClass")
cls.quit()
cls.file_handler.close()
cls.reset_packet_infos()
@@ -741,14 +831,15 @@ class VppTestCase(CPUInterface, unittest.TestCase):
debug_internal.on_tear_down_class(cls)
def show_commands_at_teardown(self):
- """ Allow subclass specific teardown logging additions."""
+ """Allow subclass specific teardown logging additions."""
self.logger.info("--- No test specific show commands provided. ---")
def tearDown(self):
- """ Show various debug prints after each test """
- self.logger.debug("--- tearDown() for %s.%s(%s) called ---" %
- (self.__class__.__name__, self._testMethodName,
- self._testMethodDoc))
+ """Show various debug prints after each test"""
+ self.logger.debug(
+ "--- tearDown() for %s.%s(%s) called ---"
+ % (self.__class__.__name__, self._testMethodName, self._testMethodDoc)
+ )
try:
if not self.vpp_dead:
@@ -769,32 +860,35 @@ class VppTestCase(CPUInterface, unittest.TestCase):
tmp_api_trace = "/tmp/%s" % api_trace
vpp_api_trace_log = "%s/%s" % (self.tempdir, api_trace)
self.logger.info(self.vapi.ppcli("api trace save %s" % api_trace))
- self.logger.info("Moving %s to %s\n" % (tmp_api_trace,
- vpp_api_trace_log))
+ self.logger.info("Moving %s to %s\n" % (tmp_api_trace, vpp_api_trace_log))
os.rename(tmp_api_trace, vpp_api_trace_log)
except VppTransportSocketIOError:
- self.logger.debug("VppTransportSocketIOError: Vpp dead. "
- "Cannot log show commands.")
+ self.logger.debug(
+ "VppTransportSocketIOError: Vpp dead. Cannot log show commands."
+ )
self.vpp_dead = True
else:
self.registry.unregister_all(self.logger)
def setUp(self):
- """ Clear trace before running each test"""
+ """Clear trace before running each test"""
super(VppTestCase, self).setUp()
self.reporter.send_keep_alive(self)
if self.vpp_dead:
- raise VppDiedError(rv=None, testcase=self.__class__.__name__,
- method_name=self._testMethodName)
- self.sleep(.1, "during setUp")
+ raise VppDiedError(
+ rv=None,
+ testcase=self.__class__.__name__,
+ method_name=self._testMethodName,
+ )
+ self.sleep(0.1, "during setUp")
self.vpp_stdout_deque.append(
- "--- test setUp() for %s.%s(%s) starts here ---\n" %
- (self.__class__.__name__, self._testMethodName,
- self._testMethodDoc))
+ "--- test setUp() for %s.%s(%s) starts here ---\n"
+ % (self.__class__.__name__, self._testMethodName, self._testMethodDoc)
+ )
self.vpp_stderr_deque.append(
- "--- test setUp() for %s.%s(%s) starts here ---\n" %
- (self.__class__.__name__, self._testMethodName,
- self._testMethodDoc))
+ "--- test setUp() for %s.%s(%s) starts here ---\n"
+ % (self.__class__.__name__, self._testMethodName, self._testMethodDoc)
+ )
self.vapi.cli("clear trace")
# store the test instance inside the test class - so that objects
# holding the class can access instance methods (like assertEqual)
@@ -816,7 +910,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
@classmethod
def register_pcap(cls, intf, worker):
- """ Register a pcap in the testclass """
+ """Register a pcap in the testclass"""
# add to the list of captures with current timestamp
cls._pcaps.append((intf, worker))
@@ -824,14 +918,14 @@ class VppTestCase(CPUInterface, unittest.TestCase):
def get_vpp_time(cls):
# processes e.g. "Time now 2.190522, Wed, 11 Mar 2020 17:29:54 GMT"
# returns float("2.190522")
- timestr = cls.vapi.cli('show clock')
- head, sep, tail = timestr.partition(',')
- head, sep, tail = head.partition('Time now')
+ timestr = cls.vapi.cli("show clock")
+ head, sep, tail = timestr.partition(",")
+ head, sep, tail = head.partition("Time now")
return float(tail)
@classmethod
def sleep_on_vpp_time(cls, sec):
- """ Sleep according to time in VPP world """
+ """Sleep according to time in VPP world"""
# On a busy system with many processes
# we might end up with VPP time being slower than real world
# So take that into account when waiting for VPP to do something
@@ -841,34 +935,31 @@ class VppTestCase(CPUInterface, unittest.TestCase):
@classmethod
def pg_start(cls, trace=True):
- """ Enable the PG, wait till it is done, then clean up """
+ """Enable the PG, wait till it is done, then clean up"""
for (intf, worker) in cls._old_pcaps:
- intf.handle_old_pcap_file(intf.get_in_path(worker),
- intf.in_history_counter)
+ intf.handle_old_pcap_file(intf.get_in_path(worker), intf.in_history_counter)
cls._old_pcaps = []
if trace:
cls.vapi.cli("clear trace")
cls.vapi.cli("trace add pg-input 1000")
- cls.vapi.cli('packet-generator enable')
+ cls.vapi.cli("packet-generator enable")
# PG, when starts, runs to completion -
# so let's avoid a race condition,
# and wait a little till it's done.
# Then clean it up - and then be gone.
deadline = time.time() + 300
- while cls.vapi.cli('show packet-generator').find("Yes") != -1:
+ while cls.vapi.cli("show packet-generator").find("Yes") != -1:
cls.sleep(0.01) # yield
if time.time() > deadline:
cls.logger.error("Timeout waiting for pg to stop")
break
for intf, worker in cls._pcaps:
- cls.vapi.cli('packet-generator delete %s' %
- intf.get_cap_name(worker))
+ cls.vapi.cli("packet-generator delete %s" % intf.get_cap_name(worker))
cls._old_pcaps = cls._pcaps
cls._pcaps = []
@classmethod
- def create_pg_interfaces_internal(cls, interfaces, gso=0, gso_size=0,
- mode=None):
+ def create_pg_interfaces_internal(cls, interfaces, gso=0, gso_size=0, mode=None):
"""
Create packet-generator interfaces.
@@ -887,26 +978,30 @@ class VppTestCase(CPUInterface, unittest.TestCase):
@classmethod
def create_pg_ip4_interfaces(cls, interfaces, gso=0, gso_size=0):
pgmode = VppEnum.vl_api_pg_interface_mode_t
- return cls.create_pg_interfaces_internal(interfaces, gso, gso_size,
- pgmode.PG_API_MODE_IP4)
+ return cls.create_pg_interfaces_internal(
+ interfaces, gso, gso_size, pgmode.PG_API_MODE_IP4
+ )
@classmethod
def create_pg_ip6_interfaces(cls, interfaces, gso=0, gso_size=0):
pgmode = VppEnum.vl_api_pg_interface_mode_t
- return cls.create_pg_interfaces_internal(interfaces, gso, gso_size,
- pgmode.PG_API_MODE_IP6)
+ return cls.create_pg_interfaces_internal(
+ interfaces, gso, gso_size, pgmode.PG_API_MODE_IP6
+ )
@classmethod
def create_pg_interfaces(cls, interfaces, gso=0, gso_size=0):
pgmode = VppEnum.vl_api_pg_interface_mode_t
- return cls.create_pg_interfaces_internal(interfaces, gso, gso_size,
- pgmode.PG_API_MODE_ETHERNET)
+ return cls.create_pg_interfaces_internal(
+ interfaces, gso, gso_size, pgmode.PG_API_MODE_ETHERNET
+ )
@classmethod
def create_pg_ethernet_interfaces(cls, interfaces, gso=0, gso_size=0):
pgmode = VppEnum.vl_api_pg_interface_mode_t
- return cls.create_pg_interfaces_internal(interfaces, gso, gso_size,
- pgmode.PG_API_MODE_ETHERNET)
+ return cls.create_pg_interfaces_internal(
+ interfaces, gso, gso_size, pgmode.PG_API_MODE_ETHERNET
+ )
@classmethod
def create_loopback_interfaces(cls, count):
@@ -937,7 +1032,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
return result
@staticmethod
- def extend_packet(packet, size, padding=' '):
+ def extend_packet(packet, size, padding=" "):
"""
Extend packet to given size by padding with spaces or custom padding
NOTE: Currently works only when Raw layer is present.
@@ -955,7 +1050,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
@classmethod
def reset_packet_infos(cls):
- """ Reset the list of packet info objects and packet counts to zero """
+ """Reset the list of packet info objects and packet counts to zero"""
cls._packet_infos = {}
cls._packet_count_for_dst_if_idx = {}
@@ -997,11 +1092,10 @@ class VppTestCase(CPUInterface, unittest.TestCase):
"""
# retrieve payload, currently 18 bytes (4 x ints + 1 short)
- return pack('iiiih', info.index, info.src,
- info.dst, info.ip, info.proto)
+ return pack("iiiih", info.index, info.src, info.dst, info.ip, info.proto)
@staticmethod
- def payload_to_info(payload, payload_field='load'):
+ def payload_to_info(payload, payload_field="load"):
"""
Convert packet payload to _PacketInfo object
@@ -1018,12 +1112,11 @@ class VppTestCase(CPUInterface, unittest.TestCase):
payload_b = getattr(payload, payload_field)[:18]
info = _PacketInfo()
- info.index, info.src, info.dst, info.ip, info.proto \
- = unpack('iiiih', payload_b)
+ info.index, info.src, info.dst, info.ip, info.proto = unpack("iiiih", payload_b)
# some SRv6 TCs depend on get an exception if bad values are detected
if info.index > 0x4000:
- raise ValueError('Index value is invalid')
+ raise ValueError("Index value is invalid")
return info
@@ -1086,32 +1179,38 @@ class VppTestCase(CPUInterface, unittest.TestCase):
return
try:
msg = "Invalid %s: %d('%s') does not match expected value %d('%s')"
- msg = msg % (getdoc(name_or_class).strip(),
- real_value, str(name_or_class(real_value)),
- expected_value, str(name_or_class(expected_value)))
+ msg = msg % (
+ getdoc(name_or_class).strip(),
+ real_value,
+ str(name_or_class(real_value)),
+ expected_value,
+ str(name_or_class(expected_value)),
+ )
except Exception:
msg = "Invalid %s: %s does not match expected value %s" % (
- name_or_class, real_value, expected_value)
+ name_or_class,
+ real_value,
+ expected_value,
+ )
self.assertEqual(real_value, expected_value, msg)
- def assert_in_range(self,
- real_value,
- expected_min,
- expected_max,
- name=None):
+ def assert_in_range(self, real_value, expected_min, expected_max, name=None):
if name is None:
msg = None
else:
msg = "Invalid %s: %s out of range <%s,%s>" % (
- name, real_value, expected_min, expected_max)
+ name,
+ real_value,
+ expected_min,
+ expected_max,
+ )
self.assertTrue(expected_min <= real_value <= expected_max, msg)
- def assert_packet_checksums_valid(self, packet,
- ignore_zero_udp_checksums=True):
+ def assert_packet_checksums_valid(self, packet, ignore_zero_udp_checksums=True):
received = packet.__class__(scapy.compat.raw(packet))
- udp_layers = ['UDP', 'UDPerror']
- checksum_fields = ['cksum', 'chksum']
+ udp_layers = ["UDP", "UDPerror"]
+ checksum_fields = ["cksum", "chksum"]
checksums = []
counter = 0
temp = received.__class__(scapy.compat.raw(received))
@@ -1122,9 +1221,11 @@ class VppTestCase(CPUInterface, unittest.TestCase):
layer.remove_payload()
for cf in checksum_fields:
if hasattr(layer, cf):
- if ignore_zero_udp_checksums and \
- 0 == getattr(layer, cf) and \
- layer.name in udp_layers:
+ if (
+ ignore_zero_udp_checksums
+ and 0 == getattr(layer, cf)
+ and layer.name in udp_layers
+ ):
continue
delattr(temp.getlayer(counter), cf)
checksums.append((counter, cf))
@@ -1137,71 +1238,76 @@ class VppTestCase(CPUInterface, unittest.TestCase):
for layer, cf in checksums:
calc_sum = getattr(temp[layer], cf)
self.assert_equal(
- getattr(received[layer], cf), calc_sum,
- "packet checksum on layer #%d: %s" % (layer, temp[layer].name))
+ getattr(received[layer], cf),
+ calc_sum,
+ "packet checksum on layer #%d: %s" % (layer, temp[layer].name),
+ )
self.logger.debug(
- "Checksum field `%s` on `%s` layer has correct value `%s`" %
- (cf, temp[layer].name, calc_sum))
-
- def assert_checksum_valid(self, received_packet, layer,
- field_name='chksum',
- ignore_zero_checksum=False):
- """ Check checksum of received packet on given layer """
+ "Checksum field `%s` on `%s` layer has correct value `%s`"
+ % (cf, temp[layer].name, calc_sum)
+ )
+
+ def assert_checksum_valid(
+ self, received_packet, layer, field_name="chksum", ignore_zero_checksum=False
+ ):
+ """Check checksum of received packet on given layer"""
received_packet_checksum = getattr(received_packet[layer], field_name)
if ignore_zero_checksum and 0 == received_packet_checksum:
return
- recalculated = received_packet.__class__(
- scapy.compat.raw(received_packet))
+ recalculated = received_packet.__class__(scapy.compat.raw(received_packet))
delattr(recalculated[layer], field_name)
recalculated = recalculated.__class__(scapy.compat.raw(recalculated))
- self.assert_equal(received_packet_checksum,
- getattr(recalculated[layer], field_name),
- "packet checksum on layer: %s" % layer)
-
- def assert_ip_checksum_valid(self, received_packet,
- ignore_zero_checksum=False):
- self.assert_checksum_valid(received_packet, 'IP',
- ignore_zero_checksum=ignore_zero_checksum)
-
- def assert_tcp_checksum_valid(self, received_packet,
- ignore_zero_checksum=False):
- self.assert_checksum_valid(received_packet, 'TCP',
- ignore_zero_checksum=ignore_zero_checksum)
-
- def assert_udp_checksum_valid(self, received_packet,
- ignore_zero_checksum=True):
- self.assert_checksum_valid(received_packet, 'UDP',
- ignore_zero_checksum=ignore_zero_checksum)
+ self.assert_equal(
+ received_packet_checksum,
+ getattr(recalculated[layer], field_name),
+ "packet checksum on layer: %s" % layer,
+ )
+
+ def assert_ip_checksum_valid(self, received_packet, ignore_zero_checksum=False):
+ self.assert_checksum_valid(
+ received_packet, "IP", ignore_zero_checksum=ignore_zero_checksum
+ )
+
+ def assert_tcp_checksum_valid(self, received_packet, ignore_zero_checksum=False):
+ self.assert_checksum_valid(
+ received_packet, "TCP", ignore_zero_checksum=ignore_zero_checksum
+ )
+
+ def assert_udp_checksum_valid(self, received_packet, ignore_zero_checksum=True):
+ self.assert_checksum_valid(
+ received_packet, "UDP", ignore_zero_checksum=ignore_zero_checksum
+ )
def assert_embedded_icmp_checksum_valid(self, received_packet):
if received_packet.haslayer(IPerror):
- self.assert_checksum_valid(received_packet, 'IPerror')
+ self.assert_checksum_valid(received_packet, "IPerror")
if received_packet.haslayer(TCPerror):
- self.assert_checksum_valid(received_packet, 'TCPerror')
+ self.assert_checksum_valid(received_packet, "TCPerror")
if received_packet.haslayer(UDPerror):
- self.assert_checksum_valid(received_packet, 'UDPerror',
- ignore_zero_checksum=True)
+ self.assert_checksum_valid(
+ received_packet, "UDPerror", ignore_zero_checksum=True
+ )
if received_packet.haslayer(ICMPerror):
- self.assert_checksum_valid(received_packet, 'ICMPerror')
+ self.assert_checksum_valid(received_packet, "ICMPerror")
def assert_icmp_checksum_valid(self, received_packet):
- self.assert_checksum_valid(received_packet, 'ICMP')
+ self.assert_checksum_valid(received_packet, "ICMP")
self.assert_embedded_icmp_checksum_valid(received_packet)
def assert_icmpv6_checksum_valid(self, pkt):
if pkt.haslayer(ICMPv6DestUnreach):
- self.assert_checksum_valid(pkt, 'ICMPv6DestUnreach', 'cksum')
+ self.assert_checksum_valid(pkt, "ICMPv6DestUnreach", "cksum")
self.assert_embedded_icmp_checksum_valid(pkt)
if pkt.haslayer(ICMPv6EchoRequest):
- self.assert_checksum_valid(pkt, 'ICMPv6EchoRequest', 'cksum')
+ self.assert_checksum_valid(pkt, "ICMPv6EchoRequest", "cksum")
if pkt.haslayer(ICMPv6EchoReply):
- self.assert_checksum_valid(pkt, 'ICMPv6EchoReply', 'cksum')
+ self.assert_checksum_valid(pkt, "ICMPv6EchoReply", "cksum")
def get_counter(self, counter):
if counter.startswith("/"):
counter_value = self.statistics.get_counter(counter)
else:
- counters = self.vapi.cli("sh errors").split('\n')
+ counters = self.vapi.cli("sh errors").split("\n")
counter_value = 0
for i in range(1, len(counters) - 1):
results = counters[i].split()
@@ -1210,8 +1316,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
break
return counter_value
- def assert_counter_equal(self, counter, expected_value,
- thread=None, index=0):
+ def assert_counter_equal(self, counter, expected_value, thread=None, index=0):
c = self.get_counter(counter)
if thread is not None:
c = c[thread][index]
@@ -1221,13 +1326,13 @@ class VppTestCase(CPUInterface, unittest.TestCase):
def assert_packet_counter_equal(self, counter, expected_value):
counter_value = self.get_counter(counter)
- self.assert_equal(counter_value, expected_value,
- "packet counter `%s'" % counter)
+ self.assert_equal(
+ counter_value, expected_value, "packet counter `%s'" % counter
+ )
def assert_error_counter_equal(self, counter, expected_value):
counter_value = self.statistics[counter].sum()
- self.assert_equal(counter_value, expected_value,
- "error counter `%s'" % counter)
+ self.assert_equal(counter_value, expected_value, "error counter `%s'" % counter)
@classmethod
def sleep(cls, timeout, remark=None):
@@ -1238,7 +1343,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
# https://github.com/python/cpython/blob/6673decfa0fb078f60587f5cb5e98460eea137c2/Modules/timemodule.c#L1892 # noqa
if timeout == 0:
# yield quantum
- if hasattr(os, 'sched_yield'):
+ if hasattr(os, "sched_yield"):
os.sched_yield()
else:
time.sleep(0)
@@ -1249,13 +1354,18 @@ class VppTestCase(CPUInterface, unittest.TestCase):
time.sleep(timeout)
after = time.time()
if after - before > 2 * timeout:
- cls.logger.error("unexpected self.sleep() result - "
- "slept for %es instead of ~%es!",
- after - before, timeout)
+ cls.logger.error(
+ "unexpected self.sleep() result - slept for %es instead of ~%es!",
+ after - before,
+ timeout,
+ )
cls.logger.debug(
"Finished sleep (%s) - slept %es (wanted %es)",
- remark, after - before, timeout)
+ remark,
+ after - before,
+ timeout,
+ )
def virtual_sleep(self, timeout, remark=None):
self.logger.debug("Moving VPP time by %s (%s)", timeout, remark)
@@ -1285,7 +1395,8 @@ class VppTestCase(CPUInterface, unittest.TestCase):
stats_snapshot[cntr].sum() + diff,
f"'{cntr}' counter value (previous value: "
f"{stats_snapshot[cntr].sum()}, "
- f"expected diff: {diff})")
+ f"expected diff: {diff})",
+ )
else:
try:
self.assert_equal(
@@ -1293,7 +1404,8 @@ class VppTestCase(CPUInterface, unittest.TestCase):
stats_snapshot[cntr][:, sw_if_index].sum() + diff,
f"'{cntr}' counter value (previous value: "
f"{stats_snapshot[cntr][:, sw_if_index].sum()}, "
- f"expected diff: {diff})")
+ f"expected diff: {diff})",
+ )
except IndexError:
# if diff is 0, then this most probably a case where
# test declares multiple interfaces but traffic hasn't
@@ -1302,8 +1414,9 @@ class VppTestCase(CPUInterface, unittest.TestCase):
if 0 != diff:
raise
- def send_and_assert_no_replies(self, intf, pkts, remark="", timeout=None,
- stats_diff=None, trace=True, msg=None):
+ def send_and_assert_no_replies(
+ self, intf, pkts, remark="", timeout=None, stats_diff=None, trace=True, msg=None
+ ):
if stats_diff:
stats_snapshot = self.snapshot_stats(stats_diff)
@@ -1324,8 +1437,17 @@ class VppTestCase(CPUInterface, unittest.TestCase):
if stats_diff:
self.compare_stats_with_snapshot(stats_diff, stats_snapshot)
- def send_and_expect(self, intf, pkts, output, n_rx=None, worker=None,
- trace=True, msg=None, stats_diff=None):
+ def send_and_expect(
+ self,
+ intf,
+ pkts,
+ output,
+ n_rx=None,
+ worker=None,
+ trace=True,
+ msg=None,
+ stats_diff=None,
+ ):
if stats_diff:
stats_snapshot = self.snapshot_stats(stats_diff)
@@ -1343,8 +1465,9 @@ class VppTestCase(CPUInterface, unittest.TestCase):
return rx
- def send_and_expect_load_balancing(self, input, pkts, outputs,
- worker=None, trace=True):
+ def send_and_expect_load_balancing(
+ self, input, pkts, outputs, worker=None, trace=True
+ ):
self.pg_send(input, pkts, worker=worker, trace=trace)
rxs = []
for oo in outputs:
@@ -1355,9 +1478,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
self.logger.debug(self.vapi.cli("show trace"))
return rxs
- def send_and_expect_some(self, intf, pkts, output,
- worker=None,
- trace=True):
+ def send_and_expect_some(self, intf, pkts, output, worker=None, trace=True):
self.pg_send(intf, pkts, worker=worker, trace=trace)
rx = output._get_capture(1)
if trace:
@@ -1366,8 +1487,7 @@ class VppTestCase(CPUInterface, unittest.TestCase):
self.assertTrue(len(rx) < len(pkts))
return rx
- def send_and_expect_only(self, intf, pkts, output, timeout=None,
- stats_diff=None):
+ def send_and_expect_only(self, intf, pkts, output, timeout=None, stats_diff=None):
if stats_diff:
stats_snapshot = self.snapshot_stats(stats_diff)
@@ -1427,8 +1547,7 @@ class VppTestResult(unittest.TestResult):
core_crash_test_cases_info = set()
current_test_case_info = None
- def __init__(self, stream=None, descriptions=None, verbosity=None,
- runner=None):
+ def __init__(self, stream=None, descriptions=None, verbosity=None, runner=None):
"""
:param stream File descriptor to store where to report test results.
Set to the standard error stream by default.
@@ -1453,9 +1572,9 @@ class VppTestResult(unittest.TestResult):
"""
if self.current_test_case_info:
self.current_test_case_info.logger.debug(
- "--- addSuccess() %s.%s(%s) called" % (test.__class__.__name__,
- test._testMethodName,
- test._testMethodDoc))
+ "--- addSuccess() %s.%s(%s) called"
+ % (test.__class__.__name__, test._testMethodName, test._testMethodDoc)
+ )
unittest.TestResult.addSuccess(self, test)
self.result_string = colorize("OK", GREEN)
@@ -1471,9 +1590,14 @@ class VppTestResult(unittest.TestResult):
"""
if self.current_test_case_info:
self.current_test_case_info.logger.debug(
- "--- addSkip() %s.%s(%s) called, reason is %s" %
- (test.__class__.__name__, test._testMethodName,
- test._testMethodDoc, reason))
+ "--- addSkip() %s.%s(%s) called, reason is %s"
+ % (
+ test.__class__.__name__,
+ test._testMethodName,
+ test._testMethodDoc,
+ reason,
+ )
+ )
unittest.TestResult.addSkip(self, test, reason)
self.result_string = colorize("SKIP", YELLOW)
@@ -1488,17 +1612,18 @@ class VppTestResult(unittest.TestResult):
failed_dir = config.failed_dir
link_path = os.path.join(
failed_dir,
- '%s-FAILED' %
- os.path.basename(self.current_test_case_info.tempdir))
+ "%s-FAILED" % os.path.basename(self.current_test_case_info.tempdir),
+ )
self.current_test_case_info.logger.debug(
- "creating a link to the failed test")
+ "creating a link to the failed test"
+ )
self.current_test_case_info.logger.debug(
- "os.symlink(%s, %s)" %
- (self.current_test_case_info.tempdir, link_path))
+ "os.symlink(%s, %s)"
+ % (self.current_test_case_info.tempdir, link_path)
+ )
if os.path.exists(link_path):
- self.current_test_case_info.logger.debug(
- 'symlink already exists')
+ self.current_test_case_info.logger.debug("symlink already exists")
else:
os.symlink(self.current_test_case_info.tempdir, link_path)
@@ -1506,7 +1631,7 @@ class VppTestResult(unittest.TestResult):
self.current_test_case_info.logger.error(e)
def send_result_through_pipe(self, test, result):
- if hasattr(self, 'test_framework_result_pipe'):
+ if hasattr(self, "test_framework_result_pipe"):
pipe = self.test_framework_result_pipe
if pipe:
pipe.send((test.id(), result))
@@ -1516,32 +1641,37 @@ class VppTestResult(unittest.TestResult):
if isinstance(test, unittest.suite._ErrorHolder):
test_name = test.description
else:
- test_name = '%s.%s(%s)' % (test.__class__.__name__,
- test._testMethodName,
- test._testMethodDoc)
+ test_name = "%s.%s(%s)" % (
+ test.__class__.__name__,
+ test._testMethodName,
+ test._testMethodDoc,
+ )
self.current_test_case_info.logger.debug(
- "--- %s() %s called, err is %s" %
- (fn_name, test_name, err))
+ "--- %s() %s called, err is %s" % (fn_name, test_name, err)
+ )
self.current_test_case_info.logger.debug(
- "formatted exception is:\n%s" %
- "".join(format_exception(*err)))
+ "formatted exception is:\n%s" % "".join(format_exception(*err))
+ )
def add_error(self, test, err, unittest_fn, error_type):
if error_type == FAIL:
- self.log_error(test, err, 'addFailure')
+ self.log_error(test, err, "addFailure")
error_type_str = colorize("FAIL", RED)
elif error_type == ERROR:
- self.log_error(test, err, 'addError')
+ self.log_error(test, err, "addError")
error_type_str = colorize("ERROR", RED)
else:
- raise Exception('Error type %s cannot be used to record an '
- 'error or a failure' % error_type)
+ raise Exception(
+ "Error type %s cannot be used to record an "
+ "error or a failure" % error_type
+ )
unittest_fn(self, test, err)
if self.current_test_case_info:
- self.result_string = "%s [ temp dir used by test case: %s ]" % \
- (error_type_str,
- self.current_test_case_info.tempdir)
+ self.result_string = "%s [ temp dir used by test case: %s ]" % (
+ error_type_str,
+ self.current_test_case_info.tempdir,
+ )
self.symlink_failed()
self.failed_test_cases_info.add(self.current_test_case_info)
if is_core_present(self.current_test_case_info.tempdir):
@@ -1550,12 +1680,12 @@ class VppTestResult(unittest.TestResult):
test_name = str(test)
else:
test_name = "'{!s}' ({!s})".format(
- get_testcase_doc_name(test), test.id())
+ get_testcase_doc_name(test), test.id()
+ )
self.current_test_case_info.core_crash_test = test_name
- self.core_crash_test_cases_info.add(
- self.current_test_case_info)
+ self.core_crash_test_cases_info.add(self.current_test_case_info)
else:
- self.result_string = '%s [no temp dir]' % error_type_str
+ self.result_string = "%s [no temp dir]" % error_type_str
self.send_result_through_pipe(test, error_type)
@@ -1613,15 +1743,13 @@ class VppTestResult(unittest.TestResult):
# This block may overwrite the colorized title above,
# but we want this to stand out and be fixed
if test.has_tag(TestCaseTag.FIXME_VPP_WORKERS):
- test_title = colorize(
- f"FIXME with VPP workers: {test_title}", RED)
+ test_title = colorize(f"FIXME with VPP workers: {test_title}", RED)
if test.has_tag(TestCaseTag.FIXME_ASAN):
- test_title = colorize(
- f"FIXME with ASAN: {test_title}", RED)
+ test_title = colorize(f"FIXME with ASAN: {test_title}", RED)
test.skip_fixme_asan()
- if hasattr(test, 'vpp_worker_count'):
+ if hasattr(test, "vpp_worker_count"):
if test.vpp_worker_count == 0:
test_title += " [main thread only]"
elif test.vpp_worker_count == 1:
@@ -1633,7 +1761,9 @@ class VppTestResult(unittest.TestResult):
test_title = colorize(
f"{test_title} [skipped - not enough cpus, "
f"required={test.__class__.get_cpus_required()}, "
- f"available={max_vpp_cpus}]", YELLOW)
+ f"available={max_vpp_cpus}]",
+ YELLOW,
+ )
print(double_line_delim)
print(test_title)
@@ -1644,8 +1774,7 @@ class VppTestResult(unittest.TestResult):
self.start_test = time.time()
unittest.TestResult.startTest(self, test)
if self.verbosity > 0:
- self.stream.writeln(
- "Starting " + self.getDescription(test) + " ...")
+ self.stream.writeln("Starting " + self.getDescription(test) + " ...")
self.stream.writeln(single_line_delim)
def stopTest(self, test):
@@ -1659,14 +1788,19 @@ class VppTestResult(unittest.TestResult):
if self.verbosity > 0:
self.stream.writeln(single_line_delim)
- self.stream.writeln("%-73s%s" % (self.getDescription(test),
- self.result_string))
+ self.stream.writeln(
+ "%-73s%s" % (self.getDescription(test), self.result_string)
+ )
self.stream.writeln(single_line_delim)
else:
- self.stream.writeln("%-68s %4.2f %s" %
- (self.getDescription(test),
- time.time() - self.start_test,
- self.result_string))
+ self.stream.writeln(
+ "%-68s %4.2f %s"
+ % (
+ self.getDescription(test),
+ time.time() - self.start_test,
+ self.result_string,
+ )
+ )
self.send_result_through_pipe(test, TEST_RUN)
@@ -1676,12 +1810,12 @@ class VppTestResult(unittest.TestResult):
"""
if len(self.errors) > 0 or len(self.failures) > 0:
self.stream.writeln()
- self.printErrorList('ERROR', self.errors)
- self.printErrorList('FAIL', self.failures)
+ self.printErrorList("ERROR", self.errors)
+ self.printErrorList("FAIL", self.failures)
# ^^ that is the last output from unittest before summary
if not self.runner.print_summary:
- devnull = unittest.runner._WritelnDecorator(open(os.devnull, 'w'))
+ devnull = unittest.runner._WritelnDecorator(open(os.devnull, "w"))
self.stream = devnull
self.runner.stream = devnull
@@ -1696,8 +1830,7 @@ class VppTestResult(unittest.TestResult):
"""
for test, err in errors:
self.stream.writeln(double_line_delim)
- self.stream.writeln("%s: %s" %
- (flavour, self.getDescription(test)))
+ self.stream.writeln("%s: %s" % (flavour, self.getDescription(test)))
self.stream.writeln(single_line_delim)
self.stream.writeln("%s" % err)
@@ -1712,14 +1845,23 @@ class VppTestRunner(unittest.TextTestRunner):
"""Class maintaining the results of the tests"""
return VppTestResult
- def __init__(self, keep_alive_pipe=None, descriptions=True, verbosity=1,
- result_pipe=None, failfast=False, buffer=False,
- resultclass=None, print_summary=True, **kwargs):
+ def __init__(
+ self,
+ keep_alive_pipe=None,
+ descriptions=True,
+ verbosity=1,
+ result_pipe=None,
+ failfast=False,
+ buffer=False,
+ resultclass=None,
+ print_summary=True,
+ **kwargs,
+ ):
# ignore stream setting here, use hard-coded stdout to be in sync
# with prints from VppTestCase methods ...
- super(VppTestRunner, self).__init__(sys.stdout, descriptions,
- verbosity, failfast, buffer,
- resultclass, **kwargs)
+ super(VppTestRunner, self).__init__(
+ sys.stdout, descriptions, verbosity, failfast, buffer, resultclass, **kwargs
+ )
KeepAliveReporter.pipe = keep_alive_pipe
self.orig_stream = self.stream
@@ -1728,10 +1870,7 @@ class VppTestRunner(unittest.TextTestRunner):
self.print_summary = print_summary
def _makeResult(self):
- return self.resultclass(self.stream,
- self.descriptions,
- self.verbosity,
- self)
+ return self.resultclass(self.stream, self.descriptions, self.verbosity, self)
def run(self, test):
"""
@@ -1754,91 +1893,120 @@ class Worker(Thread):
super(Worker, self).__init__(*args, **kwargs)
self.logger = logger
self.args = executable_args
- if hasattr(self, 'testcase') and self.testcase.debug_all:
+ if hasattr(self, "testcase") and self.testcase.debug_all:
if self.testcase.debug_gdbserver:
- self.args = ['/usr/bin/gdbserver', 'localhost:{port}'
- .format(port=self.testcase.gdbserver_port)] + args
- elif self.testcase.debug_gdb and hasattr(self, 'wait_for_gdb'):
+ self.args = [
+ "/usr/bin/gdbserver",
+ "localhost:{port}".format(port=self.testcase.gdbserver_port),
+ ] + args
+ elif self.testcase.debug_gdb and hasattr(self, "wait_for_gdb"):
self.args.append(self.wait_for_gdb)
self.app_bin = executable_args[0]
self.app_name = os.path.basename(self.app_bin)
- if hasattr(self, 'role'):
- self.app_name += ' {role}'.format(role=self.role)
+ if hasattr(self, "role"):
+ self.app_name += " {role}".format(role=self.role)
self.process = None
self.result = None
env = {} if env is None else env
self.env = copy.deepcopy(env)
def wait_for_enter(self):
- if not hasattr(self, 'testcase'):
+ if not hasattr(self, "testcase"):
return
if self.testcase.debug_all and self.testcase.debug_gdbserver:
print()
print(double_line_delim)
- print("Spawned GDB Server for '{app}' with PID: {pid}"
- .format(app=self.app_name, pid=self.process.pid))
+ print(
+ "Spawned GDB Server for '{app}' with PID: {pid}".format(
+ app=self.app_name, pid=self.process.pid
+ )
+ )
elif self.testcase.debug_all and self.testcase.debug_gdb:
print()
print(double_line_delim)
- print("Spawned '{app}' with PID: {pid}"
- .format(app=self.app_name, pid=self.process.pid))
+ print(
+ "Spawned '{app}' with PID: {pid}".format(
+ app=self.app_name, pid=self.process.pid
+ )
+ )
else:
return
print(single_line_delim)
print("You can debug '{app}' using:".format(app=self.app_name))
if self.testcase.debug_gdbserver:
- print("sudo gdb " + self.app_bin +
- " -ex 'target remote localhost:{port}'"
- .format(port=self.testcase.gdbserver_port))
- print("Now is the time to attach gdb by running the above "
- "command, set up breakpoints etc., then resume from "
- "within gdb by issuing the 'continue' command")
+ print(
+ "sudo gdb "
+ + self.app_bin
+ + " -ex 'target remote localhost:{port}'".format(
+ port=self.testcase.gdbserver_port
+ )
+ )
+ print(
+ "Now is the time to attach gdb by running the above "
+ "command, set up breakpoints etc., then resume from "
+ "within gdb by issuing the 'continue' command"
+ )
self.testcase.gdbserver_port += 1
elif self.testcase.debug_gdb:
- print("sudo gdb " + self.app_bin +
- " -ex 'attach {pid}'".format(pid=self.process.pid))
- print("Now is the time to attach gdb by running the above "
- "command and set up breakpoints etc., then resume from"
- " within gdb by issuing the 'continue' command")
+ print(
+ "sudo gdb "
+ + self.app_bin
+ + " -ex 'attach {pid}'".format(pid=self.process.pid)
+ )
+ print(
+ "Now is the time to attach gdb by running the above "
+ "command and set up breakpoints etc., then resume from"
+ " within gdb by issuing the 'continue' command"
+ )
print(single_line_delim)
input("Press ENTER to continue running the testcase...")
def run(self):
executable = self.args[0]
if not os.path.exists(executable) or not os.access(
- executable, os.F_OK | os.X_OK):
+ executable, os.F_OK | os.X_OK
+ ):
# Exit code that means some system file did not exist,
# could not be opened, or had some other kind of error.
self.result = os.EX_OSFILE
raise EnvironmentError(
- "executable '%s' is not found or executable." % executable)
- self.logger.debug("Running executable '{app}': '{cmd}'"
- .format(app=self.app_name,
- cmd=' '.join(self.args)))
+ "executable '%s' is not found or executable." % executable
+ )
+ self.logger.debug(
+ "Running executable '{app}': '{cmd}'".format(
+ app=self.app_name, cmd=" ".join(self.args)
+ )
+ )
env = os.environ.copy()
env.update(self.env)
env["CK_LOG_FILE_NAME"] = "-"
self.process = subprocess.Popen(
- ['stdbuf', '-o0', '-e0'] + self.args, shell=False, env=env,
- preexec_fn=os.setpgrp, stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
+ ["stdbuf", "-o0", "-e0"] + self.args,
+ shell=False,
+ env=env,
+ preexec_fn=os.setpgrp,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
self.wait_for_enter()
out, err = self.process.communicate()
self.logger.debug("Finished running `{app}'".format(app=self.app_name))
self.logger.info("Return code is `%s'" % self.process.returncode)
self.logger.info(single_line_delim)
- self.logger.info("Executable `{app}' wrote to stdout:"
- .format(app=self.app_name))
+ self.logger.info(
+ "Executable `{app}' wrote to stdout:".format(app=self.app_name)
+ )
self.logger.info(single_line_delim)
- self.logger.info(out.decode('utf-8'))
+ self.logger.info(out.decode("utf-8"))
self.logger.info(single_line_delim)
- self.logger.info("Executable `{app}' wrote to stderr:"
- .format(app=self.app_name))
+ self.logger.info(
+ "Executable `{app}' wrote to stderr:".format(app=self.app_name)
+ )
self.logger.info(single_line_delim)
- self.logger.info(err.decode('utf-8'))
+ self.logger.info(err.decode("utf-8"))
self.logger.info(single_line_delim)
self.result = self.process.returncode
-if __name__ == '__main__':
+if __name__ == "__main__":
pass
diff --git a/test/hook.py b/test/hook.py
index 8033c9355cb..3429bdad1fe 100644
--- a/test/hook.py
+++ b/test/hook.py
@@ -33,19 +33,20 @@ class Hook:
if not isinstance(val, str):
return val
if len(val) == 6:
- return '{!s} ({!s})'.format(val, ':'.join(['{:02x}'.format(
- scapy.compat.orb(x)) for x in val]))
+ return "{!s} ({!s})".format(
+ val, ":".join(["{:02x}".format(scapy.compat.orb(x)) for x in val])
+ )
try:
# we don't call test_type(val) because it is a packed value.
- return '{!s} ({!s})'.format(val, str(
- ipaddress.ip_address(val)))
+ return "{!s} ({!s})".format(val, str(ipaddress.ip_address(val)))
except ValueError:
return val
- _args = ', '.join("{!s}={!r}".format(key, _friendly_format(val)) for
- (key, val) in api_args.items())
- self.logger.debug("API: %s (%s)" %
- (api_name, _args), extra={'color': RED})
+ _args = ", ".join(
+ "{!s}={!r}".format(key, _friendly_format(val))
+ for (key, val) in api_args.items()
+ )
+ self.logger.debug("API: %s (%s)" % (api_name, _args), extra={"color": RED})
def after_api(self, api_name, api_args):
"""
@@ -63,7 +64,7 @@ class Hook:
@param cli: CLI string
"""
- self.logger.debug("CLI: %s" % (cli), extra={'color': RED})
+ self.logger.debug("CLI: %s" % (cli), extra={"color": RED})
def after_cli(self, cli):
"""
@@ -73,14 +74,15 @@ class Hook:
class PollHook(Hook):
- """ Hook which checks if the vpp subprocess is alive """
+ """Hook which checks if the vpp subprocess is alive"""
def __init__(self, test):
super(PollHook, self).__init__(test)
def on_crash(self, core_path):
- self.logger.error("Core file present, debug with: gdb %s %s",
- config.vpp, core_path)
+ self.logger.error(
+ "Core file present, debug with: gdb %s %s", config.vpp, core_path
+ )
check_core_path(self.logger, core_path)
self.logger.error("Running `file %s':", core_path)
try:
@@ -90,17 +92,24 @@ class PollHook(Hook):
self.logger.error(
"Subprocess returned with error running `file' utility on "
"core-file, "
- "rc=%s", e.returncode)
+ "rc=%s",
+ e.returncode,
+ )
except OSError as e:
self.logger.error(
"Subprocess returned OS error running `file' utility on "
"core-file, "
- "oserror=(%s) %s", e.errno, e.strerror)
+ "oserror=(%s) %s",
+ e.errno,
+ e.strerror,
+ )
except Exception as e:
self.logger.error(
"Subprocess returned unanticipated error running `file' "
"utility on core-file, "
- "%s", e)
+ "%s",
+ e,
+ )
def poll_vpp(self):
"""
@@ -144,7 +153,7 @@ class PollHook(Hook):
class StepHook(PollHook):
- """ Hook which requires user to press ENTER before doing any API/CLI """
+ """Hook which requires user to press ENTER before doing any API/CLI"""
def __init__(self, test):
self.skip_stack = None
@@ -183,19 +192,18 @@ class StepHook(PollHook):
self.skip_count += 1
return True
else:
- print("%d API/CLI calls skipped in specified stack "
- "frame" % self.skip_count)
+ print("%d API/CLI calls skipped in specified stack frame" % self.skip_count)
self.skip_count = 0
self.skip_stack = None
self.skip_num = None
return False
def user_input(self):
- print('number\tfunction\tfile\tcode')
+ print("number\tfunction\tfile\tcode")
counter = 0
stack = traceback.extract_stack()
for e in stack:
- print('%02d.\t%s\t%s:%d\t[%s]' % (counter, e[2], e[0], e[1], e[3]))
+ print("%02d.\t%s\t%s:%d\t[%s]" % (counter, e[2], e[0], e[1], e[3]))
counter += 1
print(single_line_delim)
print("You may enter a number of stack frame chosen from above")
@@ -203,9 +211,11 @@ class StepHook(PollHook):
print("Alternatively, enter a test function name to stop at")
print(single_line_delim)
while True:
- print("Enter your choice, if any, and press ENTER to continue "
- "running the testcase...")
- choice = sys.stdin.readline().rstrip('\r\n')
+ print(
+ "Enter your choice, if any, and press ENTER to continue "
+ "running the testcase..."
+ )
+ choice = sys.stdin.readline().rstrip("\r\n")
if choice == "":
choice = None
try:
@@ -229,7 +239,7 @@ class StepHook(PollHook):
self.skip_num = num
def before_cli(self, cli):
- """ Wait for ENTER before executing CLI """
+ """Wait for ENTER before executing CLI"""
if self.skip():
print("Skip pause before executing CLI: %s" % cli)
else:
@@ -240,14 +250,12 @@ class StepHook(PollHook):
super(StepHook, self).before_cli(cli)
def before_api(self, api_name, api_args):
- """ Wait for ENTER before executing API """
+ """Wait for ENTER before executing API"""
if self.skip():
- print("Skip pause before executing API: %s (%s)"
- % (api_name, api_args))
+ print("Skip pause before executing API: %s (%s)" % (api_name, api_args))
else:
print(double_line_delim)
- print("Test paused before executing API: %s (%s)"
- % (api_name, api_args))
+ print("Test paused before executing API: %s (%s)" % (api_name, api_args))
print(single_line_delim)
self.user_input()
super(StepHook, self).before_api(api_name, api_args)
diff --git a/test/ipfix.py b/test/ipfix.py
index bac6dfd4c2a..bf833b36bbf 100644
--- a/test/ipfix.py
+++ b/test/ipfix.py
@@ -1,106 +1,114 @@
#!/usr/bin/env python3
# IPFIX support for Scapy (RFC7011)
-from scapy.all import bind_layers, FieldLenField, IntField, Packet, \
- PacketListField, ShortEnumField, ShortField, StrLenField
+from scapy.all import (
+ bind_layers,
+ FieldLenField,
+ IntField,
+ Packet,
+ PacketListField,
+ ShortEnumField,
+ ShortField,
+ StrLenField,
+)
from scapy.layers.inet import UDP
# IPFIX Information Elements http://www.iana.org/assignments/ipfix/ipfix.xhtml
information_elements = {
- 1: "octetDeltaCount",
- 2: "packetDeltaCount",
- 3: "deltaFlowCount",
- 4: "protocolIdentifier",
- 5: "ipClassOfService",
- 6: "tcpControlBits",
- 7: "sourceTransportPort",
- 8: "sourceIPv4Address",
- 9: "sourceIPv4PrefixLength",
- 10: "ingressInterface",
- 11: "destinationTransportPort",
- 12: "destinationIPv4Address",
- 13: "destinationIPv4PrefixLength",
- 14: "egressInterface",
- 15: "ipNextHopIPv4Address",
- 16: "bgpSourceAsNumber",
- 17: "bgpDestinationAsNumber",
- 18: "bgpNextHopIPv4Address",
- 19: "postMCastPacketDeltaCount",
- 20: "postMCastOctetDeltaCount",
- 21: "flowEndSysUpTime",
- 22: "flowStartSysUpTime",
- 23: "postOctetDeltaCount",
- 24: "postPacketDeltaCount",
- 25: "minimumIpTotalLength",
- 26: "maximumIpTotalLength",
- 27: "sourceIPv6Address",
- 28: "destinationIPv6Address",
- 29: "sourceIPv6PrefixLength",
- 30: "destinationIPv6PrefixLength",
- 31: "flowLabelIPv6",
- 32: "icmpTypeCodeIPv4",
- 33: "igmpType",
- 34: "samplingInterval",
- 35: "samplingAlgorithm",
- 36: "flowActiveTimeout",
- 37: "flowIdleTimeout",
- 38: "engineType",
- 39: "engineId",
- 40: "exportedOctetTotalCount",
- 41: "exportedMessageTotalCount",
- 42: "exportedFlowRecordTotalCount",
- 43: "ipv4RouterSc",
- 44: "sourceIPv4Prefix",
- 45: "destinationIPv4Prefix",
- 46: "mplsTopLabelType",
- 47: "mplsTopLabelIPv4Address",
- 48: "samplerId",
- 49: "samplerMode",
- 50: "samplerRandomInterval",
- 51: "classId",
- 52: "minimumTTL",
- 53: "maximumTTL",
- 54: "fragmentIdentification",
- 55: "postIpClassOfService",
- 56: "sourceMacAddress",
- 57: "postDestinationMacAddress",
- 58: "vlanId",
- 59: "postVlanId",
- 60: "ipVersion",
- 61: "flowDirection",
- 62: "ipNextHopIPv6Address",
- 63: "bgpNextHopIPv6Address",
- 64: "ipv6ExtensionHeaders",
- 70: "mplsTopLabelStackSection",
- 71: "mplsLabelStackSection2",
- 72: "mplsLabelStackSection3",
- 73: "mplsLabelStackSection4",
- 74: "mplsLabelStackSection5",
- 75: "mplsLabelStackSection6",
- 76: "mplsLabelStackSection7",
- 77: "mplsLabelStackSection8",
- 78: "mplsLabelStackSection9",
- 79: "mplsLabelStackSection10",
- 80: "destinationMacAddress",
- 81: "postSourceMacAddress",
- 82: "interfaceName",
- 83: "interfaceDescription",
- 84: "samplerName",
- 85: "octetTotalCount",
- 86: "packetTotalCount",
- 87: "flagsAndSamplerId",
- 88: "fragmentOffset",
- 89: "forwardingStatus",
- 90: "mplsVpnRouteDistinguisher",
- 91: "mplsTopLabelPrefixLength",
- 92: "srcTrafficIndex",
- 93: "dstTrafficIndex",
- 94: "applicationDescription",
- 95: "applicationId",
- 96: "applicationName",
- 98: "postIpDiffServCodePoint",
- 99: "multicastReplicationFactor",
+ 1: "octetDeltaCount",
+ 2: "packetDeltaCount",
+ 3: "deltaFlowCount",
+ 4: "protocolIdentifier",
+ 5: "ipClassOfService",
+ 6: "tcpControlBits",
+ 7: "sourceTransportPort",
+ 8: "sourceIPv4Address",
+ 9: "sourceIPv4PrefixLength",
+ 10: "ingressInterface",
+ 11: "destinationTransportPort",
+ 12: "destinationIPv4Address",
+ 13: "destinationIPv4PrefixLength",
+ 14: "egressInterface",
+ 15: "ipNextHopIPv4Address",
+ 16: "bgpSourceAsNumber",
+ 17: "bgpDestinationAsNumber",
+ 18: "bgpNextHopIPv4Address",
+ 19: "postMCastPacketDeltaCount",
+ 20: "postMCastOctetDeltaCount",
+ 21: "flowEndSysUpTime",
+ 22: "flowStartSysUpTime",
+ 23: "postOctetDeltaCount",
+ 24: "postPacketDeltaCount",
+ 25: "minimumIpTotalLength",
+ 26: "maximumIpTotalLength",
+ 27: "sourceIPv6Address",
+ 28: "destinationIPv6Address",
+ 29: "sourceIPv6PrefixLength",
+ 30: "destinationIPv6PrefixLength",
+ 31: "flowLabelIPv6",
+ 32: "icmpTypeCodeIPv4",
+ 33: "igmpType",
+ 34: "samplingInterval",
+ 35: "samplingAlgorithm",
+ 36: "flowActiveTimeout",
+ 37: "flowIdleTimeout",
+ 38: "engineType",
+ 39: "engineId",
+ 40: "exportedOctetTotalCount",
+ 41: "exportedMessageTotalCount",
+ 42: "exportedFlowRecordTotalCount",
+ 43: "ipv4RouterSc",
+ 44: "sourceIPv4Prefix",
+ 45: "destinationIPv4Prefix",
+ 46: "mplsTopLabelType",
+ 47: "mplsTopLabelIPv4Address",
+ 48: "samplerId",
+ 49: "samplerMode",
+ 50: "samplerRandomInterval",
+ 51: "classId",
+ 52: "minimumTTL",
+ 53: "maximumTTL",
+ 54: "fragmentIdentification",
+ 55: "postIpClassOfService",
+ 56: "sourceMacAddress",
+ 57: "postDestinationMacAddress",
+ 58: "vlanId",
+ 59: "postVlanId",
+ 60: "ipVersion",
+ 61: "flowDirection",
+ 62: "ipNextHopIPv6Address",
+ 63: "bgpNextHopIPv6Address",
+ 64: "ipv6ExtensionHeaders",
+ 70: "mplsTopLabelStackSection",
+ 71: "mplsLabelStackSection2",
+ 72: "mplsLabelStackSection3",
+ 73: "mplsLabelStackSection4",
+ 74: "mplsLabelStackSection5",
+ 75: "mplsLabelStackSection6",
+ 76: "mplsLabelStackSection7",
+ 77: "mplsLabelStackSection8",
+ 78: "mplsLabelStackSection9",
+ 79: "mplsLabelStackSection10",
+ 80: "destinationMacAddress",
+ 81: "postSourceMacAddress",
+ 82: "interfaceName",
+ 83: "interfaceDescription",
+ 84: "samplerName",
+ 85: "octetTotalCount",
+ 86: "packetTotalCount",
+ 87: "flagsAndSamplerId",
+ 88: "fragmentOffset",
+ 89: "forwardingStatus",
+ 90: "mplsVpnRouteDistinguisher",
+ 91: "mplsTopLabelPrefixLength",
+ 92: "srcTrafficIndex",
+ 93: "dstTrafficIndex",
+ 94: "applicationDescription",
+ 95: "applicationId",
+ 96: "applicationName",
+ 98: "postIpDiffServCodePoint",
+ 99: "multicastReplicationFactor",
100: "className",
101: "classificationEngineId",
102: "layer2packetSectionOffset",
@@ -443,24 +451,27 @@ information_elements = {
471: "maxSessionEntries",
472: "maxBIBEntries",
473: "maxEntriesPerUser",
- 475: "maxFragmentsPendingReassembly"
+ 475: "maxFragmentsPendingReassembly",
}
class IPFIX(Packet):
name = "IPFIX"
- fields_desc = [ShortField("version", 10),
- ShortField("length", None),
- IntField("exportTime", None),
- IntField("sequenceNumber", 1),
- IntField("observationDomainID", 1)]
+ fields_desc = [
+ ShortField("version", 10),
+ ShortField("length", None),
+ IntField("exportTime", None),
+ IntField("sequenceNumber", 1),
+ IntField("observationDomainID", 1),
+ ]
class FieldSpecifier(Packet):
name = "Field Specifier"
- fields_desc = [ShortEnumField(
- "informationElement", None, information_elements),
- ShortField("fieldLength", None)]
+ fields_desc = [
+ ShortEnumField("informationElement", None, information_elements),
+ ShortField("fieldLength", None),
+ ]
def extract_padding(self, s):
return "", s
@@ -468,16 +479,20 @@ class FieldSpecifier(Packet):
class Template(Packet):
name = "Template"
- fields_desc = [ShortField("templateID", 256),
- FieldLenField("fieldCount", None, count_of="fields"),
- PacketListField("templateFields", [], FieldSpecifier,
- count_from=lambda p: p.fieldCount)]
+ fields_desc = [
+ ShortField("templateID", 256),
+ FieldLenField("fieldCount", None, count_of="fields"),
+ PacketListField(
+ "templateFields", [], FieldSpecifier, count_from=lambda p: p.fieldCount
+ ),
+ ]
class Data(Packet):
name = "Data"
fields_desc = [
- StrLenField("data", "", length_from=lambda p: p.underlayer.length - 4)]
+ StrLenField("data", "", length_from=lambda p: p.underlayer.length - 4)
+ ]
def extract_padding(self, s):
return "", s
@@ -485,8 +500,7 @@ class Data(Packet):
class Set(Packet):
name = "Set"
- fields_desc = [ShortField("setID", 256),
- ShortField("length", None)]
+ fields_desc = [ShortField("setID", 256), ShortField("length", None)]
def guess_payload_class(self, payload):
if self.setID == 2:
@@ -502,7 +516,7 @@ bind_layers(UDP, IPFIX, dport=4739)
class IPFIXDecoder:
- """ IPFIX data set decoder """
+ """IPFIX data set decoder"""
def __init__(self):
self._templates = []
@@ -517,11 +531,9 @@ class IPFIXDecoder:
fields = []
rec_len = 0
for field in template.templateFields:
- fields.append(
- {'name': field.informationElement, 'len': field.fieldLength})
+ fields.append({"name": field.informationElement, "len": field.fieldLength})
rec_len += field.fieldLength
- self._templates.append(
- {'id': templateID, 'fields': fields, 'rec_len': rec_len})
+ self._templates.append({"id": templateID, "fields": fields, "rec_len": rec_len})
def decode_data_set(self, data_set):
"""
@@ -532,15 +544,15 @@ class IPFIXDecoder:
"""
data = []
for template in self._templates:
- if template['id'] == data_set.setID:
+ if template["id"] == data_set.setID:
offset = 0
d = data_set[Data].data
- for i in range(len(d) // template['rec_len']):
+ for i in range(len(d) // template["rec_len"]):
record = {}
- for field in template['fields']:
- f = d[offset:offset + field['len']]
- offset += field['len']
- record.update({field['name']: f})
+ for field in template["fields"]:
+ f = d[offset : offset + field["len"]]
+ offset += field["len"]
+ record.update({field["name"]: f})
data.append(record)
break
return data
diff --git a/test/lisp.py b/test/lisp.py
index bd5e1ab7c5f..9ebc86a35e3 100644
--- a/test/lisp.py
+++ b/test/lisp.py
@@ -5,7 +5,7 @@ from vpp_object import VppObject
class VppLispLocatorSet(VppObject):
- """ Represents LISP locator set in VPP """
+ """Represents LISP locator set in VPP"""
def __init__(self, test, ls_name):
self._test = test
@@ -26,7 +26,7 @@ class VppLispLocatorSet(VppObject):
def get_lisp_locator_sets_dump_entry(self):
result = self.test.vapi.lisp_locator_set_dump()
for ls in result:
- if ls.ls_name.strip('\x00') == self._ls_name:
+ if ls.ls_name.strip("\x00") == self._ls_name:
return ls
return None
@@ -34,15 +34,16 @@ class VppLispLocatorSet(VppObject):
return self.get_lisp_locator_sets_dump_entry() is not None
def remove_vpp_config(self):
- self.test.vapi.lisp_add_del_locator_set(locator_set_name=self._ls_name,
- is_add=0)
+ self.test.vapi.lisp_add_del_locator_set(
+ locator_set_name=self._ls_name, is_add=0
+ )
def object_id(self):
- return 'lisp-locator-set-%s' % self._ls_name
+ return "lisp-locator-set-%s" % self._ls_name
class VppLispLocator(VppObject):
- """ Represents LISP locator in VPP """
+ """Represents LISP locator in VPP"""
def __init__(self, test, sw_if_index, ls_name, priority=1, weight=1):
self._test = test
@@ -53,12 +54,12 @@ class VppLispLocator(VppObject):
@property
def test(self):
- """ Test which created this locator """
+ """Test which created this locator"""
return self._test
@property
def ls_name(self):
- """ Locator set name """
+ """Locator set name"""
return self._ls_name
@property
@@ -74,15 +75,18 @@ class VppLispLocator(VppObject):
return self._weight
def add_vpp_config(self):
- self.test.vapi.lisp_add_del_locator(locator_set_name=self._ls_name,
- sw_if_index=self._sw_if_index,
- priority=self._priority,
- weight=self._weight)
+ self.test.vapi.lisp_add_del_locator(
+ locator_set_name=self._ls_name,
+ sw_if_index=self._sw_if_index,
+ priority=self._priority,
+ weight=self._weight,
+ )
self._test.registry.register(self, self.test.logger)
def get_lisp_locator_dump_entry(self):
locators = self.test.vapi.lisp_locator_dump(
- is_index_set=0, ls_name=self._ls_name)
+ is_index_set=0, ls_name=self._ls_name
+ )
for locator in locators:
if locator.sw_if_index == self._sw_if_index:
return locator
@@ -94,12 +98,16 @@ class VppLispLocator(VppObject):
def remove_vpp_config(self):
self.test.vapi.lisp_add_del_locator(
- locator_set_name=self._ls_name, sw_if_index=self._sw_if_index,
- priority=self._priority, weight=self._weight, is_add=0)
+ locator_set_name=self._ls_name,
+ sw_if_index=self._sw_if_index,
+ priority=self._priority,
+ weight=self._weight,
+ is_add=0,
+ )
self._test.registry.register(self, self.test.logger)
def object_id(self):
- return 'lisp-locator-%s-%d' % (self._ls_name, self._sw_if_index)
+ return "lisp-locator-%s-%d" % (self._ls_name, self._sw_if_index)
class LispEIDType:
@@ -115,7 +123,8 @@ class LispKeyIdType:
class LispEID:
- """ Lisp endpoint identifier """
+ """Lisp endpoint identifier"""
+
def __init__(self, eid):
self.eid = eid
self._type = -1
@@ -130,7 +139,7 @@ class LispEID:
self.mac = self.eid
self._type = LispEIDType.MAC
return
- raise Exception('Unsupported EID format {!s}!'.format(eid))
+ raise Exception("Unsupported EID format {!s}!".format(eid))
@property
def eid_type(self):
@@ -143,7 +152,7 @@ class LispEID:
elif self.eid_type == LispEIDType.MAC:
return self.mac
elif self.eid_type == LispEIDType.NSH:
- return Exception('Unimplemented')
+ return Exception("Unimplemented")
@property
def packed(self):
@@ -152,11 +161,12 @@ class LispEID:
elif self.eid_type == LispEIDType.MAC:
return {"type": self._type, "address": {"mac": self.mac}}
elif self.eid_type == LispEIDType.NSH:
- return Exception('Unimplemented')
+ return Exception("Unimplemented")
class LispKey:
- """ Lisp Key """
+ """Lisp Key"""
+
def __init__(self, key_type, key):
self._key_type = key_type
self._key = key
@@ -167,7 +177,7 @@ class LispKey:
class VppLispMapping(VppObject):
- """ Represents common features for remote and local LISP mapping in VPP """
+ """Represents common features for remote and local LISP mapping in VPP"""
def __init__(self, test, eid, vni=0, priority=1, weight=1):
self._eid = LispEID(eid)
@@ -198,21 +208,36 @@ class VppLispMapping(VppObject):
def get_lisp_mapping_dump_entry(self):
return self.test.vapi.lisp_eid_table_dump(
- eid_set=1, vni=self._vni, eid=self._eid.packed)
+ eid_set=1, vni=self._vni, eid=self._eid.packed
+ )
def query_vpp_config(self):
mapping = self.get_lisp_mapping_dump_entry()
return mapping
def object_id(self):
- return 'lisp-mapping-[%s]-%s-%s-%s' % (
- self.vni, self.eid.address, self.priority, self.weight)
+ return "lisp-mapping-[%s]-%s-%s-%s" % (
+ self.vni,
+ self.eid.address,
+ self.priority,
+ self.weight,
+ )
class VppLocalMapping(VppLispMapping):
- """ LISP Local mapping """
- def __init__(self, test, eid, ls_name, vni=0, priority=1, weight=1,
- key_id=LispKeyIdType.NONE, key=''):
+ """LISP Local mapping"""
+
+ def __init__(
+ self,
+ test,
+ eid,
+ ls_name,
+ vni=0,
+ priority=1,
+ weight=1,
+ key_id=LispKeyIdType.NONE,
+ key="",
+ ):
super(VppLocalMapping, self).__init__(test, eid, vni, priority, weight)
self._ls_name = ls_name
self._key = LispKey(key_id, key)
@@ -231,17 +256,23 @@ class VppLocalMapping(VppLispMapping):
def add_vpp_config(self):
self.test.vapi.lisp_add_del_local_eid(
- locator_set_name=self._ls_name, eid=self._eid.packed,
- vni=self._vni, key=self._key.packed)
+ locator_set_name=self._ls_name,
+ eid=self._eid.packed,
+ vni=self._vni,
+ key=self._key.packed,
+ )
self._test.registry.register(self, self.test.logger)
def remove_vpp_config(self):
self.test.vapi.lisp_add_del_local_eid(
- locator_set_name=self._ls_name, eid=self._eid.packed,
- vni=self._vni, is_add=0)
+ locator_set_name=self._ls_name,
+ eid=self._eid.packed,
+ vni=self._vni,
+ is_add=0,
+ )
def object_id(self):
- return 'lisp-eid-local-mapping-%s[%d]' % (self._eid.address, self._vni)
+ return "lisp-eid-local-mapping-%s[%d]" % (self._eid.address, self._vni)
class LispRemoteLocator:
@@ -252,15 +283,16 @@ class LispRemoteLocator:
@property
def packed(self):
- return {"priority": self.priority, "weight": self.weight,
- "ip_address": self.addr}
+ return {
+ "priority": self.priority,
+ "weight": self.weight,
+ "ip_address": self.addr,
+ }
class VppRemoteMapping(VppLispMapping):
-
def __init__(self, test, eid, rlocs=None, vni=0, priority=1, weight=1):
- super(VppRemoteMapping, self).__init__(test, eid, vni, priority,
- weight)
+ super(VppRemoteMapping, self).__init__(test, eid, vni, priority, weight)
self._rlocs = rlocs
@property
@@ -272,27 +304,30 @@ class VppRemoteMapping(VppLispMapping):
def add_vpp_config(self):
self.test.vapi.lisp_add_del_remote_mapping(
- rlocs=self.rlocs, deid=self._eid.packed,
- vni=self._vni, rloc_num=len(self._rlocs))
+ rlocs=self.rlocs,
+ deid=self._eid.packed,
+ vni=self._vni,
+ rloc_num=len(self._rlocs),
+ )
self._test.registry.register(self, self.test.logger)
def remove_vpp_config(self):
self.test.vapi.lisp_add_del_remote_mapping(
- deid=self._eid.packed, vni=self._vni, is_add=0, rloc_num=0)
+ deid=self._eid.packed, vni=self._vni, is_add=0, rloc_num=0
+ )
def object_id(self):
- return 'lisp-eid-remote-mapping-%s[%d]' % (self._eid.address,
- self._vni)
+ return "lisp-eid-remote-mapping-%s[%d]" % (self._eid.address, self._vni)
class VppLispAdjacency(VppObject):
- """ Represents LISP adjacency in VPP """
+ """Represents LISP adjacency in VPP"""
def __init__(self, test, leid, reid, vni=0):
self._leid = LispEID(leid)
self._reid = LispEID(reid)
if self._leid.eid_type != self._reid.eid_type:
- raise Exception('remote and local EID are different types!')
+ raise Exception("remote and local EID are different types!")
self._vni = vni
self._test = test
@@ -314,7 +349,8 @@ class VppLispAdjacency(VppObject):
def add_vpp_config(self):
self.test.vapi.lisp_add_del_adjacency(
- leid=self._leid.packed, reid=self._reid.packed, vni=self._vni)
+ leid=self._leid.packed, reid=self._reid.packed, vni=self._vni
+ )
self._test.registry.register(self, self.test.logger)
@staticmethod
@@ -334,15 +370,16 @@ class VppLispAdjacency(VppObject):
def query_vpp_config(self):
res = self.test.vapi.lisp_adjacencies_get(vni=self._vni)
for adj in res.adjacencies:
- if self.eid_equal(self._leid, adj.leid) and \
- self.eid_equal(self._reid, adj.reid):
+ if self.eid_equal(self._leid, adj.leid) and self.eid_equal(
+ self._reid, adj.reid
+ ):
return True
return False
def remove_vpp_config(self):
self.test.vapi.lisp_add_del_adjacency(
- leid=self._leid.packed, reid=self._reid.packed,
- vni=self._vni, is_add=0)
+ leid=self._leid.packed, reid=self._reid.packed, vni=self._vni, is_add=0
+ )
def object_id(self):
- return 'lisp-adjacency-%s-%s[%d]' % (self._leid, self._reid, self._vni)
+ return "lisp-adjacency-%s-%s[%d]" % (self._leid, self._reid, self._vni)
diff --git a/test/log.py b/test/log.py
index 9701aecc04a..f848e221044 100644
--- a/test/log.py
+++ b/test/log.py
@@ -7,9 +7,9 @@ import logging
from config import config
""" @var formatting delimiter consisting of '=' characters """
-double_line_delim = '=' * 78
+double_line_delim = "=" * 78
""" @var formatting delimiter consisting of '-' characters """
-single_line_delim = '-' * 78
+single_line_delim = "-" * 78
def colorize(msg, color):
@@ -17,13 +17,12 @@ def colorize(msg, color):
class ColorFormatter(logging.Formatter):
-
def init(self, fmt=None, datefmt=None):
super(ColorFormatter, self).__init__(fmt, datefmt)
def format(self, record):
message = super(ColorFormatter, self).format(record)
- if hasattr(record, 'color'):
+ if hasattr(record, "color"):
message = colorize(message, record.color)
return message
@@ -37,8 +36,9 @@ else:
log_level = 40
handler = logging.StreamHandler(sys.stdout)
-color_formatter = ColorFormatter(fmt='%(asctime)s,%(msecs)03d %(message)s',
- datefmt="%H:%M:%S")
+color_formatter = ColorFormatter(
+ fmt="%(asctime)s,%(msecs)03d %(message)s", datefmt="%H:%M:%S"
+)
handler.setFormatter(color_formatter)
handler.setLevel(log_level)
@@ -56,7 +56,7 @@ def get_logger(name):
def get_parallel_logger(stream):
- logger = logging.getLogger('parallel_logger_{!s}'.format(stream))
+ logger = logging.getLogger("parallel_logger_{!s}".format(stream))
logger.propagate = False
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(stream)
@@ -71,15 +71,15 @@ def get_parallel_logger(stream):
# These variables (RED, GREEN, YELLOW and LPURPLE) are used to configure
# the color of the text to be printed in the terminal. Variable COLOR_RESET
# is used to revert the text color to the default one.
-if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
- RED = '\033[91m'
- GREEN = '\033[92m'
- YELLOW = '\033[93m'
- LPURPLE = '\033[94m'
- COLOR_RESET = '\033[0m'
+if hasattr(sys.stdout, "isatty") and sys.stdout.isatty():
+ RED = "\033[91m"
+ GREEN = "\033[92m"
+ YELLOW = "\033[93m"
+ LPURPLE = "\033[94m"
+ COLOR_RESET = "\033[0m"
else:
- RED = ''
- GREEN = ''
- YELLOW = ''
- LPURPLE = ''
- COLOR_RESET = ''
+ RED = ""
+ GREEN = ""
+ YELLOW = ""
+ LPURPLE = ""
+ COLOR_RESET = ""
diff --git a/test/remote_test.py b/test/remote_test.py
index 19bad897cdf..707d61fa9e5 100644
--- a/test/remote_test.py
+++ b/test/remote_test.py
@@ -16,10 +16,11 @@ class SerializableClassCopy:
"""
Empty class used as a basis for a serializable copy of another class.
"""
+
pass
def __repr__(self):
- return '<SerializableClassCopy dict=%s>' % self.__dict__
+ return "<SerializableClassCopy dict=%s>" % self.__dict__
class RemoteClassAttr:
@@ -32,7 +33,7 @@ class RemoteClassAttr:
self._remote = remote
def path_to_str(self):
- return '.'.join(self._path)
+ return ".".join(self._path)
def get_remote_value(self):
return self._remote._remote_exec(RemoteClass.GET, self.path_to_str())
@@ -44,25 +45,24 @@ class RemoteClassAttr:
return self._remote._remote_exec(RemoteClass.STR, self.path_to_str())
def __getattr__(self, attr):
- if attr[0] == '_':
- if not (attr.startswith('__') and attr.endswith('__')):
- raise AttributeError('tried to get private attribute: %s ',
- attr)
+ if attr[0] == "_":
+ if not (attr.startswith("__") and attr.endswith("__")):
+ raise AttributeError("tried to get private attribute: %s ", attr)
self._path.append(attr)
return self
def __setattr__(self, attr, val):
- if attr[0] == '_':
- if not (attr.startswith('__') and attr.endswith('__')):
+ if attr[0] == "_":
+ if not (attr.startswith("__") and attr.endswith("__")):
super(RemoteClassAttr, self).__setattr__(attr, val)
return
self._path.append(attr)
- self._remote._remote_exec(RemoteClass.SETATTR, self.path_to_str(),
- value=val)
+ self._remote._remote_exec(RemoteClass.SETATTR, self.path_to_str(), value=val)
def __call__(self, *args, **kwargs):
- return self._remote._remote_exec(RemoteClass.CALL, self.path_to_str(),
- *args, **kwargs)
+ return self._remote._remote_exec(
+ RemoteClass.CALL, self.path_to_str(), *args, **kwargs
+ )
class RemoteClass(Process):
@@ -98,12 +98,12 @@ class RemoteClass(Process):
object.terminate()
"""
- GET = 0 # Get attribute remotely
- CALL = 1 # Call method remotely
- SETATTR = 2 # Set attribute remotely
- REPR = 3 # Get representation of a remote object
- STR = 4 # Get string representation of a remote object
- QUIT = 5 # Quit remote execution
+ GET = 0 # Get attribute remotely
+ CALL = 1 # Call method remotely
+ SETATTR = 2 # Set attribute remotely
+ REPR = 3 # Get representation of a remote object
+ STR = 4 # Get string representation of a remote object
+ QUIT = 5 # Quit remote execution
PIPE_PARENT = 0 # Parent end of the pipe
PIPE_CHILD = 1 # Child end of the pipe
@@ -128,16 +128,16 @@ class RemoteClass(Process):
return self.RemoteClassAttr(self, None)()
def __getattr__(self, attr):
- if attr[0] == '_' or not self.is_alive():
- if not (attr.startswith('__') and attr.endswith('__')):
- if hasattr(super(RemoteClass, self), '__getattr__'):
+ if attr[0] == "_" or not self.is_alive():
+ if not (attr.startswith("__") and attr.endswith("__")):
+ if hasattr(super(RemoteClass, self), "__getattr__"):
return super(RemoteClass, self).__getattr__(attr)
- raise AttributeError('missing: %s', attr)
+ raise AttributeError("missing: %s", attr)
return RemoteClassAttr(self, attr)
def __setattr__(self, attr, val):
- if attr[0] == '_' or not self.is_alive():
- if not (attr.startswith('__') and attr.endswith('__')):
+ if attr[0] == "_" or not self.is_alive():
+ if not (attr.startswith("__") and attr.endswith("__")):
super(RemoteClass, self).__setattr__(attr, val)
return
setattr(RemoteClassAttr(self, None), attr, val)
@@ -149,13 +149,11 @@ class RemoteClass(Process):
# automatically resolve remote objects in the arguments
mutable_args = list(args)
for i, val in enumerate(mutable_args):
- if isinstance(val, RemoteClass) or \
- isinstance(val, RemoteClassAttr):
+ if isinstance(val, RemoteClass) or isinstance(val, RemoteClassAttr):
mutable_args[i] = val.get_remote_value()
args = tuple(mutable_args)
for key, val in kwargs.items():
- if isinstance(val, RemoteClass) or \
- isinstance(val, RemoteClassAttr):
+ if isinstance(val, RemoteClass) or isinstance(val, RemoteClassAttr):
kwargs[key] = val.get_remote_value()
# send request
args = self._make_serializable(args)
@@ -163,11 +161,11 @@ class RemoteClass(Process):
self._pipe[RemoteClass.PIPE_PARENT].send((op, path, args, kwargs))
timeout = self._timeout
# adjust timeout specifically for the .sleep method
- if path is not None and path.split('.')[-1] == 'sleep':
+ if path is not None and path.split(".")[-1] == "sleep":
if args and isinstance(args[0], (long, int)):
timeout += args[0]
- elif 'timeout' in kwargs:
- timeout += kwargs['timeout']
+ elif "timeout" in kwargs:
+ timeout += kwargs["timeout"]
if not self._pipe[RemoteClass.PIPE_PARENT].poll(timeout):
return None
try:
@@ -222,7 +220,7 @@ class RemoteClass(Process):
return None
def _serializable(self, obj):
- """ Test if the given object is serializable """
+ """Test if the given object is serializable"""
try:
dumps(obj)
return True
@@ -243,7 +241,7 @@ class RemoteClass(Process):
Dictionaries can hold complex values, so we split keys and values into
separate lists and serialize them individually.
"""
- if (type(obj) is dict):
+ if type(obj) is dict:
copy.type = type(obj)
copy.k_list = list()
copy.v_list = list()
@@ -255,12 +253,12 @@ class RemoteClass(Process):
# copy at least serializable attributes and properties
for name, member in inspect.getmembers(obj):
# skip private members and non-writable dunder methods.
- if name[0] == '_':
- if name in ['__weakref__']:
+ if name[0] == "_":
+ if name in ["__weakref__"]:
continue
- if name in ['__dict__']:
+ if name in ["__dict__"]:
continue
- if not (name.startswith('__') and name.endswith('__')):
+ if not (name.startswith("__") and name.endswith("__")):
continue
if callable(member) and not isinstance(member, property):
continue
@@ -281,13 +279,13 @@ class RemoteClass(Process):
if type(obj) is tuple:
rv = tuple(rv)
return rv
- elif (isinstance(obj, IntEnum) or isinstance(obj, IntFlag)):
+ elif isinstance(obj, IntEnum) or isinstance(obj, IntFlag):
return obj.value
else:
return self._make_obj_serializable(obj)
def _deserialize_obj(self, obj):
- if (hasattr(obj, 'type')):
+ if hasattr(obj, "type"):
if obj.type is dict:
_obj = dict()
for k, v in zip(obj.k_list, obj.v_list):
@@ -307,19 +305,19 @@ class RemoteClass(Process):
return self._deserialize_obj(obj)
def start_remote(self):
- """ Start remote execution """
+ """Start remote execution"""
self.start()
def quit_remote(self):
- """ Quit remote execution """
+ """Quit remote execution"""
self._remote_exec(RemoteClass.QUIT, None)
def get_remote_value(self):
- """ Get value of a remotely held object """
+ """Get value of a remotely held object"""
return RemoteClassAttr(self, None).get_remote_value()
def set_request_timeout(self, timeout):
- """ Change request timeout """
+ """Change request timeout"""
self._timeout = timeout
def run(self):
@@ -332,17 +330,16 @@ class RemoteClass(Process):
try:
rv = None
# get request from the parent process
- (op, path, args,
- kwargs) = self._pipe[RemoteClass.PIPE_CHILD].recv()
+ (op, path, args, kwargs) = self._pipe[RemoteClass.PIPE_CHILD].recv()
args = self._deserialize(args)
kwargs = self._deserialize(kwargs)
- path = path.split('.') if path else []
+ path = path.split(".") if path else []
if op == RemoteClass.GET:
rv = self._get_local_value(path)
elif op == RemoteClass.CALL:
rv = self._call_local_method(path, *args, **kwargs)
- elif op == RemoteClass.SETATTR and 'value' in kwargs:
- self._set_local_attr(path, kwargs['value'])
+ elif op == RemoteClass.SETATTR and "value" in kwargs:
+ self._set_local_attr(path, kwargs["value"])
elif op == RemoteClass.REPR:
rv = self._get_local_repr(path)
elif op == RemoteClass.STR:
@@ -362,34 +359,34 @@ class RemoteClass(Process):
@unittest.skip("Remote Vpp Test Case Class")
class RemoteVppTestCase(VppTestCase):
- """ Re-use VppTestCase to create remote VPP segment
+ """Re-use VppTestCase to create remote VPP segment
- In your test case::
+ In your test case::
- @classmethod
- def setUpClass(cls):
- # fork new process before client connects to VPP
- cls.remote_test = RemoteClass(RemoteVppTestCase)
+ @classmethod
+ def setUpClass(cls):
+ # fork new process before client connects to VPP
+ cls.remote_test = RemoteClass(RemoteVppTestCase)
- # start remote process
- cls.remote_test.start_remote()
+ # start remote process
+ cls.remote_test.start_remote()
- # set up your test case
- super(MyTestCase, cls).setUpClass()
+ # set up your test case
+ super(MyTestCase, cls).setUpClass()
- # set up remote test
- cls.remote_test.setUpClass(cls.tempdir)
+ # set up remote test
+ cls.remote_test.setUpClass(cls.tempdir)
- @classmethod
- def tearDownClass(cls):
- # tear down remote test
- cls.remote_test.tearDownClass()
+ @classmethod
+ def tearDownClass(cls):
+ # tear down remote test
+ cls.remote_test.tearDownClass()
- # stop remote process
- cls.remote_test.quit_remote()
+ # stop remote process
+ cls.remote_test.quit_remote()
- # tear down your test case
- super(MyTestCase, cls).tearDownClass()
+ # tear down your test case
+ super(MyTestCase, cls).tearDownClass()
"""
def __init__(self):
@@ -408,10 +405,10 @@ class RemoteVppTestCase(VppTestCase):
def setUpClass(cls, tempdir):
# disable features unsupported in remote VPP
orig_env = dict(os.environ)
- if 'STEP' in os.environ:
- del os.environ['STEP']
- if 'DEBUG' in os.environ:
- del os.environ['DEBUG']
+ if "STEP" in os.environ:
+ del os.environ["STEP"]
+ if "DEBUG" in os.environ:
+ del os.environ["DEBUG"]
cls.tempdir_prefix = os.path.basename(tempdir) + "/"
super(RemoteVppTestCase, cls).setUpClass()
os.environ = orig_env
@@ -422,7 +419,7 @@ class RemoteVppTestCase(VppTestCase):
@unittest.skip("Empty test")
def emptyTest(self):
- """ Do nothing """
+ """Do nothing"""
pass
def setTestFunctionInfo(self, name, doc):
diff --git a/test/requirements-3.txt b/test/requirements-3.txt
index 0ccdec7fa5c..2e8f17df0c5 100644
--- a/test/requirements-3.txt
+++ b/test/requirements-3.txt
@@ -1,5 +1,5 @@
#
-# This file is autogenerated by pip-compile with python 3.8
+# This file is autogenerated by pip-compile with python 3.7
# To update, run:
#
# make test-refresh-deps (or update requirements.txt)
@@ -12,10 +12,35 @@ attrs==21.4.0 \
--hash=sha256:2d27e3784d7a565d36ab851fe94887c5eccd6a463168875832a1be79c82828b4 \
--hash=sha256:626ba8234211db98e869df76230a137c4c40a12d72445c45d5f5b716f076e2fd
# via jsonschema
-babel==2.9.1 \
- --hash=sha256:ab49e12b91d937cd11f0b67cb259a57ab4ad2b59ac7a3b41d6c06c0ac5b0def9 \
- --hash=sha256:bc0c176f9f6a994582230df350aa6e05ba2ebe4b3ac317eab29d9be5d2768da0
+babel==2.10.1 \
+ --hash=sha256:3f349e85ad3154559ac4930c3918247d319f21910d5ce4b25d439ed8693b98d2 \
+ --hash=sha256:98aeaca086133efb3e1e2aad0396987490c8425929ddbcfe0550184fdc54cd13
# via sphinx
+black==22.3.0 \
+ --hash=sha256:06f9d8846f2340dfac80ceb20200ea5d1b3f181dd0556b47af4e8e0b24fa0a6b \
+ --hash=sha256:10dbe6e6d2988049b4655b2b739f98785a884d4d6b85bc35133a8fb9a2233176 \
+ --hash=sha256:2497f9c2386572e28921fa8bec7be3e51de6801f7459dffd6e62492531c47e09 \
+ --hash=sha256:30d78ba6bf080eeaf0b7b875d924b15cd46fec5fd044ddfbad38c8ea9171043a \
+ --hash=sha256:328efc0cc70ccb23429d6be184a15ce613f676bdfc85e5fe8ea2a9354b4e9015 \
+ --hash=sha256:35020b8886c022ced9282b51b5a875b6d1ab0c387b31a065b84db7c33085ca79 \
+ --hash=sha256:5795a0375eb87bfe902e80e0c8cfaedf8af4d49694d69161e5bd3206c18618bb \
+ --hash=sha256:5891ef8abc06576985de8fa88e95ab70641de6c1fca97e2a15820a9b69e51b20 \
+ --hash=sha256:637a4014c63fbf42a692d22b55d8ad6968a946b4a6ebc385c5505d9625b6a464 \
+ --hash=sha256:67c8301ec94e3bcc8906740fe071391bce40a862b7be0b86fb5382beefecd968 \
+ --hash=sha256:6d2fc92002d44746d3e7db7cf9313cf4452f43e9ea77a2c939defce3b10b5c82 \
+ --hash=sha256:6ee227b696ca60dd1c507be80a6bc849a5a6ab57ac7352aad1ffec9e8b805f21 \
+ --hash=sha256:863714200ada56cbc366dc9ae5291ceb936573155f8bf8e9de92aef51f3ad0f0 \
+ --hash=sha256:9b542ced1ec0ceeff5b37d69838106a6348e60db7b8fdd245294dc1d26136265 \
+ --hash=sha256:a6342964b43a99dbc72f72812bf88cad8f0217ae9acb47c0d4f141a6416d2d7b \
+ --hash=sha256:ad4efa5fad66b903b4a5f96d91461d90b9507a812b3c5de657d544215bb7877a \
+ --hash=sha256:bc58025940a896d7e5356952228b68f793cf5fcb342be703c3a2669a1488cb72 \
+ --hash=sha256:cc1e1de68c8e5444e8f94c3670bb48a2beef0e91dddfd4fcc29595ebd90bb9ce \
+ --hash=sha256:cee3e11161dde1b2a33a904b850b0899e0424cc331b7295f2a9698e79f9a69a0 \
+ --hash=sha256:e3556168e2e5c49629f7b0f377070240bd5511e45e25a4497bb0073d9dda776a \
+ --hash=sha256:e8477ec6bbfe0312c128e74644ac8a02ca06bcdb8982d4ee06f209be28cdf163 \
+ --hash=sha256:ee8f1f7228cce7dffc2b464f07ce769f478968bfb3dd1254a4c2eeed84928aad \
+ --hash=sha256:fd57160949179ec517d32ac2ac898b5f20d68ed1a9c977346efbac9c2f1e779d
+ # via -r requirements.txt
certifi==2021.10.8 \
--hash=sha256:78884e7c1d4b00ce3cea67b44566851c4343c120abd683433ce934a68ea58872 \
--hash=sha256:d62a0163eb4c2344ac042ab2bdf75399a71a2d8c7d47eac2e2ee91b9d6339569
@@ -72,39 +97,43 @@ cffi==1.15.0 \
--hash=sha256:fd8a250edc26254fe5b33be00402e6d287f562b6a5b2152dec302fa15bb3e997 \
--hash=sha256:ffaa5c925128e29efbde7301d8ecaf35c8c60ffbcd6a1ffd3a552177c8e5e796
# via cryptography
-charset-normalizer==2.0.11 \
- --hash=sha256:2842d8f5e82a1f6aa437380934d5e1cd4fcf2003b06fed6940769c164a480a45 \
- --hash=sha256:98398a9d69ee80548c762ba991a4728bfc3836768ed226b3945908d1a688371c
+charset-normalizer==2.0.12 \
+ --hash=sha256:2857e29ff0d34db842cd7ca3230549d1a697f96ee6d3fb071cfa6c7393832597 \
+ --hash=sha256:6881edbebdb17b39b4eaaa821b438bf6eddffb4468cf344f09f89def34a8b1df
# via requests
-click==8.0.3 \
- --hash=sha256:353f466495adaeb40b6b5f592f9f91cb22372351c84caeb068132442a4518ef3 \
- --hash=sha256:410e932b050f5eed773c4cda94de75971c89cdb3155a72a0831139a79e5ecb5b
- # via pip-tools
+click==8.1.3 \
+ --hash=sha256:7682dc8afb30297001674575ea00d1814d808d6a36af415a82bd481d37ba7b8e \
+ --hash=sha256:bb4d8133cb15a609f44e8213d9b391b0809795062913b383c62be0ee95b1db48
+ # via
+ # black
+ # pip-tools
commonmark==0.9.1 \
--hash=sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60 \
--hash=sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9
# via recommonmark
-cryptography==36.0.1 \
- --hash=sha256:0a817b961b46894c5ca8a66b599c745b9a3d9f822725221f0e0fe49dc043a3a3 \
- --hash=sha256:2d87cdcb378d3cfed944dac30596da1968f88fb96d7fc34fdae30a99054b2e31 \
- --hash=sha256:30ee1eb3ebe1644d1c3f183d115a8c04e4e603ed6ce8e394ed39eea4a98469ac \
- --hash=sha256:391432971a66cfaf94b21c24ab465a4cc3e8bf4a939c1ca5c3e3a6e0abebdbcf \
- --hash=sha256:39bdf8e70eee6b1c7b289ec6e5d84d49a6bfa11f8b8646b5b3dfe41219153316 \
- --hash=sha256:4caa4b893d8fad33cf1964d3e51842cd78ba87401ab1d2e44556826df849a8ca \
- --hash=sha256:53e5c1dc3d7a953de055d77bef2ff607ceef7a2aac0353b5d630ab67f7423638 \
- --hash=sha256:596f3cd67e1b950bc372c33f1a28a0692080625592ea6392987dba7f09f17a94 \
- --hash=sha256:5d59a9d55027a8b88fd9fd2826c4392bd487d74bf628bb9d39beecc62a644c12 \
- --hash=sha256:6c0c021f35b421ebf5976abf2daacc47e235f8b6082d3396a2fe3ccd537ab173 \
- --hash=sha256:73bc2d3f2444bcfeac67dd130ff2ea598ea5f20b40e36d19821b4df8c9c5037b \
- --hash=sha256:74d6c7e80609c0f4c2434b97b80c7f8fdfaa072ca4baab7e239a15d6d70ed73a \
- --hash=sha256:7be0eec337359c155df191d6ae00a5e8bbb63933883f4f5dffc439dac5348c3f \
- --hash=sha256:94ae132f0e40fe48f310bba63f477f14a43116f05ddb69d6fa31e93f05848ae2 \
- --hash=sha256:bb5829d027ff82aa872d76158919045a7c1e91fbf241aec32cb07956e9ebd3c9 \
- --hash=sha256:ca238ceb7ba0bdf6ce88c1b74a87bffcee5afbfa1e41e173b1ceb095b39add46 \
- --hash=sha256:ca28641954f767f9822c24e927ad894d45d5a1e501767599647259cbf030b903 \
- --hash=sha256:e0344c14c9cb89e76eb6a060e67980c9e35b3f36691e15e1b7a9e58a0a6c6dc3 \
- --hash=sha256:ebc15b1c22e55c4d5566e3ca4db8689470a0ca2babef8e3a9ee057a8b82ce4b1 \
- --hash=sha256:ec63da4e7e4a5f924b90af42eddf20b698a70e58d86a72d943857c4c6045b3ee
+cryptography==37.0.1 \
+ --hash=sha256:06bfafa6e53ccbfb7a94be4687b211a025ce0625e3f3c60bb15cd048a18f3ed8 \
+ --hash=sha256:0db5cf21bd7d092baacb576482b0245102cea2d3cf09f09271ce9f69624ecb6f \
+ --hash=sha256:125702572be12bcd318e3a14e9e70acd4be69a43664a75f0397e8650fe3c6cc3 \
+ --hash=sha256:1858eff6246bb8bbc080eee78f3dd1528739e3f416cba5f9914e8631b8df9871 \
+ --hash=sha256:315af6268de72bcfa0bb3401350ce7d921f216e6b60de12a363dad128d9d459f \
+ --hash=sha256:451aaff8b8adf2dd0597cbb1fdcfc8a7d580f33f843b7cce75307a7f20112dd8 \
+ --hash=sha256:58021d6e9b1d88b1105269d0da5e60e778b37dfc0e824efc71343dd003726831 \
+ --hash=sha256:618391152147a1221c87b1b0b7f792cafcfd4b5a685c5c72eeea2ddd29aeceff \
+ --hash=sha256:6d4daf890e674d191757d8d7d60dc3a29c58c72c7a76a05f1c0a326013f47e8b \
+ --hash=sha256:74b55f67f4cf026cb84da7a1b04fc2a1d260193d4ad0ea5e9897c8b74c1e76ac \
+ --hash=sha256:7ceae26f876aabe193b13a0c36d1bb8e3e7e608d17351861b437bd882f617e9f \
+ --hash=sha256:930b829e8a2abaf43a19f38277ae3c5e1ffcf547b936a927d2587769ae52c296 \
+ --hash=sha256:a18ff4bfa9d64914a84d7b06c46eb86e0cc03113470b3c111255aceb6dcaf81d \
+ --hash=sha256:ae1cd29fbe6b716855454e44f4bf743465152e15d2d317303fe3b58ee9e5af7a \
+ --hash=sha256:b1ee5c82cf03b30f6ae4e32d2bcb1e167ef74d6071cbb77c2af30f101d0b360b \
+ --hash=sha256:bf585476fcbcd37bed08072e8e2db3954ce1bfc68087a2dc9c19cfe0b90979ca \
+ --hash=sha256:c4a58eeafbd7409054be41a377e726a7904a17c26f45abf18125d21b1215b08b \
+ --hash=sha256:cce90609e01e1b192fae9e13665058ab46b2ea53a3c05a3ea74a3eb8c3af8857 \
+ --hash=sha256:d610d0ee14dd9109006215c7c0de15eee91230b70a9bce2263461cf7c3720b83 \
+ --hash=sha256:e69a0e36e62279120e648e787b76d79b41e0f9e86c1c636a4f38d415595c722e \
+ --hash=sha256:f095988548ec5095e3750cdb30e6962273d239b1998ba1aac66c0d5bee7111c1 \
+ --hash=sha256:faf0f5456c059c7b1c29441bdd5e988f0ba75bdc3eea776520d8dcb1e30e1b5c
# via
# -r requirements.txt
# noiseprotocol
@@ -119,9 +148,9 @@ docutils==0.17.1 \
# recommonmark
# sphinx
# sphinx-rtd-theme
-graphviz==0.19.1 \
- --hash=sha256:09ed0cde452d015fe77c4845a210eb642f28d245f5bc250d4b97808cb8f49078 \
- --hash=sha256:f34088c08be2ec16279dfa9c3b4ff3d1453c5c67597a33e2819b000e18d4c546
+graphviz==0.20 \
+ --hash=sha256:62c5f48bcc534a45b4588c548ff75e419c1f1f3a33d31a91796ae80a7f581e4a \
+ --hash=sha256:76bdfb73f42e72564ffe9c7299482f9d72f8e6cb8d54bce7b48ab323755e9ba5
# via objgraph
idna==3.3 \
--hash=sha256:84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff \
@@ -131,17 +160,22 @@ imagesize==1.3.0 \
--hash=sha256:1db2f82529e53c3e929e8926a1fa9235aa82d0bd0c580359c67ec31b2fddaa8c \
--hash=sha256:cd1750d452385ca327479d45b64d9c7729ecf0b3969a58148298c77092261f9d
# via sphinx
-importlib-metadata==4.10.1 \
- --hash=sha256:899e2a40a8c4a1aec681feef45733de8a6c58f3f6a0dbed2eb6574b4387a77b6 \
- --hash=sha256:951f0d8a5b7260e9db5e41d429285b5f451e928479f19d80818878527d36e95e
- # via sphinx
-importlib-resources==5.4.0 \
- --hash=sha256:33a95faed5fc19b4bc16b29a6eeae248a3fe69dd55d4d229d2b480e23eeaad45 \
- --hash=sha256:d756e2f85dd4de2ba89be0b21dba2a3bbec2e871a42a3a16719258a11f87506b
+importlib-metadata==4.11.3 \
+ --hash=sha256:1208431ca90a8cca1a6b8af391bb53c1a2db74e5d1cef6ddced95d4b2062edc6 \
+ --hash=sha256:ea4c597ebf37142f827b8f39299579e31685c31d3a438b59f469406afd0f2539
+ # via
+ # click
+ # jsonschema
+ # pep517
+ # sphinx
+ # sphinxcontrib-spelling
+importlib-resources==5.7.1 \
+ --hash=sha256:b6062987dfc51f0fcb809187cffbd60f35df7acb4589091f154214af6d0d49d3 \
+ --hash=sha256:e447dc01619b1e951286f3929be820029d48c75eb25d265c28b92a16548212b8
# via jsonschema
-jinja2==3.0.3 \
- --hash=sha256:077ce6014f7b40d03b47d1f1ca4b0fc8328a692bd284016f806ed0eaca390ad8 \
- --hash=sha256:611bb273cd68f3b993fabdc4064fc858c5b47a973cb5aa7999ec1ba405c87cd7
+jinja2==3.1.2 \
+ --hash=sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852 \
+ --hash=sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61
# via sphinx
jsonschema==4.4.0 ; python_version >= "3.7" \
--hash=sha256:636694eb41b3535ed608fe04129f26542b59ed99808b4f688aa32dcf55317a83 \
@@ -150,77 +184,52 @@ jsonschema==4.4.0 ; python_version >= "3.7" \
lark-parser==0.6.7 \
--hash=sha256:062800f3823a6c733ec1d181a2089a22d1f62dbe65f90a3f6b1e6de1934b05ef
# via syslog-rfc5424-parser
-markupsafe==2.0.1 \
- --hash=sha256:01a9b8ea66f1658938f65b93a85ebe8bc016e6769611be228d797c9d998dd298 \
- --hash=sha256:023cb26ec21ece8dc3907c0e8320058b2e0cb3c55cf9564da612bc325bed5e64 \
- --hash=sha256:0446679737af14f45767963a1a9ef7620189912317d095f2d9ffa183a4d25d2b \
- --hash=sha256:04635854b943835a6ea959e948d19dcd311762c5c0c6e1f0e16ee57022669194 \
- --hash=sha256:0717a7390a68be14b8c793ba258e075c6f4ca819f15edfc2a3a027c823718567 \
- --hash=sha256:0955295dd5eec6cb6cc2fe1698f4c6d84af2e92de33fbcac4111913cd100a6ff \
- --hash=sha256:0d4b31cc67ab36e3392bbf3862cfbadac3db12bdd8b02a2731f509ed5b829724 \
- --hash=sha256:10f82115e21dc0dfec9ab5c0223652f7197feb168c940f3ef61563fc2d6beb74 \
- --hash=sha256:168cd0a3642de83558a5153c8bd34f175a9a6e7f6dc6384b9655d2697312a646 \
- --hash=sha256:1d609f577dc6e1aa17d746f8bd3c31aa4d258f4070d61b2aa5c4166c1539de35 \
- --hash=sha256:1f2ade76b9903f39aa442b4aadd2177decb66525062db244b35d71d0ee8599b6 \
- --hash=sha256:20dca64a3ef2d6e4d5d615a3fd418ad3bde77a47ec8a23d984a12b5b4c74491a \
- --hash=sha256:2a7d351cbd8cfeb19ca00de495e224dea7e7d919659c2841bbb7f420ad03e2d6 \
- --hash=sha256:2d7d807855b419fc2ed3e631034685db6079889a1f01d5d9dac950f764da3dad \
- --hash=sha256:2ef54abee730b502252bcdf31b10dacb0a416229b72c18b19e24a4509f273d26 \
- --hash=sha256:36bc903cbb393720fad60fc28c10de6acf10dc6cc883f3e24ee4012371399a38 \
- --hash=sha256:37205cac2a79194e3750b0af2a5720d95f786a55ce7df90c3af697bfa100eaac \
- --hash=sha256:3c112550557578c26af18a1ccc9e090bfe03832ae994343cfdacd287db6a6ae7 \
- --hash=sha256:3dd007d54ee88b46be476e293f48c85048603f5f516008bee124ddd891398ed6 \
- --hash=sha256:4296f2b1ce8c86a6aea78613c34bb1a672ea0e3de9c6ba08a960efe0b0a09047 \
- --hash=sha256:47ab1e7b91c098ab893b828deafa1203de86d0bc6ab587b160f78fe6c4011f75 \
- --hash=sha256:49e3ceeabbfb9d66c3aef5af3a60cc43b85c33df25ce03d0031a608b0a8b2e3f \
- --hash=sha256:4dc8f9fb58f7364b63fd9f85013b780ef83c11857ae79f2feda41e270468dd9b \
- --hash=sha256:4efca8f86c54b22348a5467704e3fec767b2db12fc39c6d963168ab1d3fc9135 \
- --hash=sha256:53edb4da6925ad13c07b6d26c2a852bd81e364f95301c66e930ab2aef5b5ddd8 \
- --hash=sha256:5855f8438a7d1d458206a2466bf82b0f104a3724bf96a1c781ab731e4201731a \
- --hash=sha256:594c67807fb16238b30c44bdf74f36c02cdf22d1c8cda91ef8a0ed8dabf5620a \
- --hash=sha256:5b6d930f030f8ed98e3e6c98ffa0652bdb82601e7a016ec2ab5d7ff23baa78d1 \
- --hash=sha256:5bb28c636d87e840583ee3adeb78172efc47c8b26127267f54a9c0ec251d41a9 \
- --hash=sha256:60bf42e36abfaf9aff1f50f52644b336d4f0a3fd6d8a60ca0d054ac9f713a864 \
- --hash=sha256:611d1ad9a4288cf3e3c16014564df047fe08410e628f89805e475368bd304914 \
- --hash=sha256:6300b8454aa6930a24b9618fbb54b5a68135092bc666f7b06901f897fa5c2fee \
- --hash=sha256:63f3268ba69ace99cab4e3e3b5840b03340efed0948ab8f78d2fd87ee5442a4f \
- --hash=sha256:6557b31b5e2c9ddf0de32a691f2312a32f77cd7681d8af66c2692efdbef84c18 \
- --hash=sha256:693ce3f9e70a6cf7d2fb9e6c9d8b204b6b39897a2c4a1aa65728d5ac97dcc1d8 \
- --hash=sha256:6a7fae0dd14cf60ad5ff42baa2e95727c3d81ded453457771d02b7d2b3f9c0c2 \
- --hash=sha256:6c4ca60fa24e85fe25b912b01e62cb969d69a23a5d5867682dd3e80b5b02581d \
- --hash=sha256:6fcf051089389abe060c9cd7caa212c707e58153afa2c649f00346ce6d260f1b \
- --hash=sha256:7d91275b0245b1da4d4cfa07e0faedd5b0812efc15b702576d103293e252af1b \
- --hash=sha256:89c687013cb1cd489a0f0ac24febe8c7a666e6e221b783e53ac50ebf68e45d86 \
- --hash=sha256:8d206346619592c6200148b01a2142798c989edcb9c896f9ac9722a99d4e77e6 \
- --hash=sha256:905fec760bd2fa1388bb5b489ee8ee5f7291d692638ea5f67982d968366bef9f \
- --hash=sha256:97383d78eb34da7e1fa37dd273c20ad4320929af65d156e35a5e2d89566d9dfb \
- --hash=sha256:984d76483eb32f1bcb536dc27e4ad56bba4baa70be32fa87152832cdd9db0833 \
- --hash=sha256:99df47edb6bda1249d3e80fdabb1dab8c08ef3975f69aed437cb69d0a5de1e28 \
- --hash=sha256:9f02365d4e99430a12647f09b6cc8bab61a6564363f313126f775eb4f6ef798e \
- --hash=sha256:a30e67a65b53ea0a5e62fe23682cfe22712e01f453b95233b25502f7c61cb415 \
- --hash=sha256:ab3ef638ace319fa26553db0624c4699e31a28bb2a835c5faca8f8acf6a5a902 \
- --hash=sha256:aca6377c0cb8a8253e493c6b451565ac77e98c2951c45f913e0b52facdcff83f \
- --hash=sha256:add36cb2dbb8b736611303cd3bfcee00afd96471b09cda130da3581cbdc56a6d \
- --hash=sha256:b2f4bf27480f5e5e8ce285a8c8fd176c0b03e93dcc6646477d4630e83440c6a9 \
- --hash=sha256:b7f2d075102dc8c794cbde1947378051c4e5180d52d276987b8d28a3bd58c17d \
- --hash=sha256:baa1a4e8f868845af802979fcdbf0bb11f94f1cb7ced4c4b8a351bb60d108145 \
- --hash=sha256:be98f628055368795d818ebf93da628541e10b75b41c559fdf36d104c5787066 \
- --hash=sha256:bf5d821ffabf0ef3533c39c518f3357b171a1651c1ff6827325e4489b0e46c3c \
- --hash=sha256:c47adbc92fc1bb2b3274c4b3a43ae0e4573d9fbff4f54cd484555edbf030baf1 \
- --hash=sha256:cdfba22ea2f0029c9261a4bd07e830a8da012291fbe44dc794e488b6c9bb353a \
- --hash=sha256:d6c7ebd4e944c85e2c3421e612a7057a2f48d478d79e61800d81468a8d842207 \
- --hash=sha256:d7f9850398e85aba693bb640262d3611788b1f29a79f0c93c565694658f4071f \
- --hash=sha256:d8446c54dc28c01e5a2dbac5a25f071f6653e6e40f3a8818e8b45d790fe6ef53 \
- --hash=sha256:deb993cacb280823246a026e3b2d81c493c53de6acfd5e6bfe31ab3402bb37dd \
- --hash=sha256:e0f138900af21926a02425cf736db95be9f4af72ba1bb21453432a07f6082134 \
- --hash=sha256:e9936f0b261d4df76ad22f8fee3ae83b60d7c3e871292cd42f40b81b70afae85 \
- --hash=sha256:f0567c4dc99f264f49fe27da5f735f414c4e7e7dd850cfd8e69f0862d7c74ea9 \
- --hash=sha256:f5653a225f31e113b152e56f154ccbe59eeb1c7487b39b9d9f9cdb58e6c79dc5 \
- --hash=sha256:f826e31d18b516f653fe296d967d700fddad5901ae07c622bb3705955e1faa94 \
- --hash=sha256:f8ba0e8349a38d3001fae7eadded3f6606f0da5d748ee53cc1dab1d6527b9509 \
- --hash=sha256:f9081981fe268bd86831e5c75f7de206ef275defcb82bc70740ae6dc507aee51 \
- --hash=sha256:fa130dd50c57d53368c9d59395cb5526eda596d3ffe36666cd81a44d56e48872
+markupsafe==2.1.1 \
+ --hash=sha256:0212a68688482dc52b2d45013df70d169f542b7394fc744c02a57374a4207003 \
+ --hash=sha256:089cf3dbf0cd6c100f02945abeb18484bd1ee57a079aefd52cffd17fba910b88 \
+ --hash=sha256:10c1bfff05d95783da83491be968e8fe789263689c02724e0c691933c52994f5 \
+ --hash=sha256:33b74d289bd2f5e527beadcaa3f401e0df0a89927c1559c8566c066fa4248ab7 \
+ --hash=sha256:3799351e2336dc91ea70b034983ee71cf2f9533cdff7c14c90ea126bfd95d65a \
+ --hash=sha256:3ce11ee3f23f79dbd06fb3d63e2f6af7b12db1d46932fe7bd8afa259a5996603 \
+ --hash=sha256:421be9fbf0ffe9ffd7a378aafebbf6f4602d564d34be190fc19a193232fd12b1 \
+ --hash=sha256:43093fb83d8343aac0b1baa75516da6092f58f41200907ef92448ecab8825135 \
+ --hash=sha256:46d00d6cfecdde84d40e572d63735ef81423ad31184100411e6e3388d405e247 \
+ --hash=sha256:4a33dea2b688b3190ee12bd7cfa29d39c9ed176bda40bfa11099a3ce5d3a7ac6 \
+ --hash=sha256:4b9fe39a2ccc108a4accc2676e77da025ce383c108593d65cc909add5c3bd601 \
+ --hash=sha256:56442863ed2b06d19c37f94d999035e15ee982988920e12a5b4ba29b62ad1f77 \
+ --hash=sha256:671cd1187ed5e62818414afe79ed29da836dde67166a9fac6d435873c44fdd02 \
+ --hash=sha256:694deca8d702d5db21ec83983ce0bb4b26a578e71fbdbd4fdcd387daa90e4d5e \
+ --hash=sha256:6a074d34ee7a5ce3effbc526b7083ec9731bb3cbf921bbe1d3005d4d2bdb3a63 \
+ --hash=sha256:6d0072fea50feec76a4c418096652f2c3238eaa014b2f94aeb1d56a66b41403f \
+ --hash=sha256:6fbf47b5d3728c6aea2abb0589b5d30459e369baa772e0f37a0320185e87c980 \
+ --hash=sha256:7f91197cc9e48f989d12e4e6fbc46495c446636dfc81b9ccf50bb0ec74b91d4b \
+ --hash=sha256:86b1f75c4e7c2ac2ccdaec2b9022845dbb81880ca318bb7a0a01fbf7813e3812 \
+ --hash=sha256:8dc1c72a69aa7e082593c4a203dcf94ddb74bb5c8a731e4e1eb68d031e8498ff \
+ --hash=sha256:8e3dcf21f367459434c18e71b2a9532d96547aef8a871872a5bd69a715c15f96 \
+ --hash=sha256:8e576a51ad59e4bfaac456023a78f6b5e6e7651dcd383bcc3e18d06f9b55d6d1 \
+ --hash=sha256:96e37a3dc86e80bf81758c152fe66dbf60ed5eca3d26305edf01892257049925 \
+ --hash=sha256:97a68e6ada378df82bc9f16b800ab77cbf4b2fada0081794318520138c088e4a \
+ --hash=sha256:99a2a507ed3ac881b975a2976d59f38c19386d128e7a9a18b7df6fff1fd4c1d6 \
+ --hash=sha256:a49907dd8420c5685cfa064a1335b6754b74541bbb3706c259c02ed65b644b3e \
+ --hash=sha256:b09bf97215625a311f669476f44b8b318b075847b49316d3e28c08e41a7a573f \
+ --hash=sha256:b7bd98b796e2b6553da7225aeb61f447f80a1ca64f41d83612e6139ca5213aa4 \
+ --hash=sha256:b87db4360013327109564f0e591bd2a3b318547bcef31b468a92ee504d07ae4f \
+ --hash=sha256:bcb3ed405ed3222f9904899563d6fc492ff75cce56cba05e32eff40e6acbeaa3 \
+ --hash=sha256:d4306c36ca495956b6d568d276ac11fdd9c30a36f1b6eb928070dc5360b22e1c \
+ --hash=sha256:d5ee4f386140395a2c818d149221149c54849dfcfcb9f1debfe07a8b8bd63f9a \
+ --hash=sha256:dda30ba7e87fbbb7eab1ec9f58678558fd9a6b8b853530e176eabd064da81417 \
+ --hash=sha256:e04e26803c9c3851c931eac40c695602c6295b8d432cbe78609649ad9bd2da8a \
+ --hash=sha256:e1c0b87e09fa55a220f058d1d49d3fb8df88fbfab58558f1198e08c1e1de842a \
+ --hash=sha256:e72591e9ecd94d7feb70c1cbd7be7b3ebea3f548870aa91e2732960fa4d57a37 \
+ --hash=sha256:e8c843bbcda3a2f1e3c2ab25913c80a3c5376cd00c6e8c4a86a89a28c8dc5452 \
+ --hash=sha256:efc1913fd2ca4f334418481c7e595c00aad186563bbc1ec76067848c7ca0a933 \
+ --hash=sha256:f121a1420d4e173a5d96e47e9a0c0dcff965afdf1626d28de1460815f7c4ee7a \
+ --hash=sha256:fc7b548b17d238737688817ab67deebb30e8073c95749d55538ed473130ec0c7
# via jinja2
+mypy-extensions==0.4.3 \
+ --hash=sha256:090fedd75945a69ae91ce1303b5824f428daf5a028d2f6ab8a299250a846f15d \
+ --hash=sha256:2d82818f5bb3e369420cb3c4060a7970edba416647068eb4c5343488a6c604a8
+ # via black
noiseprotocol==0.3.1 \
--hash=sha256:2e1a603a38439636cf0ffd8b3e8b12cee27d368a28b41be7dbe568b2abb23111 \
--hash=sha256:b092a871b60f6a8f07f17950dc9f7098c8fe7d715b049bd4c24ee3752b90d645
@@ -239,6 +248,10 @@ parameterized==0.8.1 \
--hash=sha256:41bbff37d6186430f77f900d777e5bb6a24928a1c46fb1de692f8b52b8833b5c \
--hash=sha256:9cbb0b69a03e8695d68b3399a8a5825200976536fe1cb79db60ed6a4c8c9efe9
# via -r requirements.txt
+pathspec==0.9.0 \
+ --hash=sha256:7d15c4ddb0b5c802d161efc417ec1a2558ea2653c2e8ad9c19098201dc1c993a \
+ --hash=sha256:e564499435a2673d586f6b2130bb5b95f04a3ba06f81b8f895b651a3c76aabb1
+ # via black
pep517==0.12.0 \
--hash=sha256:931378d93d11b298cf511dd634cf5ea4cb249a28ef84160b3247ee9afb4e8ab0 \
--hash=sha256:dd884c326898e2c6e11f9e0b64940606a93eb10ea022a2e067959f3a110cf161
@@ -247,10 +260,14 @@ pexpect==4.8.0 \
--hash=sha256:0b48a55dcb3c05f3329815901ea4fc1537514d6ba867a152b581d69ae3710937 \
--hash=sha256:fc65a43959d153d0114afe13997d439c22823a27cefceb5ff35c2178c6784c0c
# via -r requirements.txt
-pip-tools==6.5.0 \
- --hash=sha256:9cf69a020e3c208a7a1bcc78cbfd436dab323efc187919df6182eca98efbe3f2 \
- --hash=sha256:d14ea4fc2c118db2a6af65a4345a8b9b355e792aedad6bf64dd3eb97c5fc5fee
+pip-tools==6.6.0 \
+ --hash=sha256:66318bc2e884b61fafa1cb2cf01b35fdd779ab9ce82cc1bce277adb8cf3ab845 \
+ --hash=sha256:98aa24004440a1c0489d71a567a4e8afdf23c7782bff483d1219881e7302de83
# via -r requirements.txt
+platformdirs==2.5.2 \
+ --hash=sha256:027d8e83a2d7de06bbac4e5ef7e023c02b863d7ea5d079477e722bb41ab25788 \
+ --hash=sha256:58c8abb07dcb441e6ee4b11d8df0ac856038f944ab98b7be6b27b2a3c7feef19
+ # via black
psutil==5.9.0 \
--hash=sha256:072664401ae6e7c1bfb878c65d7282d4b4391f1bc9a56d5e03b5a490403271b5 \
--hash=sha256:1070a9b287846a21a5d572d6dddd369517510b68710fca56b0e9e02fd24bed9a \
@@ -289,10 +306,6 @@ ptyprocess==0.7.0 \
--hash=sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35 \
--hash=sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220
# via pexpect
-pycodestyle==2.8.0 \
- --hash=sha256:720f8b39dde8b293825e7ff02c475f3077124006db4f440dcbc9a20b76548a20 \
- --hash=sha256:eddd5847ef438ea1c7870ca7eb78a9d47ce0cdb4851a5523949f2601d0cbbe7f
- # via -r requirements.txt
pycparser==2.21 \
--hash=sha256:8ee45429555515e1f6b185e78100aea234072576aa43ab53aefcae078162fca9 \
--hash=sha256:e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206
@@ -303,17 +316,17 @@ pyenchant==3.2.2 \
--hash=sha256:5facc821ece957208a81423af7d6ec7810dad29697cb0d77aae81e4e11c8e5a6 \
--hash=sha256:6153f521852e23a5add923dbacfbf4bebbb8d70c4e4bad609a8e0f9faeb915d1
# via sphinxcontrib-spelling
-pygments==2.11.2 \
- --hash=sha256:44238f1b60a76d78fc8ca0528ee429702aae011c265fe6a8dd8b63049ae41c65 \
- --hash=sha256:4e426f72023d88d03b2fa258de560726ce890ff3b630f88c21cbb8b2503b8c6a
+pygments==2.12.0 \
+ --hash=sha256:5eb116118f9612ff1ee89ac96437bb6b49e8f04d8a13b514ba26f620208e26eb \
+ --hash=sha256:dc9c10fb40944260f6ed4c688ece0cd2048414940f1cea51b8b226318411c519
# via sphinx
pympler==1.0.1 \
--hash=sha256:993f1a3599ca3f4fcd7160c7545ad06310c9e12f70174ae7ae8d4e25f6c5d3fa \
--hash=sha256:d260dda9ae781e1eab6ea15bacb84015849833ba5555f141d2d9b7b7473b307d
# via -r requirements.txt
-pyparsing==3.0.7 \
- --hash=sha256:18ee9022775d270c55187733956460083db60b37d0d0fb357445f3094eed3eea \
- --hash=sha256:a6c06a88f252e6c322f65faf8f418b16213b51bdfaece0524c1c1bc30c63c484
+pyparsing==3.0.8 \
+ --hash=sha256:7bf433498c016c4314268d95df76c81b842a4cb2b276fa3312cfb1e1d85f6954 \
+ --hash=sha256:ef7b523f6356f763771559412c0d7134753f037822dad1b16945b7b846f7ad06
# via packaging
pyrsistent==0.18.1 \
--hash=sha256:0e3e1fcc45199df76053026a51cc59ab2ea3fc7c094c6627e93b7b44cdae2c8c \
@@ -338,9 +351,9 @@ pyrsistent==0.18.1 \
--hash=sha256:f87cc2863ef33c709e237d4b5f4502a62a00fab450c9e020892e8e2ede5847f5 \
--hash=sha256:fd8da6d0124efa2f67d86fa70c851022f87c98e205f0594e1fae044e7119a5a6
# via jsonschema
-pytz==2021.3 \
- --hash=sha256:3672058bc3453457b622aab7a1c3bfd5ab0bdae451512f6cf25f64ed37f5b87c \
- --hash=sha256:acad2d8b20a1af07d4e4c9d2e9285c5ed9104354062f275f3fcd88dcef4f1326
+pytz==2022.1 \
+ --hash=sha256:1e760e2fe6a8163bc0b3d9a19c4f84342afa0a2affebfaa84b01b978a02ecaa7 \
+ --hash=sha256:e68985985296d9a66a881eb3193b0906246245294a881e7c8afe623866ac6a5c
# via babel
pyyaml==6.0 \
--hash=sha256:0283c35a6a9fbf047493e3a0ce8d79ef5030852c51e9d911a27badfde0605293 \
@@ -396,9 +409,9 @@ snowballstemmer==2.2.0 \
--hash=sha256:09b16deb8547d3412ad7b590689584cd0fe25ec8db3be37788be3810cbf19cb1 \
--hash=sha256:c8e1716e83cc398ae16824e5572ae04e0d9fc2c6b985fb0f900f5f0c96ecba1a
# via sphinx
-sphinx==4.4.0 \
- --hash=sha256:5da895959511473857b6d0200f56865ed62c31e8f82dd338063b84ec022701fe \
- --hash=sha256:6caad9786055cb1fa22b4a365c1775816b876f91966481765d7d50e9f0dd35cc
+sphinx==4.5.0 \
+ --hash=sha256:7bf8ca9637a4ee15af412d1a1d9689fec70523a68ca9bb9127c2f3eeb344e2e6 \
+ --hash=sha256:ebf612653238bcc8f4359627a9b7ce44ede6fdd75d9d30f68255c7383d3a6226
# via
# -r requirements.txt
# recommonmark
@@ -432,32 +445,68 @@ sphinxcontrib-serializinghtml==1.1.5 \
--hash=sha256:352a9a00ae864471d3a7ead8d7d79f5fc0b57e8b3f95e9867eb9eb28999b92fd \
--hash=sha256:aa5f6de5dfdf809ef505c4895e51ef5c9eac17d0f287933eb49ec495280b6952
# via sphinx
-sphinxcontrib-spelling==7.3.2 \
- --hash=sha256:1b99cdb1a30271c7080ec5b968dfc243c2540a960afdc4c052cd59dfe8d94c54 \
- --hash=sha256:9d66dc4990749c5ac52e7eaf17e82f4dc6b4aff6515d26bbf48821829d41bd02
+sphinxcontrib-spelling==7.3.3 \
+ --hash=sha256:3819d12629d95e0c909224fa40b462a67e0adb321d50283d7fc0d11686c8ac7e \
+ --hash=sha256:8809d5dc175f43f00628134a41ef9fec56db9f794f4eab701f9a5a87f8c69bb0
# via -r requirements.txt
syslog-rfc5424-parser==0.3.2 \
--hash=sha256:6134ee1958da89ab7f8d32ed5370a49ddabcc99d75a950b6ec59708417f20a7a \
--hash=sha256:80a9239d4da404a271266000f4c5f00a183af3d03d53d19d7052c8272430bee9
# via -r requirements.txt
-tomli==2.0.0 \
- --hash=sha256:b5bde28da1fed24b9bd1d4d2b8cba62300bfb4ec9a6187a957e8ddb9434c5224 \
- --hash=sha256:c292c34f58502a1eb2bbb9f5bbc9a5ebc37bee10ffb8c2d6bbdfa8eb13cc14e1
- # via pep517
-urllib3==1.26.8 \
- --hash=sha256:000ca7f471a233c2251c6c7023ee85305721bfdf18621ebff4fd17a8653427ed \
- --hash=sha256:0e7c33d9a63e7ddfcb86780aac87befc2fbddf46c58dbb487e0855f7ceec283c
+tomli==2.0.1 \
+ --hash=sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc \
+ --hash=sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f
+ # via
+ # black
+ # pep517
+typed-ast==1.5.3 \
+ --hash=sha256:20d5118e494478ef2d3a2702d964dae830aedd7b4d3b626d003eea526be18718 \
+ --hash=sha256:27e46cdd01d6c3a0dd8f728b6a938a6751f7bd324817501c15fb056307f918c6 \
+ --hash=sha256:27f25232e2dd0edfe1f019d6bfaaf11e86e657d9bdb7b0956db95f560cceb2b3 \
+ --hash=sha256:3042bfc9ca118712c9809201f55355479cfcdc17449f9f8db5e744e9625c6805 \
+ --hash=sha256:37e5349d1d5de2f4763d534ccb26809d1c24b180a477659a12c4bde9dd677d74 \
+ --hash=sha256:4fff9fdcce59dc61ec1b317bdb319f8f4e6b69ebbe61193ae0a60c5f9333dc49 \
+ --hash=sha256:542cd732351ba8235f20faa0fc7398946fe1a57f2cdb289e5497e1e7f48cfedb \
+ --hash=sha256:5dc2c11ae59003d4a26dda637222d9ae924387f96acae9492df663843aefad55 \
+ --hash=sha256:8831479695eadc8b5ffed06fdfb3e424adc37962a75925668deeb503f446c0a3 \
+ --hash=sha256:8cdf91b0c466a6c43f36c1964772918a2c04cfa83df8001ff32a89e357f8eb06 \
+ --hash=sha256:8e0b8528838ffd426fea8d18bde4c73bcb4167218998cc8b9ee0a0f2bfe678a6 \
+ --hash=sha256:8ef1d96ad05a291f5c36895d86d1375c0ee70595b90f6bb5f5fdbee749b146db \
+ --hash=sha256:9ad3b48cf2b487be140072fb86feff36801487d4abb7382bb1929aaac80638ea \
+ --hash=sha256:9cc9e1457e1feb06b075c8ef8aeb046a28ec351b1958b42c7c31c989c841403a \
+ --hash=sha256:9e237e74fd321a55c90eee9bc5d44be976979ad38a29bbd734148295c1ce7617 \
+ --hash=sha256:c9f1a27592fac87daa4e3f16538713d705599b0a27dfe25518b80b6b017f0a6d \
+ --hash=sha256:d64dabc6336ddc10373922a146fa2256043b3b43e61f28961caec2a5207c56d5 \
+ --hash=sha256:e20d196815eeffb3d76b75223e8ffed124e65ee62097e4e73afb5fec6b993e7a \
+ --hash=sha256:e34f9b9e61333ecb0f7d79c21c28aa5cd63bec15cb7e1310d7d3da6ce886bc9b \
+ --hash=sha256:ed44e81517364cb5ba367e4f68fca01fba42a7a4690d40c07886586ac267d9b9 \
+ --hash=sha256:ee852185964744987609b40aee1d2eb81502ae63ee8eef614558f96a56c1902d \
+ --hash=sha256:f60d9de0d087454c91b3999a296d0c4558c1666771e3460621875021bf899af9 \
+ --hash=sha256:f818c5b81966d4728fec14caa338e30a70dfc3da577984d38f97816c4b3071ec \
+ --hash=sha256:fd5df1313915dbd70eaaa88c19030b441742e8b05e6103c631c83b75e0435ccc
+ # via black
+typing-extensions==4.2.0 \
+ --hash=sha256:6657594ee297170d19f67d55c05852a874e7eb634f4f753dbd667855e07c1708 \
+ --hash=sha256:f1c24655a0da0d1b67f07e17a5e6b2a105894e6824b92096378bb3668ef02376
+ # via
+ # black
+ # importlib-metadata
+ # jsonschema
+urllib3==1.26.9 \
+ --hash=sha256:44ece4d53fb1706f667c9bd1c648f5469a2ec925fcf3a776667042d645472c14 \
+ --hash=sha256:aabaf16477806a5e1dd19aa41f8c2b7950dd3c746362d7e3223dbe6de6ac448e
# via requests
wheel==0.37.1 \
--hash=sha256:4bdcd7d840138086126cd09254dc6195fb4fc6f01c050a1d7236f2630db1d22a \
--hash=sha256:e9a504e793efbca1b8e0e9cb979a249cf4a0a7b5b8c9e8b65a5e39d49529c1c4
# via pip-tools
-zipp==3.7.0 \
- --hash=sha256:9f50f446828eb9d45b267433fd3e9da8d801f614129124863f9c51ebceafb87d \
- --hash=sha256:b47250dd24f92b7dd6a0a8fc5244da14608f3ca90a5efcd37a3b1642fac9a375
+zipp==3.8.0 \
+ --hash=sha256:56bf8aadb83c24db6c4b577e13de374ccfb67da2078beba1d037c17980bf43ad \
+ --hash=sha256:c4f6e5bbf48e74f7a38e7cc5b0480ff42b0ae5178957d564d18932525d5cf099
# via
# importlib-metadata
# importlib-resources
+ # pep517
# WARNING: The following packages were not pinned, but pip requires them to be
# pinned when the requirements file includes hashes. Consider using the --allow-unsafe flag.
diff --git a/test/requirements.txt b/test/requirements.txt
index 7df379367a4..a1779671e31 100644
--- a/test/requirements.txt
+++ b/test/requirements.txt
@@ -1,4 +1,4 @@
-pip-tools==6.5.0 # BSD Keep this in sync with Makefile's PIP_TOOLS_VERSION
+pip-tools==6.6.0 # BSD Keep this in sync with Makefile's PIP_TOOLS_VERSION
cryptography!=2.0 # BSD/Apache-2.0
deprecation>=2.0.6 # Apache-2.0
faulthandler; python_version < '3.3' # # BSD License (2 clause)
@@ -6,7 +6,6 @@ ipaddress; python_version < '3.3' # PSF
parameterized>=0.6.1 # BSD
pexpect # ISC
psutil # BSD
-pycodestyle # MIT (Expat license) https://pypi.org/project/pycodestyle/
scapy==2.4.3; python_version >= '2.7' or python_version >= '3.4' # GPL2 https://github.com/secdev/scapy/blob/master/LICENSE
six # MIT
syslog_rfc5424_parser>=0.3.1 # ISC
@@ -20,3 +19,4 @@ recommonmark # MIT
pyyaml # MIT
jsonschema; python_version >= '3.7' # MIT
dataclasses; python_version == '3.6' # Apache-2.0
+black # MIT https://github.com/psf/black
diff --git a/test/run_tests.py b/test/run_tests.py
index 8cb631ed660..5df37efba6b 100644
--- a/test/run_tests.py
+++ b/test/run_tests.py
@@ -16,12 +16,28 @@ from multiprocessing.queues import Queue
from multiprocessing.managers import BaseManager
import framework
from config import config, num_cpus, available_cpus, max_vpp_cpus
-from framework import VppTestRunner, VppTestCase, \
- get_testcase_doc_name, get_test_description, PASS, FAIL, ERROR, SKIP, \
- TEST_RUN, SKIP_CPU_SHORTAGE
+from framework import (
+ VppTestRunner,
+ VppTestCase,
+ get_testcase_doc_name,
+ get_test_description,
+ PASS,
+ FAIL,
+ ERROR,
+ SKIP,
+ TEST_RUN,
+ SKIP_CPU_SHORTAGE,
+)
from debug import spawn_gdb, start_vpp_in_gdb
-from log import get_parallel_logger, double_line_delim, RED, YELLOW, GREEN, \
- colorize, single_line_delim
+from log import (
+ get_parallel_logger,
+ double_line_delim,
+ RED,
+ YELLOW,
+ GREEN,
+ colorize,
+ single_line_delim,
+)
from discover_tests import discover_tests
import sanity_run_vpp
from subprocess import check_output, CalledProcessError
@@ -50,7 +66,7 @@ class StreamQueueManager(BaseManager):
pass
-StreamQueueManager.register('StreamQueue', StreamQueue)
+StreamQueueManager.register("StreamQueue", StreamQueue)
class TestResult(dict):
@@ -68,9 +84,11 @@ class TestResult(dict):
self.testcases_by_id = testcases_by_id
def was_successful(self):
- return 0 == len(self[FAIL]) == len(self[ERROR]) \
- and len(self[PASS] + self[SKIP] + self[SKIP_CPU_SHORTAGE]) \
+ return (
+ 0 == len(self[FAIL]) == len(self[ERROR])
+ and len(self[PASS] + self[SKIP] + self[SKIP_CPU_SHORTAGE])
== self.testcase_suite.countTestCases()
+ )
def no_tests_run(self):
return 0 == len(self[TEST_RUN])
@@ -90,10 +108,11 @@ class TestResult(dict):
def get_testcase_names(self, test_id):
# could be tearDownClass (test_ipsec_esp.TestIpsecEsp1)
setup_teardown_match = re.match(
- r'((tearDownClass)|(setUpClass)) \((.+\..+)\)', test_id)
+ r"((tearDownClass)|(setUpClass)) \((.+\..+)\)", test_id
+ )
if setup_teardown_match:
test_name, _, _, testcase_name = setup_teardown_match.groups()
- if len(testcase_name.split('.')) == 2:
+ if len(testcase_name.split(".")) == 2:
for key in self.testcases_by_id.keys():
if key.startswith(testcase_name):
testcase_name = key
@@ -107,8 +126,7 @@ class TestResult(dict):
def _get_test_description(self, test_id):
if test_id in self.testcases_by_id:
- desc = get_test_description(descriptions,
- self.testcases_by_id[test_id])
+ desc = get_test_description(descriptions, self.testcases_by_id[test_id])
else:
desc = test_id
return desc
@@ -121,17 +139,20 @@ class TestResult(dict):
return doc_name
-def test_runner_wrapper(suite, keep_alive_pipe, stdouterr_queue,
- finished_pipe, result_pipe, logger):
+def test_runner_wrapper(
+ suite, keep_alive_pipe, stdouterr_queue, finished_pipe, result_pipe, logger
+):
sys.stdout = stdouterr_queue
sys.stderr = stdouterr_queue
VppTestCase.parallel_handler = logger.handlers[0]
- result = VppTestRunner(keep_alive_pipe=keep_alive_pipe,
- descriptions=descriptions,
- verbosity=config.verbose,
- result_pipe=result_pipe,
- failfast=config.failfast,
- print_summary=False).run(suite)
+ result = VppTestRunner(
+ keep_alive_pipe=keep_alive_pipe,
+ descriptions=descriptions,
+ verbosity=config.verbose,
+ result_pipe=result_pipe,
+ failfast=config.failfast,
+ print_summary=False,
+ ).run(suite)
finished_pipe.send(result.wasSuccessful())
finished_pipe.close()
keep_alive_pipe.close()
@@ -139,21 +160,23 @@ def test_runner_wrapper(suite, keep_alive_pipe, stdouterr_queue,
class TestCaseWrapper(object):
def __init__(self, testcase_suite, manager):
- self.keep_alive_parent_end, self.keep_alive_child_end = Pipe(
- duplex=False)
+ self.keep_alive_parent_end, self.keep_alive_child_end = Pipe(duplex=False)
self.finished_parent_end, self.finished_child_end = Pipe(duplex=False)
self.result_parent_end, self.result_child_end = Pipe(duplex=False)
self.testcase_suite = testcase_suite
self.stdouterr_queue = manager.StreamQueue(ctx=get_context())
self.logger = get_parallel_logger(self.stdouterr_queue)
- self.child = Process(target=test_runner_wrapper,
- args=(testcase_suite,
- self.keep_alive_child_end,
- self.stdouterr_queue,
- self.finished_child_end,
- self.result_child_end,
- self.logger)
- )
+ self.child = Process(
+ target=test_runner_wrapper,
+ args=(
+ testcase_suite,
+ self.keep_alive_child_end,
+ self.stdouterr_queue,
+ self.finished_child_end,
+ self.result_child_end,
+ self.logger,
+ ),
+ )
self.child.start()
self.last_test_temp_dir = None
self.last_test_vpp_binary = None
@@ -187,18 +210,20 @@ class TestCaseWrapper(object):
if self.last_test_id in self.testcases_by_id:
test = self.testcases_by_id[self.last_test_id]
class_name = unittest.util.strclass(test.__class__)
- test_name = "'{}' ({})".format(get_test_description(descriptions,
- test),
- self.last_test_id)
+ test_name = "'{}' ({})".format(
+ get_test_description(descriptions, test), self.last_test_id
+ )
else:
test_name = self.last_test_id
- class_name = re.match(r'((tearDownClass)|(setUpClass)) '
- r'\((.+\..+)\)', test_name).groups()[3]
+ class_name = re.match(
+ r"((tearDownClass)|(setUpClass)) " r"\((.+\..+)\)", test_name
+ ).groups()[3]
if class_name not in self.testclasess_with_core:
self.testclasess_with_core[class_name] = (
test_name,
self.last_test_vpp_binary,
- self.last_test_temp_dir)
+ self.last_test_temp_dir,
+ )
def close_pipes(self):
self.keep_alive_child_end.close()
@@ -219,8 +244,9 @@ class TestCaseWrapper(object):
return self.testcase_suite.get_assigned_cpus()
-def stdouterr_reader_wrapper(unread_testcases, finished_unread_testcases,
- read_testcases):
+def stdouterr_reader_wrapper(
+ unread_testcases, finished_unread_testcases, read_testcases
+):
read_testcase = None
while read_testcases.is_set() or unread_testcases:
if finished_unread_testcases:
@@ -229,7 +255,7 @@ def stdouterr_reader_wrapper(unread_testcases, finished_unread_testcases,
elif unread_testcases:
read_testcase = unread_testcases.pop()
if read_testcase:
- data = ''
+ data = ""
while data is not None:
sys.stdout.write(data)
data = read_testcase.stdouterr_queue.get()
@@ -243,52 +269,62 @@ def handle_failed_suite(logger, last_test_temp_dir, vpp_pid, vpp_binary):
if last_test_temp_dir:
# Need to create link in case of a timeout or core dump without failure
lttd = os.path.basename(last_test_temp_dir)
- link_path = '%s%s-FAILED' % (config.failed_dir, lttd)
+ link_path = "%s%s-FAILED" % (config.failed_dir, lttd)
if not os.path.exists(link_path):
os.symlink(last_test_temp_dir, link_path)
- logger.error("Symlink to failed testcase directory: %s -> %s"
- % (link_path, lttd))
+ logger.error(
+ "Symlink to failed testcase directory: %s -> %s" % (link_path, lttd)
+ )
# Report core existence
core_path = get_core_path(last_test_temp_dir)
if os.path.exists(core_path):
logger.error(
- "Core-file exists in test temporary directory: %s!" %
- core_path)
+ "Core-file exists in test temporary directory: %s!" % core_path
+ )
check_core_path(logger, core_path)
logger.debug("Running 'file %s':" % core_path)
try:
info = check_output(["file", core_path])
logger.debug(info)
except CalledProcessError as e:
- logger.error("Subprocess returned with return code "
- "while running `file' utility on core-file "
- "returned: "
- "rc=%s", e.returncode)
+ logger.error(
+ "Subprocess returned with return code "
+ "while running `file' utility on core-file "
+ "returned: "
+ "rc=%s",
+ e.returncode,
+ )
except OSError as e:
- logger.error("Subprocess returned with OS error while "
- "running 'file' utility "
- "on core-file: "
- "(%s) %s", e.errno, e.strerror)
+ logger.error(
+ "Subprocess returned with OS error while "
+ "running 'file' utility "
+ "on core-file: "
+ "(%s) %s",
+ e.errno,
+ e.strerror,
+ )
except Exception as e:
- logger.exception("Unexpected error running `file' utility "
- "on core-file")
+ logger.exception("Unexpected error running `file' utility on core-file")
logger.error(f"gdb {vpp_binary} {core_path}")
if vpp_pid:
# Copy api post mortem
api_post_mortem_path = "/tmp/api_post_mortem.%d" % vpp_pid
if os.path.isfile(api_post_mortem_path):
- logger.error("Copying api_post_mortem.%d to %s" %
- (vpp_pid, last_test_temp_dir))
+ logger.error(
+ "Copying api_post_mortem.%d to %s" % (vpp_pid, last_test_temp_dir)
+ )
shutil.copy2(api_post_mortem_path, last_test_temp_dir)
def check_and_handle_core(vpp_binary, tempdir, core_crash_test):
if is_core_present(tempdir):
if debug_core:
- print('VPP core detected in %s. Last test running was %s' %
- (tempdir, core_crash_test))
+ print(
+ "VPP core detected in %s. Last test running was %s"
+ % (tempdir, core_crash_test)
+ )
print(single_line_delim)
spawn_gdb(vpp_binary, get_core_path(tempdir))
print(single_line_delim)
@@ -305,10 +341,9 @@ def handle_cores(failed_testcases):
check_and_handle_core(vpp_binary, tempdir, test)
-def process_finished_testsuite(wrapped_testcase_suite,
- finished_testcase_suites,
- failed_wrapped_testcases,
- results):
+def process_finished_testsuite(
+ wrapped_testcase_suite, finished_testcase_suites, failed_wrapped_testcases, results
+):
results.append(wrapped_testcase_suite.result)
finished_testcase_suites.add(wrapped_testcase_suite)
stop_run = False
@@ -317,10 +352,12 @@ def process_finished_testsuite(wrapped_testcase_suite,
if not wrapped_testcase_suite.was_successful():
failed_wrapped_testcases.add(wrapped_testcase_suite)
- handle_failed_suite(wrapped_testcase_suite.logger,
- wrapped_testcase_suite.last_test_temp_dir,
- wrapped_testcase_suite.vpp_pid,
- wrapped_testcase_suite.last_test_vpp_binary,)
+ handle_failed_suite(
+ wrapped_testcase_suite.logger,
+ wrapped_testcase_suite.last_test_temp_dir,
+ wrapped_testcase_suite.vpp_pid,
+ wrapped_testcase_suite.last_test_vpp_binary,
+ )
return stop_run
@@ -355,17 +392,17 @@ def run_forked(testcase_suites):
nonlocal wrapped_testcase_suites
nonlocal unread_testcases
nonlocal free_cpus
- suite.assign_cpus(free_cpus[:suite.cpus_used])
- free_cpus = free_cpus[suite.cpus_used:]
+ suite.assign_cpus(free_cpus[: suite.cpus_used])
+ free_cpus = free_cpus[suite.cpus_used :]
wrapper = TestCaseWrapper(suite, manager)
wrapped_testcase_suites.add(wrapper)
unread_testcases.add(wrapper)
on_suite_start(suite)
def can_run_suite(suite):
- return (tests_running < max_concurrent_tests and
- (suite.cpus_used <= len(free_cpus) or
- suite.cpus_used > max_vpp_cpus))
+ return tests_running < max_concurrent_tests and (
+ suite.cpus_used <= len(free_cpus) or suite.cpus_used > max_vpp_cpus
+ )
while free_cpus and testcase_suites:
a_suite = testcase_suites[0]
@@ -385,10 +422,10 @@ def run_forked(testcase_suites):
read_from_testcases = threading.Event()
read_from_testcases.set()
- stdouterr_thread = threading.Thread(target=stdouterr_reader_wrapper,
- args=(unread_testcases,
- finished_unread_testcases,
- read_from_testcases))
+ stdouterr_thread = threading.Thread(
+ target=stdouterr_reader_wrapper,
+ args=(unread_testcases, finished_unread_testcases, read_from_testcases),
+ )
stdouterr_thread.start()
failed_wrapped_testcases = set()
@@ -400,59 +437,75 @@ def run_forked(testcase_suites):
for wrapped_testcase_suite in wrapped_testcase_suites:
while wrapped_testcase_suite.result_parent_end.poll():
wrapped_testcase_suite.result.process_result(
- *wrapped_testcase_suite.result_parent_end.recv())
+ *wrapped_testcase_suite.result_parent_end.recv()
+ )
wrapped_testcase_suite.last_heard = time.time()
while wrapped_testcase_suite.keep_alive_parent_end.poll():
- wrapped_testcase_suite.last_test, \
- wrapped_testcase_suite.last_test_vpp_binary, \
- wrapped_testcase_suite.last_test_temp_dir, \
- wrapped_testcase_suite.vpp_pid = \
- wrapped_testcase_suite.keep_alive_parent_end.recv()
+ (
+ wrapped_testcase_suite.last_test,
+ wrapped_testcase_suite.last_test_vpp_binary,
+ wrapped_testcase_suite.last_test_temp_dir,
+ wrapped_testcase_suite.vpp_pid,
+ ) = wrapped_testcase_suite.keep_alive_parent_end.recv()
wrapped_testcase_suite.last_heard = time.time()
if wrapped_testcase_suite.finished_parent_end.poll():
wrapped_testcase_suite.finished_parent_end.recv()
wrapped_testcase_suite.last_heard = time.time()
- stop_run = process_finished_testsuite(
- wrapped_testcase_suite,
- finished_testcase_suites,
- failed_wrapped_testcases,
- results) or stop_run
+ stop_run = (
+ process_finished_testsuite(
+ wrapped_testcase_suite,
+ finished_testcase_suites,
+ failed_wrapped_testcases,
+ results,
+ )
+ or stop_run
+ )
continue
fail = False
- if wrapped_testcase_suite.last_heard + config.timeout < \
- time.time():
+ if wrapped_testcase_suite.last_heard + config.timeout < time.time():
fail = True
wrapped_testcase_suite.logger.critical(
"Child test runner process timed out "
- "(last test running was `%s' in `%s')!" %
- (wrapped_testcase_suite.last_test,
- wrapped_testcase_suite.last_test_temp_dir))
+ "(last test running was `%s' in `%s')!"
+ % (
+ wrapped_testcase_suite.last_test,
+ wrapped_testcase_suite.last_test_temp_dir,
+ )
+ )
elif not wrapped_testcase_suite.child.is_alive():
fail = True
wrapped_testcase_suite.logger.critical(
"Child test runner process unexpectedly died "
- "(last test running was `%s' in `%s')!" %
- (wrapped_testcase_suite.last_test,
- wrapped_testcase_suite.last_test_temp_dir))
- elif wrapped_testcase_suite.last_test_temp_dir and \
- wrapped_testcase_suite.last_test_vpp_binary:
- if is_core_present(
- wrapped_testcase_suite.last_test_temp_dir):
+ "(last test running was `%s' in `%s')!"
+ % (
+ wrapped_testcase_suite.last_test,
+ wrapped_testcase_suite.last_test_temp_dir,
+ )
+ )
+ elif (
+ wrapped_testcase_suite.last_test_temp_dir
+ and wrapped_testcase_suite.last_test_vpp_binary
+ ):
+ if is_core_present(wrapped_testcase_suite.last_test_temp_dir):
wrapped_testcase_suite.add_testclass_with_core()
if wrapped_testcase_suite.core_detected_at is None:
- wrapped_testcase_suite.core_detected_at = \
- time.time()
- elif wrapped_testcase_suite.core_detected_at + \
- core_timeout < time.time():
+ wrapped_testcase_suite.core_detected_at = time.time()
+ elif (
+ wrapped_testcase_suite.core_detected_at + core_timeout
+ < time.time()
+ ):
wrapped_testcase_suite.logger.critical(
"Child test runner process unresponsive and "
"core-file exists in test temporary directory "
- "(last test running was `%s' in `%s')!" %
- (wrapped_testcase_suite.last_test,
- wrapped_testcase_suite.last_test_temp_dir))
+ "(last test running was `%s' in `%s')!"
+ % (
+ wrapped_testcase_suite.last_test,
+ wrapped_testcase_suite.last_test_temp_dir,
+ )
+ )
fail = True
if fail:
@@ -461,19 +514,23 @@ def run_forked(testcase_suites):
# terminating the child process tends to leave orphan
# VPP process around
if wrapped_testcase_suite.vpp_pid:
- os.kill(wrapped_testcase_suite.vpp_pid,
- signal.SIGTERM)
+ os.kill(wrapped_testcase_suite.vpp_pid, signal.SIGTERM)
except OSError:
# already dead
pass
wrapped_testcase_suite.result.crashed = True
wrapped_testcase_suite.result.process_result(
- wrapped_testcase_suite.last_test_id, ERROR)
- stop_run = process_finished_testsuite(
- wrapped_testcase_suite,
- finished_testcase_suites,
- failed_wrapped_testcases,
- results) or stop_run
+ wrapped_testcase_suite.last_test_id, ERROR
+ )
+ stop_run = (
+ process_finished_testsuite(
+ wrapped_testcase_suite,
+ finished_testcase_suites,
+ failed_wrapped_testcases,
+ results,
+ )
+ or stop_run
+ )
for finished_testcase in finished_testcase_suites:
# Somewhat surprisingly, the join below may
@@ -484,9 +541,9 @@ def run_forked(testcase_suites):
join_end = time.time()
if join_end - join_start >= test_finished_join_timeout:
finished_testcase.logger.error(
- "Timeout joining finished test: %s (pid %d)" %
- (finished_testcase.last_test,
- finished_testcase.child.pid))
+ "Timeout joining finished test: %s (pid %d)"
+ % (finished_testcase.last_test, finished_testcase.child.pid)
+ )
finished_testcase.close_pipes()
wrapped_testcase_suites.remove(finished_testcase)
finished_unread_testcases.add(finished_testcase)
@@ -548,7 +605,7 @@ class TestSuiteWrapper(unittest.TestSuite):
class SplitToSuitesCallback:
def __init__(self, filter_callback):
self.suites = {}
- self.suite_name = 'default'
+ self.suite_name = "default"
self.filter_callback = filter_callback
self.filtered = TestSuiteWrapper()
@@ -573,28 +630,27 @@ def parse_test_filter(test_filter):
filter_class_name = None
filter_func_name = None
if f:
- if '.' in f:
- parts = f.split('.')
+ if "." in f:
+ parts = f.split(".")
if len(parts) > 3:
- raise Exception("Unrecognized %s option: %s" %
- (test_option, f))
+ raise Exception("Unrecognized %s option: %s" % (test_option, f))
if len(parts) > 2:
- if parts[2] not in ('*', ''):
+ if parts[2] not in ("*", ""):
filter_func_name = parts[2]
- if parts[1] not in ('*', ''):
+ if parts[1] not in ("*", ""):
filter_class_name = parts[1]
- if parts[0] not in ('*', ''):
- if parts[0].startswith('test_'):
+ if parts[0] not in ("*", ""):
+ if parts[0].startswith("test_"):
filter_file_name = parts[0]
else:
- filter_file_name = 'test_%s' % parts[0]
+ filter_file_name = "test_%s" % parts[0]
else:
- if f.startswith('test_'):
+ if f.startswith("test_"):
filter_file_name = f
else:
- filter_file_name = 'test_%s' % f
+ filter_file_name = "test_%s" % f
if filter_file_name:
- filter_file_name = '%s.py' % filter_file_name
+ filter_file_name = "%s.py" % filter_file_name
return filter_file_name, filter_class_name, filter_func_name
@@ -608,7 +664,7 @@ def filter_tests(tests, filter_cb):
result.addTest(x)
elif isinstance(t, unittest.TestCase):
# this is a single test
- parts = t.id().split('.')
+ parts = t.id().split(".")
# t.id() for common cases like this:
# test_classifier.TestClassifier.test_acl_ip
# apply filtering only if it is so
@@ -645,11 +701,11 @@ class FilterByClassList:
self.classes_with_filenames = classes_with_filenames
def __call__(self, file_name, class_name, func_name):
- return '.'.join([file_name, class_name]) in self.classes_with_filenames
+ return ".".join([file_name, class_name]) in self.classes_with_filenames
def suite_from_failed(suite, failed):
- failed = {x.rsplit('.', 1)[0] for x in failed}
+ failed = {x.rsplit(".", 1)[0] for x in failed}
filter_cb = FilterByClassList(failed)
suite = filter_tests(suite, filter_cb)
return suite
@@ -695,9 +751,9 @@ class AllResults(dict):
return retval
def print_results(self):
- print('')
+ print("")
print(double_line_delim)
- print('TEST RESULTS:')
+ print("TEST RESULTS:")
def indent_results(lines):
lines = list(filter(None, lines))
@@ -707,62 +763,86 @@ class AllResults(dict):
padding = " " * (maximum - l.index(":"))
print(f"{padding}{l}")
- indent_results([
- f'Scheduled tests: {self.all_testcases}',
- f'Executed tests: {self[TEST_RUN]}',
- f'Passed tests: {colorize(self[PASS], GREEN)}',
- f'Skipped tests: {colorize(self[SKIP], YELLOW)}'
- if self[SKIP] else None,
- f'Not Executed tests: {colorize(self.not_executed, RED)}'
- if self.not_executed else None,
- f'Failures: {colorize(self[FAIL], RED)}' if self[FAIL] else None,
- f'Errors: {colorize(self[ERROR], RED)}' if self[ERROR] else None,
- 'Tests skipped due to lack of CPUS: '
- f'{colorize(self[SKIP_CPU_SHORTAGE], YELLOW)}'
- if self[SKIP_CPU_SHORTAGE] else None
- ])
+ indent_results(
+ [
+ f"Scheduled tests: {self.all_testcases}",
+ f"Executed tests: {self[TEST_RUN]}",
+ f"Passed tests: {colorize(self[PASS], GREEN)}",
+ f"Skipped tests: {colorize(self[SKIP], YELLOW)}"
+ if self[SKIP]
+ else None,
+ f"Not Executed tests: {colorize(self.not_executed, RED)}"
+ if self.not_executed
+ else None,
+ f"Failures: {colorize(self[FAIL], RED)}" if self[FAIL] else None,
+ f"Errors: {colorize(self[ERROR], RED)}" if self[ERROR] else None,
+ "Tests skipped due to lack of CPUS: "
+ f"{colorize(self[SKIP_CPU_SHORTAGE], YELLOW)}"
+ if self[SKIP_CPU_SHORTAGE]
+ else None,
+ ]
+ )
if self.all_failed > 0:
- print('FAILURES AND ERRORS IN TESTS:')
+ print("FAILURES AND ERRORS IN TESTS:")
for result in self.results_per_suite:
failed_testcase_ids = result[FAIL]
errored_testcase_ids = result[ERROR]
old_testcase_name = None
if failed_testcase_ids:
for failed_test_id in failed_testcase_ids:
- new_testcase_name, test_name = \
- result.get_testcase_names(failed_test_id)
+ new_testcase_name, test_name = result.get_testcase_names(
+ failed_test_id
+ )
if new_testcase_name != old_testcase_name:
- print(' Testcase name: {}'.format(
- colorize(new_testcase_name, RED)))
+ print(
+ " Testcase name: {}".format(
+ colorize(new_testcase_name, RED)
+ )
+ )
old_testcase_name = new_testcase_name
- print(' FAILURE: {} [{}]'.format(
- colorize(test_name, RED), failed_test_id))
+ print(
+ " FAILURE: {} [{}]".format(
+ colorize(test_name, RED), failed_test_id
+ )
+ )
if errored_testcase_ids:
for errored_test_id in errored_testcase_ids:
- new_testcase_name, test_name = \
- result.get_testcase_names(errored_test_id)
+ new_testcase_name, test_name = result.get_testcase_names(
+ errored_test_id
+ )
if new_testcase_name != old_testcase_name:
- print(' Testcase name: {}'.format(
- colorize(new_testcase_name, RED)))
+ print(
+ " Testcase name: {}".format(
+ colorize(new_testcase_name, RED)
+ )
+ )
old_testcase_name = new_testcase_name
- print(' ERROR: {} [{}]'.format(
- colorize(test_name, RED), errored_test_id))
+ print(
+ " ERROR: {} [{}]".format(
+ colorize(test_name, RED), errored_test_id
+ )
+ )
if self.testsuites_no_tests_run:
- print('TESTCASES WHERE NO TESTS WERE SUCCESSFULLY EXECUTED:')
+ print("TESTCASES WHERE NO TESTS WERE SUCCESSFULLY EXECUTED:")
tc_classes = set()
for testsuite in self.testsuites_no_tests_run:
for testcase in testsuite:
tc_classes.add(get_testcase_doc_name(testcase))
for tc_class in tc_classes:
- print(' {}'.format(colorize(tc_class, RED)))
+ print(" {}".format(colorize(tc_class, RED)))
if self[SKIP_CPU_SHORTAGE]:
print()
- print(colorize(' SOME TESTS WERE SKIPPED BECAUSE THERE ARE NOT'
- ' ENOUGH CPUS AVAILABLE', YELLOW))
+ print(
+ colorize(
+ " SOME TESTS WERE SKIPPED BECAUSE THERE ARE NOT"
+ " ENOUGH CPUS AVAILABLE",
+ YELLOW,
+ )
+ )
print(double_line_delim)
- print('')
+ print("")
@property
def not_executed(self):
@@ -805,7 +885,7 @@ def parse_results(results):
return return_code, results_per_suite.rerun
-if __name__ == '__main__':
+if __name__ == "__main__":
print(f"Config is: {config}")
@@ -831,35 +911,41 @@ if __name__ == '__main__':
print(f"OS reports {num_cpus} available cpu(s).")
test_jobs = config.jobs
- if test_jobs == 'auto':
+ if test_jobs == "auto":
if run_interactive:
max_concurrent_tests = 1
- print('Interactive mode required, running tests consecutively.')
+ print("Interactive mode required, running tests consecutively.")
else:
max_concurrent_tests = num_cpus
- print(f"Running at most {max_concurrent_tests} python test "
- "processes concurrently.")
+ print(
+ f"Running at most {max_concurrent_tests} python test "
+ "processes concurrently."
+ )
else:
max_concurrent_tests = test_jobs
- print(f"Running at most {max_concurrent_tests} python test processes "
- "concurrently as set by 'TEST_JOBS'.")
+ print(
+ f"Running at most {max_concurrent_tests} python test processes "
+ "concurrently as set by 'TEST_JOBS'."
+ )
print(f"Using at most {max_vpp_cpus} cpus for VPP threads.")
if run_interactive and max_concurrent_tests > 1:
raise NotImplementedError(
- 'Running tests interactively (DEBUG is gdb[server] or ATTACH or '
- 'STEP is set) in parallel (TEST_JOBS is more than 1) is not '
- 'supported')
+ "Running tests interactively (DEBUG is gdb[server] or ATTACH or "
+ "STEP is set) in parallel (TEST_JOBS is more than 1) is not "
+ "supported"
+ )
descriptions = True
print("Running tests using custom test runner.")
- filter_file, filter_class, filter_func = \
- parse_test_filter(config.filter)
+ filter_file, filter_class, filter_func = parse_test_filter(config.filter)
- print("Selected filters: file=%s, class=%s, function=%s" % (
- filter_file, filter_class, filter_func))
+ print(
+ "Selected filters: file=%s, class=%s, function=%s"
+ % (filter_file, filter_class, filter_func)
+ )
filter_cb = FilterByTestOption(filter_file, filter_class, filter_func)
@@ -882,17 +968,19 @@ if __name__ == '__main__':
# in stopTest() (for that to trigger, test function must run)
for t in testcase_suite:
for m in dir(t):
- if m.startswith('test_'):
+ if m.startswith("test_"):
setattr(t, m, lambda: t.skipTest("not enough cpus"))
- setattr(t.__class__, 'setUpClass', lambda: None)
- setattr(t.__class__, 'tearDownClass', lambda: None)
- setattr(t, 'setUp', lambda: None)
- setattr(t, 'tearDown', lambda: None)
+ setattr(t.__class__, "setUpClass", lambda: None)
+ setattr(t.__class__, "tearDownClass", lambda: None)
+ setattr(t, "setUp", lambda: None)
+ setattr(t, "tearDown", lambda: None)
t.__class__.skipped_due_to_cpu_lack = True
suites.append(testcase_suite)
- print("%s out of %s tests match specified filters" % (
- tests_amount, tests_amount + cb.filtered.countTestCases()))
+ print(
+ "%s out of %s tests match specified filters"
+ % (tests_amount, tests_amount + cb.filtered.countTestCases())
+ )
if not config.extended:
print("Not running extended tests (some tests will be skipped)")
@@ -903,49 +991,60 @@ if __name__ == '__main__':
if run_interactive and suites:
# don't fork if requiring interactive terminal
- print('Running tests in foreground in the current process')
+ print("Running tests in foreground in the current process")
full_suite = unittest.TestSuite()
free_cpus = list(available_cpus)
cpu_shortage = False
for suite in suites:
if suite.cpus_used <= max_vpp_cpus:
- suite.assign_cpus(free_cpus[:suite.cpus_used])
+ suite.assign_cpus(free_cpus[: suite.cpus_used])
else:
suite.assign_cpus([])
cpu_shortage = True
full_suite.addTests(suites)
- result = VppTestRunner(verbosity=config.verbose,
- failfast=config.failfast,
- print_summary=True).run(full_suite)
+ result = VppTestRunner(
+ verbosity=config.verbose, failfast=config.failfast, print_summary=True
+ ).run(full_suite)
was_successful = result.wasSuccessful()
if not was_successful:
for test_case_info in result.failed_test_cases_info:
- handle_failed_suite(test_case_info.logger,
- test_case_info.tempdir,
- test_case_info.vpp_pid,
- config.vpp)
+ handle_failed_suite(
+ test_case_info.logger,
+ test_case_info.tempdir,
+ test_case_info.vpp_pid,
+ config.vpp,
+ )
if test_case_info in result.core_crash_test_cases_info:
- check_and_handle_core(test_case_info.vpp_bin_path,
- test_case_info.tempdir,
- test_case_info.core_crash_test)
+ check_and_handle_core(
+ test_case_info.vpp_bin_path,
+ test_case_info.tempdir,
+ test_case_info.core_crash_test,
+ )
if cpu_shortage:
print()
- print(colorize('SOME TESTS WERE SKIPPED BECAUSE THERE ARE NOT'
- ' ENOUGH CPUS AVAILABLE', YELLOW))
+ print(
+ colorize(
+ "SOME TESTS WERE SKIPPED BECAUSE THERE ARE NOT"
+ " ENOUGH CPUS AVAILABLE",
+ YELLOW,
+ )
+ )
print()
sys.exit(not was_successful)
else:
- print('Running each VPPTestCase in a separate background process'
- f' with at most {max_concurrent_tests} parallel python test '
- 'process(es)')
+ print(
+ "Running each VPPTestCase in a separate background process"
+ f" with at most {max_concurrent_tests} parallel python test "
+ "process(es)"
+ )
exit_code = 0
while suites and attempts > 0:
results = run_forked(suites)
exit_code, suites = parse_results(results)
attempts -= 1
if exit_code == 0:
- print('Test run was successful')
+ print("Test run was successful")
else:
- print('%s attempt(s) left.' % attempts)
+ print("%s attempt(s) left." % attempts)
sys.exit(exit_code)
diff --git a/test/sanity_run_vpp.py b/test/sanity_run_vpp.py
index b923c791b61..5e2b3c1f92b 100644
--- a/test/sanity_run_vpp.py
+++ b/test/sanity_run_vpp.py
@@ -8,7 +8,8 @@ from framework import VppDiedError, VppTestCase, KeepAliveReporter
class SanityTestCase(VppTestCase):
- """ Sanity test case - verify whether VPP is able to start """
+ """Sanity test case - verify whether VPP is able to start"""
+
cpus = [0]
# don't ask to debug SanityTestCase
@@ -43,11 +44,11 @@ def main():
y.close()
if rc == 0:
- print('Sanity test case passed.')
+ print("Sanity test case passed.")
else:
- print('Sanity test case failed.')
+ print("Sanity test case failed.")
return rc
-if __name__ == '__main__':
+if __name__ == "__main__":
sys.exit(main())
diff --git a/test/template_bd.py b/test/template_bd.py
index bebe76d765d..55aaa5a8f4c 100644
--- a/test/template_bd.py
+++ b/test/template_bd.py
@@ -8,51 +8,55 @@ from scapy.layers.inet import IP, UDP
class BridgeDomain(metaclass=abc.ABCMeta):
- """ Bridge domain abstraction """
+ """Bridge domain abstraction"""
@property
def frame_request(self):
- """ Ethernet frame modeling a generic request """
- return (Ether(src='00:00:00:00:00:01', dst='00:00:00:00:00:02') /
- IP(src='1.2.3.4', dst='4.3.2.1') /
- UDP(sport=10000, dport=20000) /
- Raw('\xa5' * 100))
+ """Ethernet frame modeling a generic request"""
+ return (
+ Ether(src="00:00:00:00:00:01", dst="00:00:00:00:00:02")
+ / IP(src="1.2.3.4", dst="4.3.2.1")
+ / UDP(sport=10000, dport=20000)
+ / Raw("\xa5" * 100)
+ )
@property
def frame_reply(self):
- """ Ethernet frame modeling a generic reply """
- return (Ether(src='00:00:00:00:00:02', dst='00:00:00:00:00:01') /
- IP(src='4.3.2.1', dst='1.2.3.4') /
- UDP(sport=20000, dport=10000) /
- Raw('\xa5' * 100))
+ """Ethernet frame modeling a generic reply"""
+ return (
+ Ether(src="00:00:00:00:00:02", dst="00:00:00:00:00:01")
+ / IP(src="4.3.2.1", dst="1.2.3.4")
+ / UDP(sport=20000, dport=10000)
+ / Raw("\xa5" * 100)
+ )
@abc.abstractmethod
def ip_range(self, start, end):
- """ range of remote ip's """
+ """range of remote ip's"""
pass
@abc.abstractmethod
def encap_mcast(self, pkt, src_ip, src_mac, vni):
- """ Encapsulate mcast packet """
+ """Encapsulate mcast packet"""
pass
@abc.abstractmethod
def encapsulate(self, pkt, vni):
- """ Encapsulate packet """
+ """Encapsulate packet"""
pass
@abc.abstractmethod
def decapsulate(self, pkt):
- """ Decapsulate packet """
+ """Decapsulate packet"""
pass
@abc.abstractmethod
def check_encapsulation(self, pkt, vni, local_only=False):
- """ Verify the encapsulation """
+ """Verify the encapsulation"""
pass
def assert_eq_pkts(self, pkt1, pkt2):
- """ Verify the Ether, IP, UDP, payload are equal in both
+ """Verify the Ether, IP, UDP, payload are equal in both
packets
"""
self.assertEqual(pkt1[Ether].src, pkt2[Ether].src)
@@ -64,15 +68,18 @@ class BridgeDomain(metaclass=abc.ABCMeta):
self.assertEqual(pkt1[Raw], pkt2[Raw])
def test_decap(self):
- """ Decapsulation test
+ """Decapsulation test
Send encapsulated frames from pg0
Verify receipt of decapsulated frames on pg1
"""
- encapsulated_pkt = self.encapsulate(self.frame_request,
- self.single_tunnel_vni)
+ encapsulated_pkt = self.encapsulate(self.frame_request, self.single_tunnel_vni)
- self.pg0.add_stream([encapsulated_pkt, ])
+ self.pg0.add_stream(
+ [
+ encapsulated_pkt,
+ ]
+ )
self.pg1.enable_capture()
@@ -85,7 +92,7 @@ class BridgeDomain(metaclass=abc.ABCMeta):
self.assert_eq_pkts(pkt, self.frame_request)
def test_encap(self):
- """ Encapsulation test
+ """Encapsulation test
Send frames from pg1
Verify receipt of encapsulated frames on pg0
"""
@@ -104,7 +111,7 @@ class BridgeDomain(metaclass=abc.ABCMeta):
self.assert_eq_pkts(payload, self.frame_reply)
def test_ucast_flood(self):
- """ Unicast flood test
+ """Unicast flood test
Send frames from pg3
Verify receipt of encapsulated frames on pg0
"""
@@ -122,7 +129,7 @@ class BridgeDomain(metaclass=abc.ABCMeta):
self.assert_eq_pkts(payload, self.frame_reply)
def test_mcast_flood(self):
- """ Multicast flood test
+ """Multicast flood test
Send frames from pg2
Verify receipt of encapsulated frames on pg0
"""
@@ -135,14 +142,15 @@ class BridgeDomain(metaclass=abc.ABCMeta):
# Pick first received frame and check if it's correctly encapsulated.
out = self.pg0.get_capture(1)
pkt = out[0]
- self.check_encapsulation(pkt, self.mcast_flood_bd,
- local_only=False, mcast_pkt=True)
+ self.check_encapsulation(
+ pkt, self.mcast_flood_bd, local_only=False, mcast_pkt=True
+ )
payload = self.decapsulate(pkt)
self.assert_eq_pkts(payload, self.frame_reply)
def test_mcast_rcv(self):
- """ Multicast receive test
+ """Multicast receive test
Send 20 encapsulated frames from pg0 only 10 match unicast tunnels
Verify receipt of 10 decap frames on pg2
"""
@@ -151,7 +159,8 @@ class BridgeDomain(metaclass=abc.ABCMeta):
ip_range_end = 30
mcast_stream = [
self.encap_mcast(self.frame_request, ip, mac, self.mcast_flood_bd)
- for ip in self.ip_range(ip_range_start, ip_range_end)]
+ for ip in self.ip_range(ip_range_start, ip_range_end)
+ ]
self.pg0.add_stream(mcast_stream)
self.pg2.enable_capture()
self.pg_start()
diff --git a/test/template_classifier.py b/test/template_classifier.py
index 7ce69d436f5..ec2a4143eec 100644
--- a/test/template_classifier.py
+++ b/test/template_classifier.py
@@ -30,13 +30,11 @@ class VarMatch:
class TestClassifier(VppTestCase):
-
@staticmethod
def _resolve_mask_match(mask_match):
mask_match = binascii.unhexlify(mask_match)
mask_match_len = ((len(mask_match) - 1) // 16 + 1) * 16
- mask_match = mask_match + b'\0' * \
- (mask_match_len - len(mask_match))
+ mask_match = mask_match + b"\0" * (mask_match_len - len(mask_match))
return mask_match, mask_match_len
@classmethod
@@ -47,7 +45,7 @@ class TestClassifier(VppTestCase):
variables and configure VPP.
"""
super(TestClassifier, cls).setUpClass()
- cls.acl_active_table = ''
+ cls.acl_active_table = ""
cls.af = AF_INET
def setUp(self):
@@ -113,13 +111,15 @@ class TestClassifier(VppTestCase):
self.logger.info(self.vapi.cli("show ip fib"))
self.logger.info(self.vapi.cli("show error"))
- if self.acl_active_table.endswith('out'):
+ if self.acl_active_table.endswith("out"):
self.output_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0)
- elif self.acl_active_table != '':
+ self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0
+ )
+ elif self.acl_active_table != "":
self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0)
- self.acl_active_table = ''
+ self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0
+ )
+ self.acl_active_table = ""
for intf in self.interfaces:
if self.af == AF_INET:
@@ -131,7 +131,7 @@ class TestClassifier(VppTestCase):
super(TestClassifier, self).tearDown()
@staticmethod
- def build_mac_match(dst_mac='', src_mac='', ether_type=''):
+ def build_mac_match(dst_mac="", src_mac="", ether_type=""):
"""Build MAC ACL match data with hexstring format.
:param str dst_mac: source MAC address <x:x:x:x:x:x>
@@ -139,15 +139,16 @@ class TestClassifier(VppTestCase):
:param str ether_type: ethernet type <0-ffff>
"""
if dst_mac:
- dst_mac = dst_mac.replace(':', '')
+ dst_mac = dst_mac.replace(":", "")
if src_mac:
- src_mac = src_mac.replace(':', '')
+ src_mac = src_mac.replace(":", "")
- return ('{!s:0>12}{!s:0>12}{!s:0>4}'.format(
- dst_mac, src_mac, ether_type)).rstrip()
+ return (
+ "{!s:0>12}{!s:0>12}{!s:0>4}".format(dst_mac, src_mac, ether_type)
+ ).rstrip()
@staticmethod
- def build_mac_mask(dst_mac='', src_mac='', ether_type=''):
+ def build_mac_mask(dst_mac="", src_mac="", ether_type=""):
"""Build MAC ACL mask data with hexstring format.
:param str dst_mac: source MAC address <0-ffffffffffff>
@@ -155,12 +156,12 @@ class TestClassifier(VppTestCase):
:param str ether_type: ethernet type <0-ffff>
"""
- return ('{!s:0>12}{!s:0>12}{!s:0>4}'.format(
- dst_mac, src_mac, ether_type)).rstrip()
+ return (
+ "{!s:0>12}{!s:0>12}{!s:0>4}".format(dst_mac, src_mac, ether_type)
+ ).rstrip()
@staticmethod
- def build_ip_mask(proto='', src_ip='', dst_ip='',
- src_port='', dst_port=''):
+ def build_ip_mask(proto="", src_ip="", dst_ip="", src_port="", dst_port=""):
"""Build IP ACL mask data with hexstring format.
:param str proto: protocol number <0-ff>
@@ -170,12 +171,14 @@ class TestClassifier(VppTestCase):
:param str dst_port: destination port number <0-ffff>
"""
- return ('{!s:0>20}{!s:0>12}{!s:0>8}{!s:0>4}{!s:0>4}'.format(
- proto, src_ip, dst_ip, src_port, dst_port)).rstrip('0')
+ return (
+ "{!s:0>20}{!s:0>12}{!s:0>8}{!s:0>4}{!s:0>4}".format(
+ proto, src_ip, dst_ip, src_port, dst_port
+ )
+ ).rstrip("0")
@staticmethod
- def build_ip6_mask(nh='', src_ip='', dst_ip='',
- src_port='', dst_port=''):
+ def build_ip6_mask(nh="", src_ip="", dst_ip="", src_port="", dst_port=""):
"""Build IPv6 ACL mask data with hexstring format.
:param str nh: next header number <0-ff>
@@ -185,24 +188,26 @@ class TestClassifier(VppTestCase):
:param str dst_port: destination port number <0-ffff>
"""
- return ('{!s:0>14}{!s:0>34}{!s:0>32}{!s:0>4}{!s:0>4}'.format(
- nh, src_ip, dst_ip, src_port, dst_port)).rstrip('0')
+ return (
+ "{!s:0>14}{!s:0>34}{!s:0>32}{!s:0>4}{!s:0>4}".format(
+ nh, src_ip, dst_ip, src_port, dst_port
+ )
+ ).rstrip("0")
@staticmethod
def build_payload_mask(masks):
- payload_mask = ''
+ payload_mask = ""
for mask in masks:
# offset is specified in bytes, convert to hex format.
length = (mask.offset * 2) + len(mask.spec)
- format_spec = '{!s:0>' + str(length) + '}'
+ format_spec = "{!s:0>" + str(length) + "}"
payload_mask += format_spec.format(mask.spec)
- return payload_mask.rstrip('0')
+ return payload_mask.rstrip("0")
@staticmethod
- def build_ip_match(proto=0, src_ip='', dst_ip='',
- src_port=0, dst_port=0):
+ def build_ip_match(proto=0, src_ip="", dst_ip="", src_port=0, dst_port=0):
"""Build IP ACL match data with hexstring format.
:param int proto: protocol number with valid option "x"
@@ -212,17 +217,18 @@ class TestClassifier(VppTestCase):
:param int dst_port: destination port number "x"
"""
if src_ip:
- src_ip = binascii.hexlify(socket.inet_aton(src_ip)).decode('ascii')
+ src_ip = binascii.hexlify(socket.inet_aton(src_ip)).decode("ascii")
if dst_ip:
- dst_ip = binascii.hexlify(socket.inet_aton(dst_ip)).decode('ascii')
+ dst_ip = binascii.hexlify(socket.inet_aton(dst_ip)).decode("ascii")
- return ('{!s:0>20}{!s:0>12}{!s:0>8}{!s:0>4}{!s:0>4}'.format(
- hex(proto)[2:], src_ip, dst_ip, hex(src_port)[2:],
- hex(dst_port)[2:])).rstrip('0')
+ return (
+ "{!s:0>20}{!s:0>12}{!s:0>8}{!s:0>4}{!s:0>4}".format(
+ hex(proto)[2:], src_ip, dst_ip, hex(src_port)[2:], hex(dst_port)[2:]
+ )
+ ).rstrip("0")
@staticmethod
- def build_ip6_match(nh=0, src_ip='', dst_ip='',
- src_port=0, dst_port=0):
+ def build_ip6_match(nh=0, src_ip="", dst_ip="", src_port=0, dst_port=0):
"""Build IPv6 ACL match data with hexstring format.
:param int nh: next header number with valid option "x"
@@ -234,39 +240,44 @@ class TestClassifier(VppTestCase):
"""
if src_ip:
if sys.version_info[0] == 2:
- src_ip = binascii.hexlify(socket.inet_pton(
- socket.AF_INET6, src_ip))
+ src_ip = binascii.hexlify(socket.inet_pton(socket.AF_INET6, src_ip))
else:
src_ip = socket.inet_pton(socket.AF_INET6, src_ip).hex()
if dst_ip:
if sys.version_info[0] == 2:
- dst_ip = binascii.hexlify(socket.inet_pton(
- socket.AF_INET6, dst_ip))
+ dst_ip = binascii.hexlify(socket.inet_pton(socket.AF_INET6, dst_ip))
else:
dst_ip = socket.inet_pton(socket.AF_INET6, dst_ip).hex()
- return ('{!s:0>14}{!s:0>34}{!s:0>32}{!s:0>4}{!s:0>4}'.format(
- hex(nh)[2:], src_ip, dst_ip, hex(src_port)[2:],
- hex(dst_port)[2:])).rstrip('0')
+ return (
+ "{!s:0>14}{!s:0>34}{!s:0>32}{!s:0>4}{!s:0>4}".format(
+ hex(nh)[2:], src_ip, dst_ip, hex(src_port)[2:], hex(dst_port)[2:]
+ )
+ ).rstrip("0")
@staticmethod
def build_payload_match(matches):
- payload_match = ''
+ payload_match = ""
for match in matches:
sval = str(hex(match.value)[2:])
# offset is specified in bytes, convert to hex format.
length = (match.offset + match.length) * 2
- format_spec = '{!s:0>' + str(length) + '}'
+ format_spec = "{!s:0>" + str(length) + "}"
payload_match += format_spec.format(sval)
- return payload_match.rstrip('0')
+ return payload_match.rstrip("0")
- def create_stream(self, src_if, dst_if, packet_sizes,
- proto_l=UDP(sport=1234, dport=5678),
- payload_ex=None):
+ def create_stream(
+ self,
+ src_if,
+ dst_if,
+ packet_sizes,
+ proto_l=UDP(sport=1234, dport=5678),
+ payload_ex=None,
+ ):
"""Create input packet stream for defined interfaces.
:param VppInterface src_if: Source Interface for packet stream.
@@ -285,15 +296,19 @@ class TestClassifier(VppTestCase):
payload += payload_ex
if self.af == AF_INET:
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4) /
- proto_l /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4)
+ / proto_l
+ / Raw(payload)
+ )
elif self.af == AF_INET6:
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IPv6(src=src_if.remote_ip6, dst=dst_if.remote_ip6) /
- proto_l /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IPv6(src=src_if.remote_ip6, dst=dst_if.remote_ip6)
+ / proto_l
+ / Raw(payload)
+ )
info.data = p.copy()
self.extend_packet(p, size)
pkts.append(p)
@@ -322,11 +337,12 @@ class TestClassifier(VppTestCase):
packet_index = payload_info.index
self.assertEqual(payload_info.dst, dst_sw_if_index)
self.logger.debug(
- "Got packet on port %s: src=%u (id=%u)" %
- (dst_if.name, payload_info.src, packet_index))
+ "Got packet on port %s: src=%u (id=%u)"
+ % (dst_if.name, payload_info.src, packet_index)
+ )
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
self.assertEqual(packet_index, next_info.index)
@@ -343,13 +359,15 @@ class TestClassifier(VppTestCase):
raise
for i in self.interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index])
- self.assertTrue(remaining_packet is None,
- "Interface %s: Packet expected from interface %s "
- "didn't arrive" % (dst_if.name, i.name))
-
- def create_classify_table(self, key, mask, data_offset=0,
- next_table_index=None):
+ i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]
+ )
+ self.assertTrue(
+ remaining_packet is None,
+ "Interface %s: Packet expected from interface %s "
+ "didn't arrive" % (dst_if.name, i.name),
+ )
+
+ def create_classify_table(self, key, mask, data_offset=0, next_table_index=None):
"""Create Classify Table
:param str key: key for classify table (ex, ACL name).
@@ -366,12 +384,14 @@ class TestClassifier(VppTestCase):
miss_next_index=0,
current_data_flag=1,
current_data_offset=data_offset,
- next_table_index=next_table_index)
- self.assertIsNotNone(r, 'No response msg for add_del_table')
+ next_table_index=next_table_index,
+ )
+ self.assertIsNotNone(r, "No response msg for add_del_table")
self.acl_tbl_idx[key] = r.new_table_index
- def create_classify_session(self, table_index, match, pbr_option=0,
- vrfid=0, is_add=1):
+ def create_classify_session(
+ self, table_index, match, pbr_option=0, vrfid=0, is_add=1
+ ):
"""Create Classify Session
:param int table_index: table index to identify classify table.
@@ -389,8 +409,9 @@ class TestClassifier(VppTestCase):
match_len=mask_match_len,
opaque_index=0,
action=pbr_option,
- metadata=vrfid)
- self.assertIsNotNone(r, 'No response msg for add_del_session')
+ metadata=vrfid,
+ )
+ self.assertIsNotNone(r, "No response msg for add_del_session")
def input_acl_set_interface(self, intf, table_index, is_add=1):
"""Configure Input ACL interface
@@ -403,20 +424,17 @@ class TestClassifier(VppTestCase):
r = None
if self.af == AF_INET:
r = self.vapi.input_acl_set_interface(
- is_add,
- intf.sw_if_index,
- ip4_table_index=table_index)
+ is_add, intf.sw_if_index, ip4_table_index=table_index
+ )
elif self.af == AF_INET6:
r = self.vapi.input_acl_set_interface(
- is_add,
- intf.sw_if_index,
- ip6_table_index=table_index)
+ is_add, intf.sw_if_index, ip6_table_index=table_index
+ )
else:
r = self.vapi.input_acl_set_interface(
- is_add,
- intf.sw_if_index,
- l2_table_index=table_index)
- self.assertIsNotNone(r, 'No response msg for acl_set_interface')
+ is_add, intf.sw_if_index, l2_table_index=table_index
+ )
+ self.assertIsNotNone(r, "No response msg for acl_set_interface")
def output_acl_set_interface(self, intf, table_index, is_add=1):
"""Configure Output ACL interface
@@ -429,20 +447,17 @@ class TestClassifier(VppTestCase):
r = None
if self.af == AF_INET:
r = self.vapi.output_acl_set_interface(
- is_add,
- intf.sw_if_index,
- ip4_table_index=table_index)
+ is_add, intf.sw_if_index, ip4_table_index=table_index
+ )
elif self.af == AF_INET6:
r = self.vapi.output_acl_set_interface(
- is_add,
- intf.sw_if_index,
- ip6_table_index=table_index)
+ is_add, intf.sw_if_index, ip6_table_index=table_index
+ )
else:
r = self.vapi.output_acl_set_interface(
- is_add,
- intf.sw_if_index,
- l2_table_index=table_index)
- self.assertIsNotNone(r, 'No response msg for acl_set_interface')
+ is_add, intf.sw_if_index, l2_table_index=table_index
+ )
+ self.assertIsNotNone(r, "No response msg for acl_set_interface")
def config_pbr_fib_entry(self, intf, is_add=1):
"""Configure fib entry to route traffic toward PBR VRF table
@@ -451,10 +466,13 @@ class TestClassifier(VppTestCase):
"""
addr_len = 24
- self.vapi.ip_add_del_route(dst_address=intf.local_ip4,
- dst_address_length=addr_len,
- next_hop_address=intf.remote_ip4,
- table_id=self.pbr_vrfid, is_add=is_add)
+ self.vapi.ip_add_del_route(
+ dst_address=intf.local_ip4,
+ dst_address_length=addr_len,
+ next_hop_address=intf.remote_ip4,
+ table_id=self.pbr_vrfid,
+ is_add=is_add,
+ )
def verify_vrf(self, vrf_id):
"""
diff --git a/test/template_ipsec.py b/test/template_ipsec.py
index 8105f0ca52d..578c284f72e 100644
--- a/test/template_ipsec.py
+++ b/test/template_ipsec.py
@@ -6,16 +6,20 @@ from scapy.layers.inet import IP, ICMP, TCP, UDP
from scapy.layers.ipsec import SecurityAssociation, ESP
from scapy.layers.l2 import Ether
from scapy.packet import raw, Raw
-from scapy.layers.inet6 import IPv6, ICMPv6EchoRequest, IPv6ExtHdrHopByHop, \
- IPv6ExtHdrFragment, IPv6ExtHdrDestOpt
+from scapy.layers.inet6 import (
+ IPv6,
+ ICMPv6EchoRequest,
+ IPv6ExtHdrHopByHop,
+ IPv6ExtHdrFragment,
+ IPv6ExtHdrDestOpt,
+)
from framework import VppTestCase, VppTestRunner
from util import ppp, reassemble4, fragment_rfc791, fragment_rfc8200
from vpp_papi import VppEnum
-from vpp_ipsec import VppIpsecSpd, VppIpsecSpdEntry, \
- VppIpsecSpdItfBinding
+from vpp_ipsec import VppIpsecSpd, VppIpsecSpdEntry, VppIpsecSpdItfBinding
from ipaddress import ip_address
from re import search
from os import popen
@@ -30,8 +34,8 @@ class IPsecIPv4Params:
is_ipv6 = 0
def __init__(self):
- self.remote_tun_if_host = '1.1.1.1'
- self.remote_tun_if_host6 = '1111::1'
+ self.remote_tun_if_host = "1.1.1.1"
+ self.remote_tun_if_host6 = "1111::1"
self.scapy_tun_sa_id = 100
self.scapy_tun_spi = 1000
@@ -48,20 +52,23 @@ class IPsecIPv4Params:
self.outer_flow_label = 0
self.inner_flow_label = 0x12345
- self.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96)
- self.auth_algo = 'HMAC-SHA1-96' # scapy name
- self.auth_key = b'C91KUR9GYMm5GfkEvNjX'
-
- self.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CBC_128)
- self.crypt_algo = 'AES-CBC' # scapy name
- self.crypt_key = b'JPjyOWBeVEQiMe7h'
+ self.auth_algo_vpp_id = (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96
+ )
+ self.auth_algo = "HMAC-SHA1-96" # scapy name
+ self.auth_key = b"C91KUR9GYMm5GfkEvNjX"
+
+ self.crypt_algo_vpp_id = (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128
+ )
+ self.crypt_algo = "AES-CBC" # scapy name
+ self.crypt_key = b"JPjyOWBeVEQiMe7h"
self.salt = 0
self.flags = 0
self.nat_header = None
- self.tun_flags = (VppEnum.vl_api_tunnel_encap_decap_flags_t.
- TUNNEL_API_ENCAP_DECAP_FLAG_NONE)
+ self.tun_flags = (
+ VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_NONE
+ )
self.dscp = 0
self.async_mode = False
@@ -75,8 +82,8 @@ class IPsecIPv6Params:
is_ipv6 = 1
def __init__(self):
- self.remote_tun_if_host = '1111:1111:1111:1111:1111:1111:1111:1111'
- self.remote_tun_if_host4 = '1.1.1.1'
+ self.remote_tun_if_host = "1111:1111:1111:1111:1111:1111:1111:1111"
+ self.remote_tun_if_host4 = "1.1.1.1"
self.scapy_tun_sa_id = 500
self.scapy_tun_spi = 3001
@@ -93,20 +100,23 @@ class IPsecIPv6Params:
self.outer_flow_label = 0
self.inner_flow_label = 0x12345
- self.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96)
- self.auth_algo = 'HMAC-SHA1-96' # scapy name
- self.auth_key = b'C91KUR9GYMm5GfkEvNjX'
-
- self.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CBC_128)
- self.crypt_algo = 'AES-CBC' # scapy name
- self.crypt_key = b'JPjyOWBeVEQiMe7h'
+ self.auth_algo_vpp_id = (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96
+ )
+ self.auth_algo = "HMAC-SHA1-96" # scapy name
+ self.auth_key = b"C91KUR9GYMm5GfkEvNjX"
+
+ self.crypt_algo_vpp_id = (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128
+ )
+ self.crypt_algo = "AES-CBC" # scapy name
+ self.crypt_key = b"JPjyOWBeVEQiMe7h"
self.salt = 0
self.flags = 0
self.nat_header = None
- self.tun_flags = (VppEnum.vl_api_tunnel_encap_decap_flags_t.
- TUNNEL_API_ENCAP_DECAP_FLAG_NONE)
+ self.tun_flags = (
+ VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_NONE
+ )
self.dscp = 0
self.async_mode = False
@@ -120,36 +130,40 @@ def mk_scapy_crypt_key(p):
def config_tun_params(p, encryption_type, tun_if):
ip_class_by_addr_type = {socket.AF_INET: IP, socket.AF_INET6: IPv6}
- esn_en = bool(p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_USE_ESN))
+ esn_en = bool(
+ p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ESN)
+ )
p.tun_dst = tun_if.remote_addr[p.addr_type]
p.tun_src = tun_if.local_addr[p.addr_type]
crypt_key = mk_scapy_crypt_key(p)
p.scapy_tun_sa = SecurityAssociation(
- encryption_type, spi=p.vpp_tun_spi,
+ encryption_type,
+ spi=p.vpp_tun_spi,
crypt_algo=p.crypt_algo,
crypt_key=crypt_key,
- auth_algo=p.auth_algo, auth_key=p.auth_key,
- tunnel_header=ip_class_by_addr_type[p.addr_type](
- src=p.tun_dst,
- dst=p.tun_src),
+ auth_algo=p.auth_algo,
+ auth_key=p.auth_key,
+ tunnel_header=ip_class_by_addr_type[p.addr_type](src=p.tun_dst, dst=p.tun_src),
nat_t_header=p.nat_header,
- esn_en=esn_en)
+ esn_en=esn_en,
+ )
p.vpp_tun_sa = SecurityAssociation(
- encryption_type, spi=p.scapy_tun_spi,
+ encryption_type,
+ spi=p.scapy_tun_spi,
crypt_algo=p.crypt_algo,
crypt_key=crypt_key,
- auth_algo=p.auth_algo, auth_key=p.auth_key,
- tunnel_header=ip_class_by_addr_type[p.addr_type](
- dst=p.tun_dst,
- src=p.tun_src),
+ auth_algo=p.auth_algo,
+ auth_key=p.auth_key,
+ tunnel_header=ip_class_by_addr_type[p.addr_type](dst=p.tun_dst, src=p.tun_src),
nat_t_header=p.nat_header,
- esn_en=esn_en)
+ esn_en=esn_en,
+ )
def config_tra_params(p, encryption_type):
- esn_en = bool(p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_USE_ESN))
+ esn_en = bool(
+ p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ESN)
+ )
crypt_key = mk_scapy_crypt_key(p)
p.scapy_tra_sa = SecurityAssociation(
encryption_type,
@@ -159,7 +173,8 @@ def config_tra_params(p, encryption_type):
auth_algo=p.auth_algo,
auth_key=p.auth_key,
nat_t_header=p.nat_header,
- esn_en=esn_en)
+ esn_en=esn_en,
+ )
p.vpp_tra_sa = SecurityAssociation(
encryption_type,
spi=p.scapy_tra_spi,
@@ -168,7 +183,8 @@ def config_tra_params(p, encryption_type):
auth_algo=p.auth_algo,
auth_key=p.auth_key,
nat_t_header=p.nat_header,
- esn_en=esn_en)
+ esn_en=esn_en,
+ )
class TemplateIpsec(VppTestCase):
@@ -189,11 +205,12 @@ class TemplateIpsec(VppTestCase):
|tun_if| -------> |VPP| ------> |pg1|
------ --- ---
"""
+
tun_spd_id = 1
tra_spd_id = 2
def ipsec_select_backend(self):
- """ empty method to be overloaded when necessary """
+ """empty method to be overloaded when necessary"""
pass
@classmethod
@@ -205,12 +222,14 @@ class TemplateIpsec(VppTestCase):
super(TemplateIpsec, cls).tearDownClass()
def setup_params(self):
- if not hasattr(self, 'ipv4_params'):
+ if not hasattr(self, "ipv4_params"):
self.ipv4_params = IPsecIPv4Params()
- if not hasattr(self, 'ipv6_params'):
+ if not hasattr(self, "ipv6_params"):
self.ipv6_params = IPsecIPv6Params()
- self.params = {self.ipv4_params.addr_type: self.ipv4_params,
- self.ipv6_params.addr_type: self.ipv6_params}
+ self.params = {
+ self.ipv4_params.addr_type: self.ipv4_params,
+ self.ipv6_params.addr_type: self.ipv6_params,
+ }
def config_interfaces(self):
self.create_pg_interfaces(range(3))
@@ -227,10 +246,8 @@ class TemplateIpsec(VppTestCase):
self.setup_params()
- self.vpp_esp_protocol = (VppEnum.vl_api_ipsec_proto_t.
- IPSEC_API_PROTO_ESP)
- self.vpp_ah_protocol = (VppEnum.vl_api_ipsec_proto_t.
- IPSEC_API_PROTO_AH)
+ self.vpp_esp_protocol = VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP
+ self.vpp_ah_protocol = VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_AH
self.config_interfaces()
@@ -250,34 +267,39 @@ class TemplateIpsec(VppTestCase):
def show_commands_at_teardown(self):
self.logger.info(self.vapi.cli("show hardware"))
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=54):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=src, dst=dst) /
- ICMP() / Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=54):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IPv6(src=src, dst=dst,
- hlim=p.inner_hop_limit,
- fl=p.inner_flow_label) /
- ICMPv6EchoRequest(id=0, seq=1,
- data='X' * payload_size))
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=54):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(IP(src=src, dst=dst) / ICMP() / Raw(b"X" * payload_size))
+ for i in range(count)
+ ]
+
+ def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=54):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IPv6(src=src, dst=dst, hlim=p.inner_hop_limit, fl=p.inner_flow_label)
+ / ICMPv6EchoRequest(id=0, seq=1, data="X" * payload_size)
+ )
+ for i in range(count)
+ ]
def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=54):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IP(src=src, dst=dst) / ICMP() / Raw(b'X' * payload_size)
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IP(src=src, dst=dst)
+ / ICMP()
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=54):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IPv6(src=src, dst=dst,
- hlim=p.inner_hop_limit, fl=p.inner_flow_label) /
- ICMPv6EchoRequest(id=0, seq=1, data='X' * payload_size)
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IPv6(src=src, dst=dst, hlim=p.inner_hop_limit, fl=p.inner_flow_label)
+ / ICMPv6EchoRequest(id=0, seq=1, data="X" * payload_size)
+ for i in range(count)
+ ]
class IpsecTcp(object):
@@ -285,10 +307,12 @@ class IpsecTcp(object):
# start http cli server listener on http://0.0.0.0:80
self.vapi.cli("http cli server")
p = self.params[socket.AF_INET]
- send = (Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac) /
- p.scapy_tun_sa.encrypt(IP(src=p.remote_tun_if_host,
- dst=self.tun_if.local_ip4) /
- TCP(flags='S', dport=80)))
+ send = Ether(
+ src=self.tun_if.remote_mac, dst=self.tun_if.local_mac
+ ) / p.scapy_tun_sa.encrypt(
+ IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4)
+ / TCP(flags="S", dport=80)
+ )
self.logger.debug(ppp("Sending packet:", send))
recv = self.send_and_expect(self.tun_if, [send], self.tun_if)
recv = recv[0]
@@ -298,36 +322,40 @@ class IpsecTcp(object):
class IpsecTcpTests(IpsecTcp):
def test_tcp_checksum(self):
- """ verify checksum correctness for vpp generated packets """
+ """verify checksum correctness for vpp generated packets"""
self.verify_tcp_checksum()
class IpsecTra4(object):
- """ verify methods for Transport v4 """
+ """verify methods for Transport v4"""
+
def get_replay_counts(self, p):
- replay_node_name = ('/err/%s/SA replayed packet' %
- self.tra4_decrypt_node_name[0])
+ replay_node_name = "/err/%s/SA replayed packet" % self.tra4_decrypt_node_name[0]
count = self.statistics.get_err_counter(replay_node_name)
if p.async_mode:
- replay_post_node_name = ('/err/%s/SA replayed packet' %
- self.tra4_decrypt_node_name[p.async_mode])
+ replay_post_node_name = (
+ "/err/%s/SA replayed packet" % self.tra4_decrypt_node_name[p.async_mode]
+ )
count += self.statistics.get_err_counter(replay_post_node_name)
return count
def get_hash_failed_counts(self, p):
if ESP == self.encryption_type and p.crypt_algo == "AES-GCM":
- hash_failed_node_name = ('/err/%s/ESP decryption failed' %
- self.tra4_decrypt_node_name[p.async_mode])
+ hash_failed_node_name = (
+ "/err/%s/ESP decryption failed"
+ % self.tra4_decrypt_node_name[p.async_mode]
+ )
else:
- hash_failed_node_name = ('/err/%s/Integrity check failed' %
- self.tra4_decrypt_node_name[p.async_mode])
+ hash_failed_node_name = (
+ "/err/%s/Integrity check failed"
+ % self.tra4_decrypt_node_name[p.async_mode]
+ )
count = self.statistics.get_err_counter(hash_failed_node_name)
if p.async_mode:
- count += self.statistics.get_err_counter(
- '/err/crypto-dispatch/bad-hmac')
+ count += self.statistics.get_err_counter("/err/crypto-dispatch/bad-hmac")
return count
@@ -337,81 +365,100 @@ class IpsecTra4(object):
esn_on = p.vpp_tra_sa.esn_en
ar_on = p.flags & saf.IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY
- seq_cycle_node_name = \
- ('/err/%s/sequence number cycled (packet dropped)' %
- self.tra4_encrypt_node_name)
+ seq_cycle_node_name = (
+ "/err/%s/sequence number cycled (packet dropped)"
+ % self.tra4_encrypt_node_name
+ )
replay_count = self.get_replay_counts(p)
hash_failed_count = self.get_hash_failed_counts(p)
seq_cycle_count = self.statistics.get_err_counter(seq_cycle_node_name)
# a few packets so we get the rx seq number above the window size and
# thus can simulate a wrap with an out of window packet
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=seq))
- for seq in range(63, 80)]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=seq,
+ )
+ )
+ for seq in range(63, 80)
+ ]
recv_pkts = self.send_and_expect(self.tra_if, pkts, self.tra_if)
# these 4 packets will all choose seq-num 0 to decrpyt since none
# are out of window when first checked. however, once #200 has
# decrypted it will move the window to 200 and has #81 is out of
# window. this packet should be dropped.
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=200)),
- (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=81)),
- (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=201)),
- (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=202))]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=200,
+ )
+ ),
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=81,
+ )
+ ),
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=201,
+ )
+ ),
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=202,
+ )
+ ),
+ ]
# if anti-replay is off then we won't drop #81
n_rx = 3 if ar_on else 4
self.send_and_expect(self.tra_if, pkts, self.tra_if, n_rx=n_rx)
# this packet is one before the wrap
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=203))]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=203,
+ )
+ )
+ ]
recv_pkts = self.send_and_expect(self.tra_if, pkts, self.tra_if)
# move the window over half way to a wrap
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x80000001))]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=0x80000001,
+ )
+ )
+ ]
recv_pkts = self.send_and_expect(self.tra_if, pkts, self.tra_if)
# anti-replay will drop old packets, no anti-replay will not
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x44000001))]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=0x44000001,
+ )
+ )
+ ]
if ar_on:
self.send_and_assert_no_replies(self.tra_if, pkts)
@@ -427,36 +474,48 @@ class IpsecTra4(object):
p.scapy_tra_sa.seq_num = 0x100000005
# send a packet that wraps the window for both AR and no AR
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x100000005))]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4)
+ / ICMP(),
+ seq_num=0x100000005,
+ )
+ )
+ ]
rxs = self.send_and_expect(self.tra_if, pkts, self.tra_if)
for rx in rxs:
decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
# move the window forward to half way to the next wrap
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x180000005))]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4)
+ / ICMP(),
+ seq_num=0x180000005,
+ )
+ )
+ ]
rxs = self.send_and_expect(self.tra_if, pkts, self.tra_if)
# a packet less than 2^30 from the current position is:
# - AR: out of window and dropped
# - non-AR: accepted
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x170000005))]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4)
+ / ICMP(),
+ seq_num=0x170000005,
+ )
+ )
+ ]
if ar_on:
self.send_and_assert_no_replies(self.tra_if, pkts)
@@ -467,12 +526,16 @@ class IpsecTra4(object):
# - AR: out of window and dropped
# - non-AR: considered a wrap, but since it's not a wrap
# it won't decrpyt and so will be dropped
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x130000005))]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4)
+ / ICMP(),
+ seq_num=0x130000005,
+ )
+ )
+ ]
self.send_and_assert_no_replies(self.tra_if, pkts)
@@ -481,12 +544,16 @@ class IpsecTra4(object):
# - AR: out of window so considered a wrap, so accepted
# - non-AR: not considered a wrap, so won't decrypt
p.scapy_tra_sa.seq_num = 0x260000005
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x260000005))]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4)
+ / ICMP(),
+ seq_num=0x260000005,
+ )
+ )
+ ]
if ar_on:
self.send_and_expect(self.tra_if, pkts, self.tra_if)
else:
@@ -502,44 +569,55 @@ class IpsecTra4(object):
# - AR: accepted
# - non-AR: not considered a wrap, so won't decrypt
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x200000005)),
- (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x200000006))]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4)
+ / ICMP(),
+ seq_num=0x200000005,
+ )
+ ),
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4)
+ / ICMP(),
+ seq_num=0x200000006,
+ )
+ ),
+ ]
self.send_and_expect(self.tra_if, pkts, self.tra_if)
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x260000005))]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4)
+ / ICMP(),
+ seq_num=0x260000005,
+ )
+ )
+ ]
self.send_and_expect(self.tra_if, pkts, self.tra_if)
def verify_tra_anti_replay(self):
p = self.params[socket.AF_INET]
esn_en = p.vpp_tra_sa.esn_en
- seq_cycle_node_name = \
- ('/err/%s/sequence number cycled (packet dropped)' %
- self.tra4_encrypt_node_name)
+ seq_cycle_node_name = (
+ "/err/%s/sequence number cycled (packet dropped)"
+ % self.tra4_encrypt_node_name
+ )
replay_count = self.get_replay_counts(p)
hash_failed_count = self.get_hash_failed_counts(p)
seq_cycle_count = self.statistics.get_err_counter(seq_cycle_node_name)
if ESP == self.encryption_type:
- undersize_node_name = ('/err/%s/undersized packet' %
- self.tra4_decrypt_node_name[0])
- undersize_count = self.statistics.get_err_counter(
- undersize_node_name)
+ undersize_node_name = (
+ "/err/%s/undersized packet" % self.tra4_decrypt_node_name[0]
+ )
+ undersize_count = self.statistics.get_err_counter(undersize_node_name)
#
# send packets with seq numbers 1->34
@@ -549,13 +627,16 @@ class IpsecTra4(object):
# for reasons i haven't investigated Scapy won't create a packet with
# seq_num=0
#
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=seq))
- for seq in range(1, 34)]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=seq,
+ )
+ )
+ for seq in range(1, 34)
+ ]
recv_pkts = self.send_and_expect(self.tra_if, pkts, self.tra_if)
# replayed packets are dropped
@@ -569,14 +650,13 @@ class IpsecTra4(object):
#
self.vapi.cli("clear error")
self.vapi.cli("clear node counters")
- pkts = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=35))
- recv_pkts = self.send_and_expect(self.tra_if, pkts * 8,
- self.tra_if, n_rx=1)
+ pkts = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=35,
+ )
+ recv_pkts = self.send_and_expect(self.tra_if, pkts * 8, self.tra_if, n_rx=1)
replay_count += 7
self.assertEqual(self.get_replay_counts(p), replay_count)
@@ -584,12 +664,12 @@ class IpsecTra4(object):
# now move the window over to 257 (more than one byte) and into Case A
#
self.vapi.cli("clear error")
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=257))
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=257,
+ )
recv_pkts = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
# replayed packets are dropped
@@ -599,27 +679,29 @@ class IpsecTra4(object):
# the window size is 64 packets
# in window are still accepted
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=200))
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=200,
+ )
recv_pkts = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
# a packet that does not decrypt does not move the window forward
- bogus_sa = SecurityAssociation(self.encryption_type,
- p.vpp_tra_spi,
- crypt_algo=p.crypt_algo,
- crypt_key=mk_scapy_crypt_key(p)[::-1],
- auth_algo=p.auth_algo,
- auth_key=p.auth_key[::-1])
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- bogus_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=350))
+ bogus_sa = SecurityAssociation(
+ self.encryption_type,
+ p.vpp_tra_spi,
+ crypt_algo=p.crypt_algo,
+ crypt_key=mk_scapy_crypt_key(p)[::-1],
+ auth_algo=p.auth_algo,
+ auth_key=p.auth_key[::-1],
+ )
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / bogus_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=350,
+ )
self.send_and_assert_no_replies(self.tra_if, pkt * 17, timeout=0.2)
hash_failed_count += 17
@@ -627,28 +709,26 @@ class IpsecTra4(object):
# a malformed 'runt' packet
# created by a mis-constructed SA
- if (ESP == self.encryption_type and p.crypt_algo != "NULL"):
- bogus_sa = SecurityAssociation(self.encryption_type,
- p.vpp_tra_spi)
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- bogus_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=350))
+ if ESP == self.encryption_type and p.crypt_algo != "NULL":
+ bogus_sa = SecurityAssociation(self.encryption_type, p.vpp_tra_spi)
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / bogus_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=350,
+ )
self.send_and_assert_no_replies(self.tra_if, pkt * 17, timeout=0.2)
undersize_count += 17
- self.assert_error_counter_equal(undersize_node_name,
- undersize_count)
+ self.assert_error_counter_equal(undersize_node_name, undersize_count)
# which we can determine since this packet is still in the window
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=234))
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=234,
+ )
self.send_and_expect(self.tra_if, [pkt], self.tra_if)
#
@@ -656,12 +736,12 @@ class IpsecTra4(object):
# this is Case B. So VPP will consider this to be a high seq num wrap
# and so the decrypt attempt will fail
#
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=17))
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=17,
+ )
self.send_and_assert_no_replies(self.tra_if, pkt * 17, timeout=0.2)
if esn_en:
@@ -675,12 +755,12 @@ class IpsecTra4(object):
self.assertEqual(self.get_replay_counts(p), replay_count)
# valid packet moves the window over to 258
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=258))
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=258,
+ )
rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
@@ -694,13 +774,16 @@ class IpsecTra4(object):
self.logger.info(self.vapi.ppcli("show ipsec sa 0"))
self.logger.info(self.vapi.ppcli("show ipsec sa 1"))
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=seq))
- for seq in range(259, 280)]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=seq,
+ )
+ )
+ for seq in range(259, 280)
+ ]
if esn_en:
rxs = self.send_and_expect(self.tra_if, pkts, self.tra_if)
@@ -719,12 +802,12 @@ class IpsecTra4(object):
# The low seq num we set it to will place VPP's RX window in Case A
#
p.scapy_tra_sa.seq_num = 0x100000005
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x100000005))
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=0x100000005,
+ )
rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
@@ -733,13 +816,13 @@ class IpsecTra4(object):
# A packet that has seq num between (2^32-64) and 5 is within
# the window
#
- p.scapy_tra_sa.seq_num = 0xfffffffd
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0xfffffffd))
+ p.scapy_tra_sa.seq_num = 0xFFFFFFFD
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=0xFFFFFFFD,
+ )
rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
@@ -748,14 +831,15 @@ class IpsecTra4(object):
# because VPP will consider this packet to be one that moves the
# window forward
#
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x200000999))
- self.send_and_assert_no_replies(self.tra_if, [pkt], self.tra_if,
- timeout=0.2)
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=0x200000999,
+ )
+ self.send_and_assert_no_replies(
+ self.tra_if, [pkt], self.tra_if, timeout=0.2
+ )
hash_failed_count += 1
self.assertEqual(self.get_hash_failed_counts(p), hash_failed_count)
@@ -765,22 +849,22 @@ class IpsecTra4(object):
# again
#
p.scapy_tra_sa.seq_num = 0x100000555
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x100000555))
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=0x100000555,
+ )
rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
p.scapy_tra_sa.seq_num = 0x200000444
- pkt = (Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=0x200000444))
+ pkt = Ether(
+ src=self.tra_if.remote_mac, dst=self.tra_if.local_mac
+ ) / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=0x200000444,
+ )
rx = self.send_and_expect(self.tra_if, [pkt], self.tra_if)
decrypted = p.vpp_tra_sa.decrypt(rx[0][IP])
@@ -791,8 +875,7 @@ class IpsecTra4(object):
#
self.send_and_assert_no_replies(self.tra_if, pkts, timeout=0.2)
seq_cycle_count += len(pkts)
- self.assert_error_counter_equal(seq_cycle_node_name,
- seq_cycle_count)
+ self.assert_error_counter_equal(seq_cycle_node_name, seq_cycle_count)
# move the security-associations seq number on to the last we used
self.vapi.cli("test ipsec sa %d seq 0x15f" % p.scapy_tra_sa_id)
@@ -811,88 +894,109 @@ class IpsecTra4(object):
# for reasons i haven't investigated Scapy won't create a packet with
# seq_num=0
#
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=seq))
- for seq in range(1, 3)]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=seq,
+ )
+ )
+ for seq in range(1, 3)
+ ]
self.send_and_expect(self.tra_if, pkts, self.tra_if)
self.assertEqual(p.tra_sa_out.get_lost(), 0)
# skip a sequence number
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=seq))
- for seq in range(4, 6)]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=seq,
+ )
+ )
+ for seq in range(4, 6)
+ ]
self.send_and_expect(self.tra_if, pkts, self.tra_if)
self.assertEqual(p.tra_sa_out.get_lost(), 0)
# the lost packet are counted untill we get up past the first
# sizeof(replay_window) packets
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=seq))
- for seq in range(6, 100)]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=seq,
+ )
+ )
+ for seq in range(6, 100)
+ ]
self.send_and_expect(self.tra_if, pkts, self.tra_if)
self.assertEqual(p.tra_sa_out.get_lost(), 1)
# lost of holes in the sequence
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=seq))
- for seq in range(100, 200, 2)]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=seq,
+ )
+ )
+ for seq in range(100, 200, 2)
+ ]
self.send_and_expect(self.tra_if, pkts, self.tra_if, n_rx=50)
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=seq))
- for seq in range(200, 300)]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=seq,
+ )
+ )
+ for seq in range(200, 300)
+ ]
self.send_and_expect(self.tra_if, pkts, self.tra_if)
self.assertEqual(p.tra_sa_out.get_lost(), 51)
# a big hole in the seq number space
- pkts = [(Ether(src=self.tra_if.remote_mac,
- dst=self.tra_if.local_mac) /
- p.scapy_tra_sa.encrypt(IP(src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4) /
- ICMP(),
- seq_num=seq))
- for seq in range(400, 500)]
+ pkts = [
+ (
+ Ether(src=self.tra_if.remote_mac, dst=self.tra_if.local_mac)
+ / p.scapy_tra_sa.encrypt(
+ IP(src=self.tra_if.remote_ip4, dst=self.tra_if.local_ip4) / ICMP(),
+ seq_num=seq,
+ )
+ )
+ for seq in range(400, 500)
+ ]
self.send_and_expect(self.tra_if, pkts, self.tra_if)
self.assertEqual(p.tra_sa_out.get_lost(), 151)
def verify_tra_basic4(self, count=1, payload_size=54):
- """ ipsec v4 transport basic test """
+ """ipsec v4 transport basic test"""
self.vapi.cli("clear errors")
self.vapi.cli("clear ipsec sa")
try:
p = self.params[socket.AF_INET]
- send_pkts = self.gen_encrypt_pkts(p, p.scapy_tra_sa, self.tra_if,
- src=self.tra_if.remote_ip4,
- dst=self.tra_if.local_ip4,
- count=count,
- payload_size=payload_size)
- recv_pkts = self.send_and_expect(self.tra_if, send_pkts,
- self.tra_if)
+ send_pkts = self.gen_encrypt_pkts(
+ p,
+ p.scapy_tra_sa,
+ self.tra_if,
+ src=self.tra_if.remote_ip4,
+ dst=self.tra_if.local_ip4,
+ count=count,
+ payload_size=payload_size,
+ )
+ recv_pkts = self.send_and_expect(self.tra_if, send_pkts, self.tra_if)
for rx in recv_pkts:
self.assertEqual(len(rx) - len(Ether()), rx[IP].len)
self.assert_packet_checksums_valid(rx)
@@ -906,14 +1010,14 @@ class IpsecTra4(object):
self.logger.info(self.vapi.ppcli("show error"))
self.logger.info(self.vapi.ppcli("show ipsec all"))
- pkts = p.tra_sa_in.get_stats()['packets']
- self.assertEqual(pkts, count,
- "incorrect SA in counts: expected %d != %d" %
- (count, pkts))
- pkts = p.tra_sa_out.get_stats()['packets']
- self.assertEqual(pkts, count,
- "incorrect SA out counts: expected %d != %d" %
- (count, pkts))
+ pkts = p.tra_sa_in.get_stats()["packets"]
+ self.assertEqual(
+ pkts, count, "incorrect SA in counts: expected %d != %d" % (count, pkts)
+ )
+ pkts = p.tra_sa_out.get_stats()["packets"]
+ self.assertEqual(
+ pkts, count, "incorrect SA out counts: expected %d != %d" % (count, pkts)
+ )
self.assertEqual(p.tra_sa_out.get_lost(), 0)
self.assertEqual(p.tra_sa_in.get_lost(), 0)
@@ -922,41 +1026,45 @@ class IpsecTra4(object):
class IpsecTra4Tests(IpsecTra4):
- """ UT test methods for Transport v4 """
+ """UT test methods for Transport v4"""
+
def test_tra_anti_replay(self):
- """ ipsec v4 transport anti-replay test """
+ """ipsec v4 transport anti-replay test"""
self.verify_tra_anti_replay()
def test_tra_lost(self):
- """ ipsec v4 transport lost packet test """
+ """ipsec v4 transport lost packet test"""
self.verify_tra_lost()
def test_tra_basic(self, count=1):
- """ ipsec v4 transport basic test """
+ """ipsec v4 transport basic test"""
self.verify_tra_basic4(count=1)
def test_tra_burst(self):
- """ ipsec v4 transport burst test """
+ """ipsec v4 transport burst test"""
self.verify_tra_basic4(count=257)
class IpsecTra6(object):
- """ verify methods for Transport v6 """
+ """verify methods for Transport v6"""
+
def verify_tra_basic6(self, count=1, payload_size=54):
self.vapi.cli("clear errors")
self.vapi.cli("clear ipsec sa")
try:
p = self.params[socket.AF_INET6]
- send_pkts = self.gen_encrypt_pkts6(p, p.scapy_tra_sa, self.tra_if,
- src=self.tra_if.remote_ip6,
- dst=self.tra_if.local_ip6,
- count=count,
- payload_size=payload_size)
- recv_pkts = self.send_and_expect(self.tra_if, send_pkts,
- self.tra_if)
+ send_pkts = self.gen_encrypt_pkts6(
+ p,
+ p.scapy_tra_sa,
+ self.tra_if,
+ src=self.tra_if.remote_ip6,
+ dst=self.tra_if.local_ip6,
+ count=count,
+ payload_size=payload_size,
+ )
+ recv_pkts = self.send_and_expect(self.tra_if, send_pkts, self.tra_if)
for rx in recv_pkts:
- self.assertEqual(len(rx) - len(Ether()) - len(IPv6()),
- rx[IPv6].plen)
+ self.assertEqual(len(rx) - len(Ether()) - len(IPv6()), rx[IPv6].plen)
try:
decrypted = p.vpp_tra_sa.decrypt(rx[IPv6])
self.assert_packet_checksums_valid(decrypted)
@@ -967,32 +1075,38 @@ class IpsecTra6(object):
self.logger.info(self.vapi.ppcli("show error"))
self.logger.info(self.vapi.ppcli("show ipsec all"))
- pkts = p.tra_sa_in.get_stats()['packets']
- self.assertEqual(pkts, count,
- "incorrect SA in counts: expected %d != %d" %
- (count, pkts))
- pkts = p.tra_sa_out.get_stats()['packets']
- self.assertEqual(pkts, count,
- "incorrect SA out counts: expected %d != %d" %
- (count, pkts))
+ pkts = p.tra_sa_in.get_stats()["packets"]
+ self.assertEqual(
+ pkts, count, "incorrect SA in counts: expected %d != %d" % (count, pkts)
+ )
+ pkts = p.tra_sa_out.get_stats()["packets"]
+ self.assertEqual(
+ pkts, count, "incorrect SA out counts: expected %d != %d" % (count, pkts)
+ )
self.assert_packet_counter_equal(self.tra6_encrypt_node_name, count)
self.assert_packet_counter_equal(self.tra6_decrypt_node_name[0], count)
- def gen_encrypt_pkts_ext_hdrs6(self, sa, sw_intf, src, dst, count=1,
- payload_size=54):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IPv6(src=src, dst=dst) /
- ICMPv6EchoRequest(id=0, seq=1,
- data='X' * payload_size))
- for i in range(count)]
+ def gen_encrypt_pkts_ext_hdrs6(
+ self, sa, sw_intf, src, dst, count=1, payload_size=54
+ ):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IPv6(src=src, dst=dst)
+ / ICMPv6EchoRequest(id=0, seq=1, data="X" * payload_size)
+ )
+ for i in range(count)
+ ]
def gen_pkts_ext_hdrs6(self, sw_intf, src, dst, count=1, payload_size=54):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IPv6(src=src, dst=dst) /
- IPv6ExtHdrHopByHop() /
- IPv6ExtHdrFragment(id=2, offset=200) /
- Raw(b'\xff' * 200)
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IPv6(src=src, dst=dst)
+ / IPv6ExtHdrHopByHop()
+ / IPv6ExtHdrFragment(id=2, offset=200)
+ / Raw(b"\xff" * 200)
+ for i in range(count)
+ ]
def verify_tra_encrypted6(self, p, sa, rxs):
decrypted = []
@@ -1018,10 +1132,13 @@ class IpsecTra6(object):
#
# check we can decrypt with options
#
- tx = self.gen_encrypt_pkts_ext_hdrs6(p.scapy_tra_sa, self.tra_if,
- src=self.tra_if.remote_ip6,
- dst=self.tra_if.local_ip6,
- count=count)
+ tx = self.gen_encrypt_pkts_ext_hdrs6(
+ p.scapy_tra_sa,
+ self.tra_if,
+ src=self.tra_if.remote_ip6,
+ dst=self.tra_if.local_ip6,
+ count=count,
+ )
self.send_and_expect(self.tra_if, tx, self.tra_if)
#
@@ -1030,11 +1147,12 @@ class IpsecTra6(object):
#
# one extension before ESP
- tx = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IPv6(src=self.tra_if.local_ip6,
- dst=self.tra_if.remote_ip6) /
- IPv6ExtHdrFragment(id=2, offset=200) /
- Raw(b'\xff' * 200))
+ tx = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IPv6(src=self.tra_if.local_ip6, dst=self.tra_if.remote_ip6)
+ / IPv6ExtHdrFragment(id=2, offset=200)
+ / Raw(b"\xff" * 200)
+ )
rxs = self.send_and_expect(self.pg2, [tx], self.tra_if)
dcs = self.verify_tra_encrypted6(p, p.vpp_tra_sa, rxs)
@@ -1047,12 +1165,13 @@ class IpsecTra6(object):
self.assert_equal(dc[IPv6ExtHdrFragment].id, 2)
# two extensions before ESP
- tx = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IPv6(src=self.tra_if.local_ip6,
- dst=self.tra_if.remote_ip6) /
- IPv6ExtHdrHopByHop() /
- IPv6ExtHdrFragment(id=2, offset=200) /
- Raw(b'\xff' * 200))
+ tx = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IPv6(src=self.tra_if.local_ip6, dst=self.tra_if.remote_ip6)
+ / IPv6ExtHdrHopByHop()
+ / IPv6ExtHdrFragment(id=2, offset=200)
+ / Raw(b"\xff" * 200)
+ )
rxs = self.send_and_expect(self.pg2, [tx], self.tra_if)
dcs = self.verify_tra_encrypted6(p, p.vpp_tra_sa, rxs)
@@ -1063,13 +1182,14 @@ class IpsecTra6(object):
self.assert_equal(dc[IPv6ExtHdrFragment].id, 2)
# two extensions before ESP, one after
- tx = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IPv6(src=self.tra_if.local_ip6,
- dst=self.tra_if.remote_ip6) /
- IPv6ExtHdrHopByHop() /
- IPv6ExtHdrFragment(id=2, offset=200) /
- IPv6ExtHdrDestOpt() /
- Raw(b'\xff' * 200))
+ tx = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IPv6(src=self.tra_if.local_ip6, dst=self.tra_if.remote_ip6)
+ / IPv6ExtHdrHopByHop()
+ / IPv6ExtHdrFragment(id=2, offset=200)
+ / IPv6ExtHdrDestOpt()
+ / Raw(b"\xff" * 200)
+ )
rxs = self.send_and_expect(self.pg2, [tx], self.tra_if)
dcs = self.verify_tra_encrypted6(p, p.vpp_tra_sa, rxs)
@@ -1082,47 +1202,54 @@ class IpsecTra6(object):
class IpsecTra6Tests(IpsecTra6):
- """ UT test methods for Transport v6 """
+ """UT test methods for Transport v6"""
+
def test_tra_basic6(self):
- """ ipsec v6 transport basic test """
+ """ipsec v6 transport basic test"""
self.verify_tra_basic6(count=1)
def test_tra_burst6(self):
- """ ipsec v6 transport burst test """
+ """ipsec v6 transport burst test"""
self.verify_tra_basic6(count=257)
class IpsecTra6ExtTests(IpsecTra6):
def test_tra_ext_hdrs_66(self):
- """ ipsec 6o6 tra extension headers test """
+ """ipsec 6o6 tra extension headers test"""
self.verify_tra_66_ext_hdrs(self.params[socket.AF_INET6])
class IpsecTra46Tests(IpsecTra4Tests, IpsecTra6Tests):
- """ UT test methods for Transport v6 and v4"""
+ """UT test methods for Transport v6 and v4"""
+
pass
class IpsecTun4(object):
- """ verify methods for Tunnel v4 """
+ """verify methods for Tunnel v4"""
+
def verify_counters4(self, p, count, n_frags=None, worker=None):
if not n_frags:
n_frags = count
- if (hasattr(p, "spd_policy_in_any")):
- pkts = p.spd_policy_in_any.get_stats(worker)['packets']
- self.assertEqual(pkts, count,
- "incorrect SPD any policy: expected %d != %d" %
- (count, pkts))
-
- if (hasattr(p, "tun_sa_in")):
- pkts = p.tun_sa_in.get_stats(worker)['packets']
- self.assertEqual(pkts, count,
- "incorrect SA in counts: expected %d != %d" %
- (count, pkts))
- pkts = p.tun_sa_out.get_stats(worker)['packets']
- self.assertEqual(pkts, n_frags,
- "incorrect SA out counts: expected %d != %d" %
- (count, pkts))
+ if hasattr(p, "spd_policy_in_any"):
+ pkts = p.spd_policy_in_any.get_stats(worker)["packets"]
+ self.assertEqual(
+ pkts,
+ count,
+ "incorrect SPD any policy: expected %d != %d" % (count, pkts),
+ )
+
+ if hasattr(p, "tun_sa_in"):
+ pkts = p.tun_sa_in.get_stats(worker)["packets"]
+ self.assertEqual(
+ pkts, count, "incorrect SA in counts: expected %d != %d" % (count, pkts)
+ )
+ pkts = p.tun_sa_out.get_stats(worker)["packets"]
+ self.assertEqual(
+ pkts,
+ n_frags,
+ "incorrect SA out counts: expected %d != %d" % (count, pkts),
+ )
self.assert_packet_counter_equal(self.tun4_encrypt_node_name, n_frags)
self.assert_packet_counter_equal(self.tun4_decrypt_node_name[0], count)
@@ -1177,19 +1304,26 @@ class IpsecTun4(object):
if not n_rx:
n_rx = count
try:
- send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip4,
- count=count,
- payload_size=payload_size)
+ send_pkts = self.gen_encrypt_pkts(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip4,
+ count=count,
+ payload_size=payload_size,
+ )
recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1)
self.verify_decrypted(p, recv_pkts)
- send_pkts = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4,
- dst=p.remote_tun_if_host, count=count,
- payload_size=payload_size)
- recv_pkts = self.send_and_expect(self.pg1, send_pkts,
- self.tun_if, n_rx)
+ send_pkts = self.gen_pkts(
+ self.pg1,
+ src=self.pg1.remote_ip4,
+ dst=p.remote_tun_if_host,
+ count=count,
+ payload_size=payload_size,
+ )
+ recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if, n_rx)
self.verify_encrypted(p, p.vpp_tun_sa, recv_pkts)
for rx in recv_pkts:
@@ -1209,15 +1343,23 @@ class IpsecTun4(object):
if not n_rx:
n_rx = count
try:
- send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip4,
- count=count)
+ send_pkts = self.gen_encrypt_pkts(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip4,
+ count=count,
+ )
self.send_and_assert_no_replies(self.tun_if, send_pkts)
- send_pkts = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4,
- dst=p.remote_tun_if_host, count=count,
- payload_size=payload_size)
+ send_pkts = self.gen_pkts(
+ self.pg1,
+ src=self.pg1.remote_ip4,
+ dst=p.remote_tun_if_host,
+ count=count,
+ payload_size=payload_size,
+ )
self.send_and_assert_no_replies(self.pg1, send_pkts)
finally:
@@ -1227,23 +1369,27 @@ class IpsecTun4(object):
def verify_tun_reass_44(self, p):
self.vapi.cli("clear errors")
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.tun_if.sw_if_index, enable_ip4=True)
+ sw_if_index=self.tun_if.sw_if_index, enable_ip4=True
+ )
try:
- send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip4,
- payload_size=1900,
- count=1)
+ send_pkts = self.gen_encrypt_pkts(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip4,
+ payload_size=1900,
+ count=1,
+ )
send_pkts = fragment_rfc791(send_pkts[0], 1400)
- recv_pkts = self.send_and_expect(self.tun_if, send_pkts,
- self.pg1, n_rx=1)
+ recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1, n_rx=1)
self.verify_decrypted(p, recv_pkts)
- send_pkts = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4,
- dst=p.remote_tun_if_host, count=1)
- recv_pkts = self.send_and_expect(self.pg1, send_pkts,
- self.tun_if)
+ send_pkts = self.gen_pkts(
+ self.pg1, src=self.pg1.remote_ip4, dst=p.remote_tun_if_host, count=1
+ )
+ recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if)
self.verify_encrypted(p, p.vpp_tun_sa, recv_pkts)
finally:
@@ -1252,23 +1398,33 @@ class IpsecTun4(object):
self.verify_counters4(p, 1, 1)
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.tun_if.sw_if_index, enable_ip4=False)
+ sw_if_index=self.tun_if.sw_if_index, enable_ip4=False
+ )
def verify_tun_64(self, p, count=1):
self.vapi.cli("clear errors")
self.vapi.cli("clear ipsec sa")
try:
- send_pkts = self.gen_encrypt_pkts6(p, p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host6,
- dst=self.pg1.remote_ip6,
- count=count)
+ send_pkts = self.gen_encrypt_pkts6(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host6,
+ dst=self.pg1.remote_ip6,
+ count=count,
+ )
recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1)
for recv_pkt in recv_pkts:
self.assert_equal(recv_pkt[IPv6].src, p.remote_tun_if_host6)
self.assert_equal(recv_pkt[IPv6].dst, self.pg1.remote_ip6)
self.assert_packet_checksums_valid(recv_pkt)
- send_pkts = self.gen_pkts6(p, self.pg1, src=self.pg1.remote_ip6,
- dst=p.remote_tun_if_host6, count=count)
+ send_pkts = self.gen_pkts6(
+ p,
+ self.pg1,
+ src=self.pg1.remote_ip6,
+ dst=p.remote_tun_if_host6,
+ count=count,
+ )
recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if)
for recv_pkt in recv_pkts:
try:
@@ -1281,8 +1437,7 @@ class IpsecTun4(object):
except:
self.logger.error(ppp("Unexpected packet:", recv_pkt))
try:
- self.logger.debug(
- ppp("Decrypted packet:", decrypt_pkt))
+ self.logger.debug(ppp("Decrypted packet:", decrypt_pkt))
except:
pass
raise
@@ -1295,37 +1450,43 @@ class IpsecTun4(object):
def verify_keepalive(self, p):
# the sizeof Raw is calculated to pad to the minimum ehternet
# frame size of 64 btyes
- pkt = (Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac) /
- IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4) /
- UDP(sport=333, dport=4500) /
- Raw(b'\xff') /
- Padding(0 * 21))
- self.send_and_assert_no_replies(self.tun_if, pkt*31)
+ pkt = (
+ Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac)
+ / IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4)
+ / UDP(sport=333, dport=4500)
+ / Raw(b"\xff")
+ / Padding(0 * 21)
+ )
+ self.send_and_assert_no_replies(self.tun_if, pkt * 31)
self.assert_error_counter_equal(
- '/err/%s/NAT Keepalive' % self.tun4_input_node, 31)
-
- pkt = (Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac) /
- IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4) /
- UDP(sport=333, dport=4500) /
- Raw(b'\xfe'))
- self.send_and_assert_no_replies(self.tun_if, pkt*31)
- self.assert_error_counter_equal(
- '/err/%s/Too Short' % self.tun4_input_node, 31)
-
- pkt = (Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac) /
- IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4) /
- UDP(sport=333, dport=4500) /
- Raw(b'\xfe') /
- Padding(0 * 21))
- self.send_and_assert_no_replies(self.tun_if, pkt*31)
- self.assert_error_counter_equal(
- '/err/%s/Too Short' % self.tun4_input_node, 62)
+ "/err/%s/NAT Keepalive" % self.tun4_input_node, 31
+ )
+
+ pkt = (
+ Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac)
+ / IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4)
+ / UDP(sport=333, dport=4500)
+ / Raw(b"\xfe")
+ )
+ self.send_and_assert_no_replies(self.tun_if, pkt * 31)
+ self.assert_error_counter_equal("/err/%s/Too Short" % self.tun4_input_node, 31)
+
+ pkt = (
+ Ether(src=self.tun_if.remote_mac, dst=self.tun_if.local_mac)
+ / IP(src=p.remote_tun_if_host, dst=self.tun_if.local_ip4)
+ / UDP(sport=333, dport=4500)
+ / Raw(b"\xfe")
+ / Padding(0 * 21)
+ )
+ self.send_and_assert_no_replies(self.tun_if, pkt * 31)
+ self.assert_error_counter_equal("/err/%s/Too Short" % self.tun4_input_node, 62)
class IpsecTun4Tests(IpsecTun4):
- """ UT test methods for Tunnel v4 """
+ """UT test methods for Tunnel v4"""
+
def test_tun_basic44(self):
- """ ipsec 4o4 tunnel basic test """
+ """ipsec 4o4 tunnel basic test"""
self.verify_tun_44(self.params[socket.AF_INET], count=1)
self.tun_if.admin_down()
self.tun_if.resolve_arp()
@@ -1333,27 +1494,30 @@ class IpsecTun4Tests(IpsecTun4):
self.verify_tun_44(self.params[socket.AF_INET], count=1)
def test_tun_reass_basic44(self):
- """ ipsec 4o4 tunnel basic reassembly test """
+ """ipsec 4o4 tunnel basic reassembly test"""
self.verify_tun_reass_44(self.params[socket.AF_INET])
def test_tun_burst44(self):
- """ ipsec 4o4 tunnel burst test """
+ """ipsec 4o4 tunnel burst test"""
self.verify_tun_44(self.params[socket.AF_INET], count=127)
class IpsecTun6(object):
- """ verify methods for Tunnel v6 """
+ """verify methods for Tunnel v6"""
+
def verify_counters6(self, p_in, p_out, count, worker=None):
- if (hasattr(p_in, "tun_sa_in")):
- pkts = p_in.tun_sa_in.get_stats(worker)['packets']
- self.assertEqual(pkts, count,
- "incorrect SA in counts: expected %d != %d" %
- (count, pkts))
- if (hasattr(p_out, "tun_sa_out")):
- pkts = p_out.tun_sa_out.get_stats(worker)['packets']
- self.assertEqual(pkts, count,
- "incorrect SA out counts: expected %d != %d" %
- (count, pkts))
+ if hasattr(p_in, "tun_sa_in"):
+ pkts = p_in.tun_sa_in.get_stats(worker)["packets"]
+ self.assertEqual(
+ pkts, count, "incorrect SA in counts: expected %d != %d" % (count, pkts)
+ )
+ if hasattr(p_out, "tun_sa_out"):
+ pkts = p_out.tun_sa_out.get_stats(worker)["packets"]
+ self.assertEqual(
+ pkts,
+ count,
+ "incorrect SA out counts: expected %d != %d" % (count, pkts),
+ )
self.assert_packet_counter_equal(self.tun6_encrypt_node_name, count)
self.assert_packet_counter_equal(self.tun6_decrypt_node_name[0], count)
@@ -1366,8 +1530,7 @@ class IpsecTun6(object):
def verify_encrypted6(self, p, sa, rxs):
for rx in rxs:
self.assert_packet_checksums_valid(rx)
- self.assertEqual(len(rx) - len(Ether()) - len(IPv6()),
- rx[IPv6].plen)
+ self.assertEqual(len(rx) - len(Ether()) - len(IPv6()), rx[IPv6].plen)
self.assert_equal(rx[IPv6].hlim, p.outer_hop_limit)
if p.outer_flow_label:
self.assert_equal(rx[IPv6].fl, p.outer_flow_label)
@@ -1392,9 +1555,14 @@ class IpsecTun6(object):
self.vapi.cli("clear errors")
self.vapi.cli("clear ipsec sa")
- send_pkts = self.gen_pkts6(p_in, self.pg1, src=self.pg1.remote_ip6,
- dst=p_in.remote_tun_if_host, count=count,
- payload_size=payload_size)
+ send_pkts = self.gen_pkts6(
+ p_in,
+ self.pg1,
+ src=self.pg1.remote_ip6,
+ dst=p_in.remote_tun_if_host,
+ count=count,
+ payload_size=payload_size,
+ )
self.send_and_assert_no_replies(self.tun_if, send_pkts)
self.logger.info(self.vapi.cli("sh punt stats"))
@@ -1402,18 +1570,19 @@ class IpsecTun6(object):
self.vapi.cli("clear errors")
self.vapi.cli("clear ipsec sa")
- send_pkts = self.gen_encrypt_pkts6(p_in, p_in.scapy_tun_sa,
- self.tun_if,
- src=p_in.remote_tun_if_host,
- dst=self.pg1.remote_ip6,
- count=count)
+ send_pkts = self.gen_encrypt_pkts6(
+ p_in,
+ p_in.scapy_tun_sa,
+ self.tun_if,
+ src=p_in.remote_tun_if_host,
+ dst=self.pg1.remote_ip6,
+ count=count,
+ )
self.send_and_assert_no_replies(self.tun_if, send_pkts)
def verify_drop_tun_66(self, p_in, count=1, payload_size=64):
- self.verify_drop_tun_tx_66(p_in, count=count,
- payload_size=payload_size)
- self.verify_drop_tun_rx_66(p_in, count=count,
- payload_size=payload_size)
+ self.verify_drop_tun_tx_66(p_in, count=count, payload_size=payload_size)
+ self.verify_drop_tun_rx_66(p_in, count=count, payload_size=payload_size)
def verify_tun_66(self, p_in, p_out=None, count=1, payload_size=64):
self.vapi.cli("clear errors")
@@ -1421,19 +1590,26 @@ class IpsecTun6(object):
if not p_out:
p_out = p_in
try:
- send_pkts = self.gen_encrypt_pkts6(p_in, p_in.scapy_tun_sa,
- self.tun_if,
- src=p_in.remote_tun_if_host,
- dst=self.pg1.remote_ip6,
- count=count,
- payload_size=payload_size)
+ send_pkts = self.gen_encrypt_pkts6(
+ p_in,
+ p_in.scapy_tun_sa,
+ self.tun_if,
+ src=p_in.remote_tun_if_host,
+ dst=self.pg1.remote_ip6,
+ count=count,
+ payload_size=payload_size,
+ )
recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1)
self.verify_decrypted6(p_in, recv_pkts)
- send_pkts = self.gen_pkts6(p_in, self.pg1, src=self.pg1.remote_ip6,
- dst=p_out.remote_tun_if_host,
- count=count,
- payload_size=payload_size)
+ send_pkts = self.gen_pkts6(
+ p_in,
+ self.pg1,
+ src=self.pg1.remote_ip6,
+ dst=p_out.remote_tun_if_host,
+ count=count,
+ payload_size=payload_size,
+ )
recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if)
self.verify_encrypted6(p_out, p_out.vpp_tun_sa, recv_pkts)
@@ -1449,50 +1625,65 @@ class IpsecTun6(object):
def verify_tun_reass_66(self, p):
self.vapi.cli("clear errors")
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.tun_if.sw_if_index, enable_ip6=True)
+ sw_if_index=self.tun_if.sw_if_index, enable_ip6=True
+ )
try:
- send_pkts = self.gen_encrypt_pkts6(p, p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip6,
- count=1,
- payload_size=1850)
+ send_pkts = self.gen_encrypt_pkts6(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip6,
+ count=1,
+ payload_size=1850,
+ )
send_pkts = fragment_rfc8200(send_pkts[0], 1, 1400, self.logger)
- recv_pkts = self.send_and_expect(self.tun_if, send_pkts,
- self.pg1, n_rx=1)
+ recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1, n_rx=1)
self.verify_decrypted6(p, recv_pkts)
- send_pkts = self.gen_pkts6(p, self.pg1, src=self.pg1.remote_ip6,
- dst=p.remote_tun_if_host,
- count=1,
- payload_size=64)
- recv_pkts = self.send_and_expect(self.pg1, send_pkts,
- self.tun_if)
+ send_pkts = self.gen_pkts6(
+ p,
+ self.pg1,
+ src=self.pg1.remote_ip6,
+ dst=p.remote_tun_if_host,
+ count=1,
+ payload_size=64,
+ )
+ recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if)
self.verify_encrypted6(p, p.vpp_tun_sa, recv_pkts)
finally:
self.logger.info(self.vapi.ppcli("show error"))
self.logger.info(self.vapi.ppcli("show ipsec all"))
self.verify_counters6(p, p, 1)
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.tun_if.sw_if_index, enable_ip6=False)
+ sw_if_index=self.tun_if.sw_if_index, enable_ip6=False
+ )
def verify_tun_46(self, p, count=1):
- """ ipsec 4o6 tunnel basic test """
+ """ipsec 4o6 tunnel basic test"""
self.vapi.cli("clear errors")
self.vapi.cli("clear ipsec sa")
try:
- send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host4,
- dst=self.pg1.remote_ip4,
- count=count)
+ send_pkts = self.gen_encrypt_pkts(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host4,
+ dst=self.pg1.remote_ip4,
+ count=count,
+ )
recv_pkts = self.send_and_expect(self.tun_if, send_pkts, self.pg1)
for recv_pkt in recv_pkts:
self.assert_equal(recv_pkt[IP].src, p.remote_tun_if_host4)
self.assert_equal(recv_pkt[IP].dst, self.pg1.remote_ip4)
self.assert_packet_checksums_valid(recv_pkt)
- send_pkts = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4,
- dst=p.remote_tun_if_host4,
- count=count)
+ send_pkts = self.gen_pkts(
+ self.pg1,
+ src=self.pg1.remote_ip4,
+ dst=p.remote_tun_if_host4,
+ count=count,
+ )
recv_pkts = self.send_and_expect(self.pg1, send_pkts, self.tun_if)
for recv_pkt in recv_pkts:
try:
@@ -1505,8 +1696,7 @@ class IpsecTun6(object):
except:
self.logger.debug(ppp("Unexpected packet:", recv_pkt))
try:
- self.logger.debug(ppp("Decrypted packet:",
- decrypt_pkt))
+ self.logger.debug(ppp("Decrypted packet:", decrypt_pkt))
except:
pass
raise
@@ -1517,27 +1707,28 @@ class IpsecTun6(object):
class IpsecTun6Tests(IpsecTun6):
- """ UT test methods for Tunnel v6 """
+ """UT test methods for Tunnel v6"""
def test_tun_basic66(self):
- """ ipsec 6o6 tunnel basic test """
+ """ipsec 6o6 tunnel basic test"""
self.verify_tun_66(self.params[socket.AF_INET6], count=1)
def test_tun_reass_basic66(self):
- """ ipsec 6o6 tunnel basic reassembly test """
+ """ipsec 6o6 tunnel basic reassembly test"""
self.verify_tun_reass_66(self.params[socket.AF_INET6])
def test_tun_burst66(self):
- """ ipsec 6o6 tunnel burst test """
+ """ipsec 6o6 tunnel burst test"""
self.verify_tun_66(self.params[socket.AF_INET6], count=257)
class IpsecTun6HandoffTests(IpsecTun6):
- """ UT test methods for Tunnel v6 with multiple workers """
+ """UT test methods for Tunnel v6 with multiple workers"""
+
vpp_worker_count = 2
def test_tun_handoff_66(self):
- """ ipsec 6o6 tunnel worker hand-off test """
+ """ipsec 6o6 tunnel worker hand-off test"""
self.vapi.cli("clear errors")
self.vapi.cli("clear ipsec sa")
@@ -1547,31 +1738,42 @@ class IpsecTun6HandoffTests(IpsecTun6):
# inject alternately on worker 0 and 1. all counts on the SA
# should be against worker 0
for worker in [0, 1, 0, 1]:
- send_pkts = self.gen_encrypt_pkts6(p, p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip6,
- count=N_PKTS)
- recv_pkts = self.send_and_expect(self.tun_if, send_pkts,
- self.pg1, worker=worker)
+ send_pkts = self.gen_encrypt_pkts6(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip6,
+ count=N_PKTS,
+ )
+ recv_pkts = self.send_and_expect(
+ self.tun_if, send_pkts, self.pg1, worker=worker
+ )
self.verify_decrypted6(p, recv_pkts)
- send_pkts = self.gen_pkts6(p, self.pg1, src=self.pg1.remote_ip6,
- dst=p.remote_tun_if_host,
- count=N_PKTS)
- recv_pkts = self.send_and_expect(self.pg1, send_pkts,
- self.tun_if, worker=worker)
+ send_pkts = self.gen_pkts6(
+ p,
+ self.pg1,
+ src=self.pg1.remote_ip6,
+ dst=p.remote_tun_if_host,
+ count=N_PKTS,
+ )
+ recv_pkts = self.send_and_expect(
+ self.pg1, send_pkts, self.tun_if, worker=worker
+ )
self.verify_encrypted6(p, p.vpp_tun_sa, recv_pkts)
# all counts against the first worker that was used
- self.verify_counters6(p, p, 4*N_PKTS, worker=0)
+ self.verify_counters6(p, p, 4 * N_PKTS, worker=0)
class IpsecTun4HandoffTests(IpsecTun4):
- """ UT test methods for Tunnel v4 with multiple workers """
+ """UT test methods for Tunnel v4 with multiple workers"""
+
vpp_worker_count = 2
def test_tun_handooff_44(self):
- """ ipsec 4o4 tunnel worker hand-off test """
+ """ipsec 4o4 tunnel worker hand-off test"""
self.vapi.cli("clear errors")
self.vapi.cli("clear ipsec sa")
@@ -1581,32 +1783,43 @@ class IpsecTun4HandoffTests(IpsecTun4):
# inject alternately on worker 0 and 1. all counts on the SA
# should be against worker 0
for worker in [0, 1, 0, 1]:
- send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip4,
- count=N_PKTS)
- recv_pkts = self.send_and_expect(self.tun_if, send_pkts,
- self.pg1, worker=worker)
+ send_pkts = self.gen_encrypt_pkts(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip4,
+ count=N_PKTS,
+ )
+ recv_pkts = self.send_and_expect(
+ self.tun_if, send_pkts, self.pg1, worker=worker
+ )
self.verify_decrypted(p, recv_pkts)
- send_pkts = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4,
- dst=p.remote_tun_if_host,
- count=N_PKTS)
- recv_pkts = self.send_and_expect(self.pg1, send_pkts,
- self.tun_if, worker=worker)
+ send_pkts = self.gen_pkts(
+ self.pg1,
+ src=self.pg1.remote_ip4,
+ dst=p.remote_tun_if_host,
+ count=N_PKTS,
+ )
+ recv_pkts = self.send_and_expect(
+ self.pg1, send_pkts, self.tun_if, worker=worker
+ )
self.verify_encrypted(p, p.vpp_tun_sa, recv_pkts)
# all counts against the first worker that was used
- self.verify_counters4(p, 4*N_PKTS, worker=0)
+ self.verify_counters4(p, 4 * N_PKTS, worker=0)
class IpsecTun46Tests(IpsecTun4Tests, IpsecTun6Tests):
- """ UT test methods for Tunnel v6 & v4 """
+ """UT test methods for Tunnel v6 & v4"""
+
pass
class IPSecIPv4Fwd(VppTestCase):
- """ Test IPSec by capturing and verifying IPv4 forwarded pkts """
+ """Test IPSec by capturing and verifying IPv4 forwarded pkts"""
+
@classmethod
def setUpConstants(cls):
super(IPSecIPv4Fwd, cls).setUpConstants()
@@ -1664,9 +1877,18 @@ class IPSecIPv4Fwd(VppTestCase):
else:
raise Exception("Invalid policy type: %s", policy_type)
- def spd_add_rem_policy(self, spd_id, src_if, dst_if,
- proto, is_out, priority, policy_type,
- remove=False, all_ips=False):
+ def spd_add_rem_policy(
+ self,
+ spd_id,
+ src_if,
+ dst_if,
+ proto,
+ is_out,
+ priority,
+ policy_type,
+ remove=False,
+ all_ips=False,
+ ):
spd = VppIpsecSpd(self, spd_id)
if all_ips:
@@ -1680,17 +1902,21 @@ class IPSecIPv4Fwd(VppTestCase):
dst_range_low = dst_if.remote_ip4
dst_range_high = dst_if.remote_ip4
- spdEntry = VppIpsecSpdEntry(self, spd, 0,
- src_range_low,
- src_range_high,
- dst_range_low,
- dst_range_high,
- proto,
- priority=priority,
- policy=self.get_policy(policy_type),
- is_outbound=is_out)
-
- if(remove is False):
+ spdEntry = VppIpsecSpdEntry(
+ self,
+ spd,
+ 0,
+ src_range_low,
+ src_range_high,
+ dst_range_low,
+ dst_range_high,
+ proto,
+ priority=priority,
+ policy=self.get_policy(policy_type),
+ is_outbound=is_out,
+ )
+
+ if remove is False:
spdEntry.add_vpp_config()
self.spd_policies.append(spdEntry)
else:
@@ -1699,8 +1925,7 @@ class IPSecIPv4Fwd(VppTestCase):
self.logger.info(self.vapi.ppcli("show ipsec all"))
return spdEntry
- def create_stream(self, src_if, dst_if, pkt_count,
- src_prt=1234, dst_prt=5678):
+ def create_stream(self, src_if, dst_if, pkt_count, src_prt=1234, dst_prt=5678):
packets = []
for i in range(pkt_count):
# create packet info stored in the test case instance
@@ -1708,10 +1933,12 @@ class IPSecIPv4Fwd(VppTestCase):
# convert the info into packet payload
payload = self.info_to_payload(info)
# create the packet itself
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4) /
- UDP(sport=src_prt, dport=dst_prt) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4)
+ / UDP(sport=src_prt, dport=dst_prt)
+ / Raw(payload)
+ )
# store a copy of the packet in the packet info
info.data = p.copy()
# append the packet to the list
@@ -1728,43 +1955,41 @@ class IPSecIPv4Fwd(VppTestCase):
# convert the payload to packet info object
payload_info = self.payload_to_info(packet)
# make sure the indexes match
- self.assert_equal(payload_info.src, src_if.sw_if_index,
- "source sw_if_index")
- self.assert_equal(payload_info.dst, dst_if.sw_if_index,
- "destination sw_if_index")
+ self.assert_equal(
+ payload_info.src, src_if.sw_if_index, "source sw_if_index"
+ )
+ self.assert_equal(
+ payload_info.dst, dst_if.sw_if_index, "destination sw_if_index"
+ )
packet_info = self.get_next_packet_info_for_interface2(
- src_if.sw_if_index,
- dst_if.sw_if_index,
- packet_info)
+ src_if.sw_if_index, dst_if.sw_if_index, packet_info
+ )
# make sure we didn't run out of saved packets
self.assertIsNotNone(packet_info)
- self.assert_equal(payload_info.index, packet_info.index,
- "packet info index")
+ self.assert_equal(
+ payload_info.index, packet_info.index, "packet info index"
+ )
saved_packet = packet_info.data # fetch the saved packet
# assert the values match
- self.assert_equal(ip.src, saved_packet[IP].src,
- "IP source address")
+ self.assert_equal(ip.src, saved_packet[IP].src, "IP source address")
# ... more assertions here
- self.assert_equal(udp.sport, saved_packet[UDP].sport,
- "UDP source port")
+ self.assert_equal(udp.sport, saved_packet[UDP].sport, "UDP source port")
except Exception as e:
- self.logger.error(ppp("Unexpected or invalid packet:",
- packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
remaining_packet = self.get_next_packet_info_for_interface2(
- src_if.sw_if_index,
- dst_if.sw_if_index,
- packet_info)
- self.assertIsNone(remaining_packet,
- "Interface %s: Packet expected from interface "
- "%s didn't arrive" % (dst_if.name, src_if.name))
+ src_if.sw_if_index, dst_if.sw_if_index, packet_info
+ )
+ self.assertIsNone(
+ remaining_packet,
+ "Interface %s: Packet expected from interface "
+ "%s didn't arrive" % (dst_if.name, src_if.name),
+ )
def verify_policy_match(self, pkt_count, spdEntry):
- self.logger.info(
- "XXXX %s %s", str(spdEntry), str(spdEntry.get_stats()))
- matched_pkts = spdEntry.get_stats().get('packets')
- self.logger.info(
- "Policy %s matched: %d pkts", str(spdEntry), matched_pkts)
+ self.logger.info("XXXX %s %s", str(spdEntry), str(spdEntry.get_stats()))
+ matched_pkts = spdEntry.get_stats().get("packets")
+ self.logger.info("Policy %s matched: %d pkts", str(spdEntry), matched_pkts)
self.assert_equal(pkt_count, matched_pkts)
@@ -1786,43 +2011,52 @@ class SpdFlowCacheTemplate(IPSecIPv4Fwd):
super(SpdFlowCacheTemplate, self).tearDown()
def get_spd_flow_cache_entries(self, outbound):
- """ 'show ipsec spd' output:
+ """'show ipsec spd' output:
ipv4-inbound-spd-flow-cache-entries: 0
ipv4-outbound-spd-flow-cache-entries: 0
"""
show_ipsec_reply = self.vapi.cli("show ipsec spd")
# match the relevant section of 'show ipsec spd' output
- if(outbound):
+ if outbound:
regex_match = re.search(
- 'ipv4-outbound-spd-flow-cache-entries: (.*)',
- show_ipsec_reply, re.DOTALL)
+ "ipv4-outbound-spd-flow-cache-entries: (.*)",
+ show_ipsec_reply,
+ re.DOTALL,
+ )
else:
regex_match = re.search(
- 'ipv4-inbound-spd-flow-cache-entries: (.*)',
- show_ipsec_reply, re.DOTALL)
+ "ipv4-inbound-spd-flow-cache-entries: (.*)", show_ipsec_reply, re.DOTALL
+ )
if regex_match is None:
- raise Exception("Unable to find spd flow cache entries \
- in \'show ipsec spd\' CLI output - regex failed to match")
+ raise Exception(
+ "Unable to find spd flow cache entries \
+ in 'show ipsec spd' CLI output - regex failed to match"
+ )
else:
try:
num_entries = int(regex_match.group(1))
except ValueError:
- raise Exception("Unable to get spd flow cache entries \
- from \'show ipsec spd\' string: %s", regex_match.group(0))
+ raise Exception(
+ "Unable to get spd flow cache entries \
+ from 'show ipsec spd' string: %s",
+ regex_match.group(0),
+ )
self.logger.info("%s", regex_match.group(0))
return num_entries
def verify_num_outbound_flow_cache_entries(self, expected_elements):
- self.assertEqual(self.get_spd_flow_cache_entries(outbound=True),
- expected_elements)
+ self.assertEqual(
+ self.get_spd_flow_cache_entries(outbound=True), expected_elements
+ )
def verify_num_inbound_flow_cache_entries(self, expected_elements):
- self.assertEqual(self.get_spd_flow_cache_entries(outbound=False),
- expected_elements)
+ self.assertEqual(
+ self.get_spd_flow_cache_entries(outbound=False), expected_elements
+ )
def crc32_supported(self):
# lscpu is part of util-linux package, available on all Linux Distros
- stream = os.popen('lscpu')
+ stream = os.popen("lscpu")
cpu_info = stream.read()
# feature/flag "crc32" on Aarch64 and "sse4_2" on x86
# see vppinfra/crc32.h
@@ -1833,5 +2067,6 @@ class SpdFlowCacheTemplate(IPSecIPv4Fwd):
self.logger.info("\ncrc32 NOT supported:\n" + cpu_info)
return False
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_abf.py b/test/test_abf.py
index 097476b879a..856d02a8185 100644
--- a/test/test_abf.py
+++ b/test/test_abf.py
@@ -5,8 +5,13 @@ import unittest
from framework import VppTestCase, VppTestRunner
from vpp_ip import DpoProto
-from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsLabel, \
- VppIpTable, FibPathProto
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ VppMplsLabel,
+ VppIpTable,
+ FibPathProto,
+)
from vpp_acl import AclRule, VppAcl
from scapy.packet import Raw
@@ -31,19 +36,13 @@ def find_abf_policy(test, id):
def find_abf_itf_attach(test, id, sw_if_index):
attachs = test.vapi.abf_itf_attach_dump()
for a in attachs:
- if id == a.attach.policy_id and \
- sw_if_index == a.attach.sw_if_index:
+ if id == a.attach.policy_id and sw_if_index == a.attach.sw_if_index:
return True
return False
class VppAbfPolicy(VppObject):
-
- def __init__(self,
- test,
- policy_id,
- acl,
- paths):
+ def __init__(self, test, policy_id, acl, paths):
self._test = test
self.policy_id = policy_id
self.acl = acl
@@ -55,35 +54,35 @@ class VppAbfPolicy(VppObject):
def add_vpp_config(self):
self._test.vapi.abf_policy_add_del(
1,
- {'policy_id': self.policy_id,
- 'acl_index': self.acl.acl_index,
- 'n_paths': len(self.paths),
- 'paths': self.encoded_paths})
+ {
+ "policy_id": self.policy_id,
+ "acl_index": self.acl.acl_index,
+ "n_paths": len(self.paths),
+ "paths": self.encoded_paths,
+ },
+ )
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
self._test.vapi.abf_policy_add_del(
0,
- {'policy_id': self.policy_id,
- 'acl_index': self.acl.acl_index,
- 'n_paths': len(self.paths),
- 'paths': self.encoded_paths})
+ {
+ "policy_id": self.policy_id,
+ "acl_index": self.acl.acl_index,
+ "n_paths": len(self.paths),
+ "paths": self.encoded_paths,
+ },
+ )
def query_vpp_config(self):
return find_abf_policy(self._test, self.policy_id)
def object_id(self):
- return ("abf-policy-%d" % self.policy_id)
+ return "abf-policy-%d" % self.policy_id
class VppAbfAttach(VppObject):
-
- def __init__(self,
- test,
- policy_id,
- sw_if_index,
- priority,
- is_ipv6=0):
+ def __init__(self, test, policy_id, sw_if_index, priority, is_ipv6=0):
self._test = test
self.policy_id = policy_id
self.sw_if_index = sw_if_index
@@ -93,31 +92,35 @@ class VppAbfAttach(VppObject):
def add_vpp_config(self):
self._test.vapi.abf_itf_attach_add_del(
1,
- {'policy_id': self.policy_id,
- 'sw_if_index': self.sw_if_index,
- 'priority': self.priority,
- 'is_ipv6': self.is_ipv6})
+ {
+ "policy_id": self.policy_id,
+ "sw_if_index": self.sw_if_index,
+ "priority": self.priority,
+ "is_ipv6": self.is_ipv6,
+ },
+ )
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
self._test.vapi.abf_itf_attach_add_del(
0,
- {'policy_id': self.policy_id,
- 'sw_if_index': self.sw_if_index,
- 'priority': self.priority,
- 'is_ipv6': self.is_ipv6})
+ {
+ "policy_id": self.policy_id,
+ "sw_if_index": self.sw_if_index,
+ "priority": self.priority,
+ "is_ipv6": self.is_ipv6,
+ },
+ )
def query_vpp_config(self):
- return find_abf_itf_attach(self._test,
- self.policy_id,
- self.sw_if_index)
+ return find_abf_itf_attach(self._test, self.policy_id, self.sw_if_index)
def object_id(self):
- return ("abf-attach-%d-%d" % (self.policy_id, self.sw_if_index))
+ return "abf-attach-%d-%d" % (self.policy_id, self.sw_if_index)
class TestAbf(VppTestCase):
- """ ABF Test Case """
+ """ABF Test Case"""
@classmethod
def setUpClass(cls):
@@ -147,8 +150,7 @@ class TestAbf(VppTestCase):
super(TestAbf, self).tearDown()
def test_abf4(self):
- """ IPv4 ACL Based Forwarding
- """
+ """IPv4 ACL Based Forwarding"""
#
# We are not testing the various matching capabilities
@@ -163,18 +165,22 @@ class TestAbf(VppTestCase):
#
# Rule 1
#
- rule_1 = AclRule(is_permit=1, proto=17, ports=1234,
- src_prefix=IPv4Network("1.1.1.1/32"),
- dst_prefix=IPv4Network("1.1.1.2/32"))
+ rule_1 = AclRule(
+ is_permit=1,
+ proto=17,
+ ports=1234,
+ src_prefix=IPv4Network("1.1.1.1/32"),
+ dst_prefix=IPv4Network("1.1.1.2/32"),
+ )
acl_1 = VppAcl(self, rules=[rule_1])
acl_1.add_vpp_config()
#
# ABF policy for ACL 1 - path via interface 1
#
- abf_1 = VppAbfPolicy(self, 10, acl_1,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ abf_1 = VppAbfPolicy(
+ self, 10, acl_1, [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)]
+ )
abf_1.add_vpp_config()
#
@@ -187,42 +193,43 @@ class TestAbf(VppTestCase):
# fire in packet matching the ACL src,dst. If it's forwarded
# then the ABF was successful, since default routing will drop it
#
- p_1 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg1)
+ p_1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg1)
#
# Attach a 'better' priority policy to the same interface
#
- abf_2 = VppAbfPolicy(self, 11, acl_1,
- [VppRoutePath(self.pg2.remote_ip4,
- self.pg2.sw_if_index)])
+ abf_2 = VppAbfPolicy(
+ self, 11, acl_1, [VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index)]
+ )
abf_2.add_vpp_config()
attach_2 = VppAbfAttach(self, 11, self.pg0.sw_if_index, 40)
attach_2.add_vpp_config()
- self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg2)
+ self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg2)
#
# Attach a policy with priority in the middle
#
- abf_3 = VppAbfPolicy(self, 12, acl_1,
- [VppRoutePath(self.pg3.remote_ip4,
- self.pg3.sw_if_index)])
+ abf_3 = VppAbfPolicy(
+ self, 12, acl_1, [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)]
+ )
abf_3.add_vpp_config()
attach_3 = VppAbfAttach(self, 12, self.pg0.sw_if_index, 45)
attach_3.add_vpp_config()
- self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg2)
+ self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg2)
#
# remove the best priority
#
attach_2.remove_vpp_config()
- self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg3)
+ self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg3)
#
# Attach one of the same policies to Pg1
@@ -230,11 +237,12 @@ class TestAbf(VppTestCase):
attach_4 = VppAbfAttach(self, 12, self.pg1.sw_if_index, 45)
attach_4.add_vpp_config()
- p_2 = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_2 = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect(self.pg1, p_2 * NUM_PKTS, self.pg3)
#
@@ -255,22 +263,27 @@ class TestAbf(VppTestCase):
self.pg4.config_ip4()
self.pg4.resolve_arp()
- abf_13 = VppAbfPolicy(self, 13, acl_1,
- [VppRoutePath(self.pg4.remote_ip4,
- 0xffffffff,
- nh_table_id=table_20.table_id)])
+ abf_13 = VppAbfPolicy(
+ self,
+ 13,
+ acl_1,
+ [
+ VppRoutePath(
+ self.pg4.remote_ip4, 0xFFFFFFFF, nh_table_id=table_20.table_id
+ )
+ ],
+ )
abf_13.add_vpp_config()
attach_5 = VppAbfAttach(self, 13, self.pg0.sw_if_index, 30)
attach_5.add_vpp_config()
- self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg4)
+ self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg4)
self.pg4.unconfig_ip4()
self.pg4.set_table_ip4(0)
def test_abf6(self):
- """ IPv6 ACL Based Forwarding
- """
+ """IPv6 ACL Based Forwarding"""
#
# Simple test for matching IPv6 packets
@@ -279,32 +292,34 @@ class TestAbf(VppTestCase):
#
# Rule 1
#
- rule_1 = AclRule(is_permit=1, proto=17, ports=1234,
- src_prefix=IPv6Network("2001::2/128"),
- dst_prefix=IPv6Network("2001::1/128"))
+ rule_1 = AclRule(
+ is_permit=1,
+ proto=17,
+ ports=1234,
+ src_prefix=IPv6Network("2001::2/128"),
+ dst_prefix=IPv6Network("2001::1/128"),
+ )
acl_1 = VppAcl(self, rules=[rule_1])
acl_1.add_vpp_config()
#
# ABF policy for ACL 1 - path via interface 1
#
- abf_1 = VppAbfPolicy(self, 10, acl_1,
- [VppRoutePath("3001::1",
- 0xffffffff)])
+ abf_1 = VppAbfPolicy(self, 10, acl_1, [VppRoutePath("3001::1", 0xFFFFFFFF)])
abf_1.add_vpp_config()
- attach_1 = VppAbfAttach(self, 10, self.pg0.sw_if_index,
- 45, is_ipv6=True)
+ attach_1 = VppAbfAttach(self, 10, self.pg0.sw_if_index, 45, is_ipv6=True)
attach_1.add_vpp_config()
#
# a packet matching the rule
#
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src="2001::2", dst="2001::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src="2001::2", dst="2001::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# packets are dropped because there is no route to the policy's
@@ -315,9 +330,12 @@ class TestAbf(VppTestCase):
#
# add a route resolving the next-hop
#
- route = VppIpRoute(self, "3001::1", 32,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ route = VppIpRoute(
+ self,
+ "3001::1",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ )
route.add_vpp_config()
#
@@ -326,5 +344,5 @@ class TestAbf(VppTestCase):
self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_acl_plugin.py b/test/test_acl_plugin.py
index 53d96215949..32ecedba2a6 100644
--- a/test/test_acl_plugin.py
+++ b/test/test_acl_plugin.py
@@ -22,7 +22,7 @@ from vpp_ip import INVALID_INDEX
@tag_fixme_vpp_workers
class TestACLplugin(VppTestCase):
- """ ACL plugin Test Case """
+ """ACL plugin Test Case"""
# traffic types
IP = 0
@@ -39,7 +39,7 @@ class TestACLplugin(VppTestCase):
# supported protocols
proto = [[6, 17], [1, 58]]
- proto_map = {1: 'ICMP', 58: 'ICMPv6EchoRequest', 6: 'TCP', 17: 'UDP'}
+ proto_map = {1: "ICMP", 58: "ICMPv6EchoRequest", 6: "TCP", 17: "UDP"}
ICMPv4 = 0
ICMPv6 = 1
TCP = 0
@@ -105,11 +105,11 @@ class TestACLplugin(VppTestCase):
# Create BD with MAC learning and unknown unicast flooding disabled
# and put interfaces to this BD
- cls.vapi.bridge_domain_add_del(bd_id=cls.bd_id, uu_flood=1,
- learn=1)
+ cls.vapi.bridge_domain_add_del(bd_id=cls.bd_id, uu_flood=1, learn=1)
for pg_if in cls.pg_interfaces:
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=pg_if.sw_if_index, bd_id=cls.bd_id)
+ rx_sw_if_index=pg_if.sw_if_index, bd_id=cls.bd_id
+ )
# Set up all interfaces
for i in cls.pg_interfaces:
@@ -135,14 +135,16 @@ class TestACLplugin(VppTestCase):
for pg_if in cls.pg_interfaces:
i += 1
start_nr = macs_per_if * i + start
- end_nr = count + start if i == (n_int - 1) \
- else macs_per_if * (i + 1) + start
+ end_nr = (
+ count + start if i == (n_int - 1) else macs_per_if * (i + 1) + start
+ )
hosts = cls.hosts_by_pg_idx[pg_if.sw_if_index]
for j in range(int(start_nr), int(end_nr)):
host = Host(
"00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j),
"172.17.1%02x.%u" % (pg_if.sw_if_index, j),
- "2017:dead:%02x::%u" % (pg_if.sw_if_index, j))
+ "2017:dead:%02x::%u" % (pg_if.sw_if_index, j),
+ )
hosts.append(host)
except Exception:
@@ -176,20 +178,32 @@ class TestACLplugin(VppTestCase):
self.logger.info(self.vapi.ppcli("show acl-plugin acl"))
self.logger.info(self.vapi.ppcli("show acl-plugin interface"))
self.logger.info(self.vapi.ppcli("show acl-plugin tables"))
- self.logger.info(self.vapi.ppcli("show bridge-domain %s detail"
- % self.bd_id))
-
- def create_rule(self, ip=0, permit_deny=0, ports=PORTS_ALL, proto=-1,
- s_prefix=0, s_ip=0,
- d_prefix=0, d_ip=0):
+ self.logger.info(self.vapi.ppcli("show bridge-domain %s detail" % self.bd_id))
+
+ def create_rule(
+ self,
+ ip=0,
+ permit_deny=0,
+ ports=PORTS_ALL,
+ proto=-1,
+ s_prefix=0,
+ s_ip=0,
+ d_prefix=0,
+ d_ip=0,
+ ):
if ip:
src_prefix = IPv6Network((s_ip, s_prefix))
dst_prefix = IPv6Network((d_ip, d_prefix))
else:
src_prefix = IPv4Network((s_ip, s_prefix))
dst_prefix = IPv4Network((d_ip, d_prefix))
- return AclRule(is_permit=permit_deny, ports=ports, proto=proto,
- src_prefix=src_prefix, dst_prefix=dst_prefix)
+ return AclRule(
+ is_permit=permit_deny,
+ ports=ports,
+ proto=proto,
+ src_prefix=src_prefix,
+ dst_prefix=dst_prefix,
+ )
def apply_rules(self, rules, tag=None):
acl = VppAcl(self, rules, tag=tag)
@@ -198,7 +212,8 @@ class TestACLplugin(VppTestCase):
# Apply a ACL on the interface as inbound
for i in self.pg_interfaces:
acl_if = VppAclInterface(
- self, sw_if_index=i.sw_if_index, n_input=1, acls=[acl])
+ self, sw_if_index=i.sw_if_index, n_input=1, acls=[acl]
+ )
acl_if.add_vpp_config()
return acl.acl_index
@@ -207,8 +222,7 @@ class TestACLplugin(VppTestCase):
acl.add_vpp_config()
self.logger.info("Dumped ACL: " + str(acl.dump()))
# Apply a ACL on the interface as inbound
- acl_if = VppAclInterface(self, sw_if_index=sw_if_index, n_input=1,
- acls=[acl])
+ acl_if = VppAclInterface(self, sw_if_index=sw_if_index, n_input=1, acls=[acl])
return acl.acl_index
def etype_whitelist(self, whitelist, n_input, add=True):
@@ -216,9 +230,14 @@ class TestACLplugin(VppTestCase):
if add:
self._wl = []
for i in self.pg_interfaces:
- self._wl.append(VppEtypeWhitelist(
- self, sw_if_index=i.sw_if_index, whitelist=whitelist,
- n_input=n_input).add_vpp_config())
+ self._wl.append(
+ VppEtypeWhitelist(
+ self,
+ sw_if_index=i.sw_if_index,
+ whitelist=whitelist,
+ n_input=n_input,
+ ).add_vpp_config()
+ )
else:
if hasattr(self, "_wl"):
for wl in self._wl:
@@ -226,27 +245,36 @@ class TestACLplugin(VppTestCase):
def create_upper_layer(self, packet_index, proto, ports=0):
p = self.proto_map[proto]
- if p == 'UDP':
+ if p == "UDP":
if ports == 0:
- return UDP(sport=random.randint(self.udp_sport_from,
- self.udp_sport_to),
- dport=random.randint(self.udp_dport_from,
- self.udp_dport_to))
+ return UDP(
+ sport=random.randint(self.udp_sport_from, self.udp_sport_to),
+ dport=random.randint(self.udp_dport_from, self.udp_dport_to),
+ )
else:
return UDP(sport=ports, dport=ports)
- elif p == 'TCP':
+ elif p == "TCP":
if ports == 0:
- return TCP(sport=random.randint(self.tcp_sport_from,
- self.tcp_sport_to),
- dport=random.randint(self.tcp_dport_from,
- self.tcp_dport_to))
+ return TCP(
+ sport=random.randint(self.tcp_sport_from, self.tcp_sport_to),
+ dport=random.randint(self.tcp_dport_from, self.tcp_dport_to),
+ )
else:
return TCP(sport=ports, dport=ports)
- return ''
-
- def create_stream(self, src_if, packet_sizes, traffic_type=0, ipv6=0,
- proto=-1, ports=0, fragments=False,
- pkt_raw=True, etype=-1):
+ return ""
+
+ def create_stream(
+ self,
+ src_if,
+ packet_sizes,
+ traffic_type=0,
+ ipv6=0,
+ proto=-1,
+ ports=0,
+ fragments=False,
+ pkt_raw=True,
+ etype=-1,
+ ):
"""
Create input packet stream for defined interface using hosts or
deleted_hosts list.
@@ -279,26 +307,25 @@ class TestACLplugin(VppTestCase):
payload = self.info_to_payload(pkt_info)
p = Ether(dst=dst_host.mac, src=src_host.mac)
if etype > 0:
- p = Ether(dst=dst_host.mac,
- src=src_host.mac,
- type=etype)
+ p = Ether(dst=dst_host.mac, src=src_host.mac, type=etype)
if pkt_info.ip:
p /= IPv6(dst=dst_host.ip6, src=src_host.ip6)
if fragments:
p /= IPv6ExtHdrFragment(offset=64, m=1)
else:
if fragments:
- p /= IP(src=src_host.ip4, dst=dst_host.ip4,
- flags=1, frag=64)
+ p /= IP(
+ src=src_host.ip4, dst=dst_host.ip4, flags=1, frag=64
+ )
else:
p /= IP(src=src_host.ip4, dst=dst_host.ip4)
if traffic_type == self.ICMP:
if pkt_info.ip:
- p /= ICMPv6EchoRequest(type=self.icmp6_type,
- code=self.icmp6_code)
+ p /= ICMPv6EchoRequest(
+ type=self.icmp6_type, code=self.icmp6_code
+ )
else:
- p /= ICMP(type=self.icmp4_type,
- code=self.icmp4_code)
+ p /= ICMP(type=self.icmp4_type, code=self.icmp4_code)
else:
p /= self.create_upper_layer(i, pkt_info.proto, ports)
if pkt_raw:
@@ -310,8 +337,7 @@ class TestACLplugin(VppTestCase):
pkts.append(p)
return pkts
- def verify_capture(self, pg_if, capture,
- traffic_type=0, ip_type=0, etype=-1):
+ def verify_capture(self, pg_if, capture, traffic_type=0, ip_type=0, etype=-1):
"""
Verify captured input packet stream for defined interface.
@@ -326,22 +352,23 @@ class TestACLplugin(VppTestCase):
for packet in capture:
if etype > 0:
if packet[Ether].type != etype:
- self.logger.error(ppp("Unexpected ethertype in packet:",
- packet))
+ self.logger.error(ppp("Unexpected ethertype in packet:", packet))
else:
continue
try:
# Raw data for ICMPv6 are stored in ICMPv6EchoRequest.data
if traffic_type == self.ICMP and ip_type == self.IPV6:
payload_info = self.payload_to_info(
- packet[ICMPv6EchoRequest], 'data')
+ packet[ICMPv6EchoRequest], "data"
+ )
payload = packet[ICMPv6EchoRequest]
else:
payload_info = self.payload_to_info(packet[Raw])
payload = packet[self.proto_map[payload_info.proto]]
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(outside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (outside network):", packet)
+ )
raise
if ip_type != 0:
@@ -355,8 +382,9 @@ class TestACLplugin(VppTestCase):
self.assertEqual(payload.type, self.icmp6_type)
self.assertEqual(payload.code, self.icmp6_code)
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(outside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (outside network):", packet)
+ )
raise
else:
try:
@@ -366,12 +394,13 @@ class TestACLplugin(VppTestCase):
packet_index = payload_info.index
self.assertEqual(payload_info.dst, dst_sw_if_index)
- self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
- (pg_if.name, payload_info.src,
- packet_index))
+ self.logger.debug(
+ "Got packet on port %s: src=%u (id=%u)"
+ % (pg_if.name, payload_info.src, packet_index)
+ )
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
self.assertEqual(packet_index, next_info.index)
@@ -380,29 +409,26 @@ class TestACLplugin(VppTestCase):
self.assertEqual(ip.src, saved_packet[ip_version].src)
self.assertEqual(ip.dst, saved_packet[ip_version].dst)
p = self.proto_map[payload_info.proto]
- if p == 'TCP':
+ if p == "TCP":
tcp = packet[TCP]
- self.assertEqual(tcp.sport, saved_packet[
- TCP].sport)
- self.assertEqual(tcp.dport, saved_packet[
- TCP].dport)
- elif p == 'UDP':
+ self.assertEqual(tcp.sport, saved_packet[TCP].sport)
+ self.assertEqual(tcp.dport, saved_packet[TCP].dport)
+ elif p == "UDP":
udp = packet[UDP]
- self.assertEqual(udp.sport, saved_packet[
- UDP].sport)
- self.assertEqual(udp.dport, saved_packet[
- UDP].dport)
+ self.assertEqual(udp.sport, saved_packet[UDP].sport)
+ self.assertEqual(udp.dport, saved_packet[UDP].dport)
except:
- self.logger.error(ppp("Unexpected or invalid packet:",
- packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
for i in self.pg_interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i, dst_sw_if_index, last_info[i.sw_if_index])
+ i, dst_sw_if_index, last_info[i.sw_if_index]
+ )
self.assertTrue(
remaining_packet is None,
- "Port %u: Packet expected from source %u didn't arrive" %
- (dst_sw_if_index, i.sw_if_index))
+ "Port %u: Packet expected from source %u didn't arrive"
+ % (dst_sw_if_index, i.sw_if_index),
+ )
def run_traffic_no_check(self):
# Test
@@ -417,16 +443,32 @@ class TestACLplugin(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- def run_verify_test(self, traffic_type=0, ip_type=0, proto=-1, ports=0,
- frags=False, pkt_raw=True, etype=-1):
+ def run_verify_test(
+ self,
+ traffic_type=0,
+ ip_type=0,
+ proto=-1,
+ ports=0,
+ frags=False,
+ pkt_raw=True,
+ etype=-1,
+ ):
# Test
# Create incoming packet streams for packet-generator interfaces
pkts_cnt = 0
for i in self.pg_interfaces:
if self.flows.__contains__(i):
- pkts = self.create_stream(i, self.pg_if_packet_sizes,
- traffic_type, ip_type, proto, ports,
- frags, pkt_raw, etype)
+ pkts = self.create_stream(
+ i,
+ self.pg_if_packet_sizes,
+ traffic_type,
+ ip_type,
+ proto,
+ ports,
+ frags,
+ pkt_raw,
+ etype,
+ )
if len(pkts) > 0:
i.add_stream(pkts)
pkts_cnt += len(pkts)
@@ -442,21 +484,28 @@ class TestACLplugin(VppTestCase):
if self.flows.__contains__(src_if):
for dst_if in self.flows[src_if]:
capture = dst_if.get_capture(pkts_cnt)
- self.logger.info("Verifying capture on interface %s" %
- dst_if.name)
- self.verify_capture(dst_if, capture,
- traffic_type, ip_type, etype)
+ self.logger.info("Verifying capture on interface %s" % dst_if.name)
+ self.verify_capture(dst_if, capture, traffic_type, ip_type, etype)
- def run_verify_negat_test(self, traffic_type=0, ip_type=0, proto=-1,
- ports=0, frags=False, etype=-1):
+ def run_verify_negat_test(
+ self, traffic_type=0, ip_type=0, proto=-1, ports=0, frags=False, etype=-1
+ ):
# Test
pkts_cnt = 0
self.reset_packet_infos()
for i in self.pg_interfaces:
if self.flows.__contains__(i):
- pkts = self.create_stream(i, self.pg_if_packet_sizes,
- traffic_type, ip_type, proto, ports,
- frags, True, etype)
+ pkts = self.create_stream(
+ i,
+ self.pg_if_packet_sizes,
+ traffic_type,
+ ip_type,
+ proto,
+ ports,
+ frags,
+ True,
+ etype,
+ )
if len(pkts) > 0:
i.add_stream(pkts)
pkts_cnt += len(pkts)
@@ -471,24 +520,22 @@ class TestACLplugin(VppTestCase):
for src_if in self.pg_interfaces:
if self.flows.__contains__(src_if):
for dst_if in self.flows[src_if]:
- self.logger.info("Verifying capture on interface %s" %
- dst_if.name)
+ self.logger.info("Verifying capture on interface %s" % dst_if.name)
capture = dst_if.get_capture(0)
self.assertEqual(len(capture), 0)
def test_0000_warmup_test(self):
- """ ACL plugin version check; learn MACs
- """
+ """ACL plugin version check; learn MACs"""
reply = self.vapi.papi.acl_plugin_get_version()
self.assertEqual(reply.major, 1)
- self.logger.info("Working with ACL plugin version: %d.%d" % (
- reply.major, reply.minor))
+ self.logger.info(
+ "Working with ACL plugin version: %d.%d" % (reply.major, reply.minor)
+ )
# minor version changes are non breaking
# self.assertEqual(reply.minor, 0)
def test_0001_acl_create(self):
- """ ACL create/delete test
- """
+ """ACL create/delete test"""
self.logger.info("ACLP_TEST_START_0001")
# Create a permit-1234 ACL
@@ -510,12 +557,13 @@ class TestACLplugin(VppTestCase):
for i_rule in range(0, len(r) - 1):
encoded_rule = r[i_rule].encode()
for rule_key in encoded_rule:
- self.assertEqual(rr[0].r[i_rule][rule_key],
- encoded_rule[rule_key])
+ self.assertEqual(rr[0].r[i_rule][rule_key], encoded_rule[rule_key])
# Create a deny-1234 ACL
- r_deny = [AclRule(is_permit=0, proto=17, ports=1234, sport_to=1235),
- AclRule(is_permit=1, proto=17, ports=0)]
+ r_deny = [
+ AclRule(is_permit=0, proto=17, ports=1234, sport_to=1235),
+ AclRule(is_permit=1, proto=17, ports=0),
+ ]
second_acl = VppAcl(self, rules=r_deny, tag="deny 1234;permit all")
second_acl.add_vpp_config()
self.assertTrue(second_acl.query_vpp_config())
@@ -528,8 +576,8 @@ class TestACLplugin(VppTestCase):
# apply an ACL on an interface inbound, try to delete ACL, must fail
acl_if_list = VppAclInterface(
- self, sw_if_index=self.pg0.sw_if_index, n_input=1,
- acls=[first_acl])
+ self, sw_if_index=self.pg0.sw_if_index, n_input=1, acls=[first_acl]
+ )
acl_if_list.add_vpp_config()
first_acl.remove_vpp_config(expect_error=True)
# Unapply an ACL and then try to delete it - must be ok
@@ -538,8 +586,8 @@ class TestACLplugin(VppTestCase):
# apply an ACL on an interface inbound, try to delete ACL, must fail
acl_if_list = VppAclInterface(
- self, sw_if_index=self.pg0.sw_if_index, n_input=0,
- acls=[second_acl])
+ self, sw_if_index=self.pg0.sw_if_index, n_input=0, acls=[second_acl]
+ )
acl_if_list.add_vpp_config()
second_acl.remove_vpp_config(expect_error=True)
# Unapply an ACL and then try to delete it - must be ok
@@ -548,22 +596,23 @@ class TestACLplugin(VppTestCase):
# try to apply a nonexistent ACL - must fail
acl_if_list = VppAclInterface(
- self, sw_if_index=self.pg0.sw_if_index, n_input=0,
- acls=[invalid_acl])
+ self, sw_if_index=self.pg0.sw_if_index, n_input=0, acls=[invalid_acl]
+ )
acl_if_list.add_vpp_config(expect_error=True)
self.logger.info("ACLP_TEST_FINISH_0001")
def test_0002_acl_permit_apply(self):
- """ permit ACL apply test
- """
+ """permit ACL apply test"""
self.logger.info("ACLP_TEST_START_0002")
rules = []
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- 0, self.proto[self.IP][self.UDP]))
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- 0, self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.UDP])
+ )
+ rules.append(
+ self.create_rule(self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.TCP])
+ )
# Apply rules
acl_idx = self.apply_rules(rules, "permit per-flow")
@@ -574,14 +623,14 @@ class TestACLplugin(VppTestCase):
# Traffic should still pass
self.run_verify_test(self.IP, self.IPV4, -1)
- matches = self.statistics.get_counter('/acl/%d/matches' % acl_idx)
+ matches = self.statistics.get_counter("/acl/%d/matches" % acl_idx)
self.logger.info("stat segment counters: %s" % repr(matches))
cli = "show acl-plugin acl"
self.logger.info(self.vapi.ppcli(cli))
cli = "show acl-plugin tables"
self.logger.info(self.vapi.ppcli(cli))
- total_hits = matches[0][0]['packets'] + matches[0][1]['packets']
+ total_hits = matches[0][0]["packets"] + matches[0][1]["packets"]
self.assertEqual(total_hits, 64)
# disable counters
@@ -590,17 +639,17 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0002")
def test_0003_acl_deny_apply(self):
- """ deny ACL apply test
- """
+ """deny ACL apply test"""
self.logger.info("ACLP_TEST_START_0003")
# Add a deny-flows ACL
rules = []
- rules.append(self.create_rule(
- self.IPV4, self.DENY, self.PORTS_ALL,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_ALL, self.proto[self.IP][self.UDP]
+ )
+ )
# Permit ip any any in the end
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0))
# Apply rules
acl_idx = self.apply_rules(rules, "deny per-flow;permit all")
@@ -609,30 +658,34 @@ class TestACLplugin(VppTestCase):
reply = self.vapi.papi.acl_stats_intf_counters_enable(enable=1)
# Traffic should not pass
- self.run_verify_negat_test(self.IP, self.IPV4,
- self.proto[self.IP][self.UDP])
+ self.run_verify_negat_test(self.IP, self.IPV4, self.proto[self.IP][self.UDP])
- matches = self.statistics.get_counter('/acl/%d/matches' % acl_idx)
+ matches = self.statistics.get_counter("/acl/%d/matches" % acl_idx)
self.logger.info("stat segment counters: %s" % repr(matches))
cli = "show acl-plugin acl"
self.logger.info(self.vapi.ppcli(cli))
cli = "show acl-plugin tables"
self.logger.info(self.vapi.ppcli(cli))
- self.assertEqual(matches[0][0]['packets'], 64)
+ self.assertEqual(matches[0][0]["packets"], 64)
# disable counters
reply = self.vapi.papi.acl_stats_intf_counters_enable(enable=0)
self.logger.info("ACLP_TEST_FINISH_0003")
# self.assertEqual(, 0)
def test_0004_vpp624_permit_icmpv4(self):
- """ VPP_624 permit ICMPv4
- """
+ """VPP_624 permit ICMPv4"""
self.logger.info("ACLP_TEST_START_0004")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.ICMP][self.ICMPv4]))
+ rules.append(
+ self.create_rule(
+ self.IPV4,
+ self.PERMIT,
+ self.PORTS_RANGE,
+ self.proto[self.ICMP][self.ICMPv4],
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
@@ -640,20 +693,24 @@ class TestACLplugin(VppTestCase):
self.apply_rules(rules, "permit icmpv4")
# Traffic should still pass
- self.run_verify_test(self.ICMP, self.IPV4,
- self.proto[self.ICMP][self.ICMPv4])
+ self.run_verify_test(self.ICMP, self.IPV4, self.proto[self.ICMP][self.ICMPv4])
self.logger.info("ACLP_TEST_FINISH_0004")
def test_0005_vpp624_permit_icmpv6(self):
- """ VPP_624 permit ICMPv6
- """
+ """VPP_624 permit ICMPv6"""
self.logger.info("ACLP_TEST_START_0005")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.ICMP][self.ICMPv6]))
+ rules.append(
+ self.create_rule(
+ self.IPV6,
+ self.PERMIT,
+ self.PORTS_RANGE,
+ self.proto[self.ICMP][self.ICMPv6],
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0))
@@ -661,22 +718,25 @@ class TestACLplugin(VppTestCase):
self.apply_rules(rules, "permit icmpv6")
# Traffic should still pass
- self.run_verify_test(self.ICMP, self.IPV6,
- self.proto[self.ICMP][self.ICMPv6])
+ self.run_verify_test(self.ICMP, self.IPV6, self.proto[self.ICMP][self.ICMPv6])
self.logger.info("ACLP_TEST_FINISH_0005")
def test_0006_vpp624_deny_icmpv4(self):
- """ VPP_624 deny ICMPv4
- """
+ """VPP_624 deny ICMPv4"""
self.logger.info("ACLP_TEST_START_0006")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE,
- self.proto[self.ICMP][self.ICMPv4]))
+ rules.append(
+ self.create_rule(
+ self.IPV4,
+ self.DENY,
+ self.PORTS_RANGE,
+ self.proto[self.ICMP][self.ICMPv4],
+ )
+ )
# permit ip any any in the end
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "deny icmpv4")
@@ -687,16 +747,20 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0006")
def test_0007_vpp624_deny_icmpv6(self):
- """ VPP_624 deny ICMPv6
- """
+ """VPP_624 deny ICMPv6"""
self.logger.info("ACLP_TEST_START_0007")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE,
- self.proto[self.ICMP][self.ICMPv6]))
+ rules.append(
+ self.create_rule(
+ self.IPV6,
+ self.DENY,
+ self.PORTS_RANGE,
+ self.proto[self.ICMP][self.ICMPv6],
+ )
+ )
# deny ip any any in the end
- rules.append(self.create_rule(self.IPV6, self.PERMIT,
- self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "deny icmpv6")
@@ -707,14 +771,16 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0007")
def test_0008_tcp_permit_v4(self):
- """ permit TCPv4
- """
+ """permit TCPv4"""
self.logger.info("ACLP_TEST_START_0008")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
@@ -727,14 +793,16 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0008")
def test_0009_tcp_permit_v6(self):
- """ permit TCPv6
- """
+ """permit TCPv6"""
self.logger.info("ACLP_TEST_START_0009")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0))
@@ -747,14 +815,16 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0008")
def test_0010_udp_permit_v4(self):
- """ permit UDPv4
- """
+ """permit UDPv4"""
self.logger.info("ACLP_TEST_START_0010")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.UDP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
@@ -767,14 +837,16 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0010")
def test_0011_udp_permit_v6(self):
- """ permit UDPv6
- """
+ """permit UDPv6"""
self.logger.info("ACLP_TEST_START_0011")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.UDP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0))
@@ -787,81 +859,89 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0011")
def test_0012_tcp_deny(self):
- """ deny TCPv4/v6
- """
+ """deny TCPv4/v6"""
self.logger.info("ACLP_TEST_START_0012")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
# permit ip any any in the end
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- self.PORTS_ALL, 0))
- rules.append(self.create_rule(self.IPV6, self.PERMIT,
- self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "deny ip4/ip6 tcp")
# Traffic should not pass
- self.run_verify_negat_test(self.IP, self.IPRANDOM,
- self.proto[self.IP][self.TCP])
+ self.run_verify_negat_test(
+ self.IP, self.IPRANDOM, self.proto[self.IP][self.TCP]
+ )
self.logger.info("ACLP_TEST_FINISH_0012")
def test_0013_udp_deny(self):
- """ deny UDPv4/v6
- """
+ """deny UDPv4/v6"""
self.logger.info("ACLP_TEST_START_0013")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE,
- self.proto[self.IP][self.UDP]))
- rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.UDP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.UDP]
+ )
+ )
# permit ip any any in the end
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- self.PORTS_ALL, 0))
- rules.append(self.create_rule(self.IPV6, self.PERMIT,
- self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "deny ip4/ip6 udp")
# Traffic should not pass
- self.run_verify_negat_test(self.IP, self.IPRANDOM,
- self.proto[self.IP][self.UDP])
+ self.run_verify_negat_test(
+ self.IP, self.IPRANDOM, self.proto[self.IP][self.UDP]
+ )
self.logger.info("ACLP_TEST_FINISH_0013")
def test_0014_acl_dump(self):
- """ verify add/dump acls
- """
+ """verify add/dump acls"""
self.logger.info("ACLP_TEST_START_0014")
- r = [[self.IPV4, self.PERMIT, 1234, self.proto[self.IP][self.TCP]],
- [self.IPV4, self.PERMIT, 2345, self.proto[self.IP][self.UDP]],
- [self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.TCP]],
- [self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.UDP]],
- [self.IPV4, self.PERMIT, 5, self.proto[self.ICMP][self.ICMPv4]],
- [self.IPV6, self.PERMIT, 4321, self.proto[self.IP][self.TCP]],
- [self.IPV6, self.PERMIT, 5432, self.proto[self.IP][self.UDP]],
- [self.IPV6, self.PERMIT, 0, self.proto[self.IP][self.TCP]],
- [self.IPV6, self.PERMIT, 0, self.proto[self.IP][self.UDP]],
- [self.IPV6, self.PERMIT, 6, self.proto[self.ICMP][self.ICMPv6]],
- [self.IPV4, self.DENY, self.PORTS_ALL, 0],
- [self.IPV4, self.DENY, 1234, self.proto[self.IP][self.TCP]],
- [self.IPV4, self.DENY, 2345, self.proto[self.IP][self.UDP]],
- [self.IPV4, self.DENY, 5, self.proto[self.ICMP][self.ICMPv4]],
- [self.IPV6, self.DENY, 4321, self.proto[self.IP][self.TCP]],
- [self.IPV6, self.DENY, 5432, self.proto[self.IP][self.UDP]],
- [self.IPV6, self.DENY, 6, self.proto[self.ICMP][self.ICMPv6]],
- [self.IPV6, self.DENY, self.PORTS_ALL, 0]
- ]
+ r = [
+ [self.IPV4, self.PERMIT, 1234, self.proto[self.IP][self.TCP]],
+ [self.IPV4, self.PERMIT, 2345, self.proto[self.IP][self.UDP]],
+ [self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.TCP]],
+ [self.IPV4, self.PERMIT, 0, self.proto[self.IP][self.UDP]],
+ [self.IPV4, self.PERMIT, 5, self.proto[self.ICMP][self.ICMPv4]],
+ [self.IPV6, self.PERMIT, 4321, self.proto[self.IP][self.TCP]],
+ [self.IPV6, self.PERMIT, 5432, self.proto[self.IP][self.UDP]],
+ [self.IPV6, self.PERMIT, 0, self.proto[self.IP][self.TCP]],
+ [self.IPV6, self.PERMIT, 0, self.proto[self.IP][self.UDP]],
+ [self.IPV6, self.PERMIT, 6, self.proto[self.ICMP][self.ICMPv6]],
+ [self.IPV4, self.DENY, self.PORTS_ALL, 0],
+ [self.IPV4, self.DENY, 1234, self.proto[self.IP][self.TCP]],
+ [self.IPV4, self.DENY, 2345, self.proto[self.IP][self.UDP]],
+ [self.IPV4, self.DENY, 5, self.proto[self.ICMP][self.ICMPv4]],
+ [self.IPV6, self.DENY, 4321, self.proto[self.IP][self.TCP]],
+ [self.IPV6, self.DENY, 5432, self.proto[self.IP][self.UDP]],
+ [self.IPV6, self.DENY, 6, self.proto[self.ICMP][self.ICMPv6]],
+ [self.IPV6, self.DENY, self.PORTS_ALL, 0],
+ ]
# Add and verify new ACLs
rules = []
@@ -886,37 +966,47 @@ class TestACLplugin(VppTestCase):
self.assertEqual(dr.srcport_or_icmptype_last, 65535)
else:
if dr.proto == self.proto[self.IP][self.TCP]:
- self.assertGreater(dr.srcport_or_icmptype_first,
- self.tcp_sport_from-1)
- self.assertLess(dr.srcport_or_icmptype_first,
- self.tcp_sport_to+1)
- self.assertGreater(dr.dstport_or_icmpcode_last,
- self.tcp_dport_from-1)
- self.assertLess(dr.dstport_or_icmpcode_last,
- self.tcp_dport_to+1)
+ self.assertGreater(
+ dr.srcport_or_icmptype_first, self.tcp_sport_from - 1
+ )
+ self.assertLess(
+ dr.srcport_or_icmptype_first, self.tcp_sport_to + 1
+ )
+ self.assertGreater(
+ dr.dstport_or_icmpcode_last, self.tcp_dport_from - 1
+ )
+ self.assertLess(
+ dr.dstport_or_icmpcode_last, self.tcp_dport_to + 1
+ )
elif dr.proto == self.proto[self.IP][self.UDP]:
- self.assertGreater(dr.srcport_or_icmptype_first,
- self.udp_sport_from-1)
- self.assertLess(dr.srcport_or_icmptype_first,
- self.udp_sport_to+1)
- self.assertGreater(dr.dstport_or_icmpcode_last,
- self.udp_dport_from-1)
- self.assertLess(dr.dstport_or_icmpcode_last,
- self.udp_dport_to+1)
+ self.assertGreater(
+ dr.srcport_or_icmptype_first, self.udp_sport_from - 1
+ )
+ self.assertLess(
+ dr.srcport_or_icmptype_first, self.udp_sport_to + 1
+ )
+ self.assertGreater(
+ dr.dstport_or_icmpcode_last, self.udp_dport_from - 1
+ )
+ self.assertLess(
+ dr.dstport_or_icmpcode_last, self.udp_dport_to + 1
+ )
i += 1
self.logger.info("ACLP_TEST_FINISH_0014")
def test_0015_tcp_permit_port_v4(self):
- """ permit single TCPv4
- """
+ """permit single TCPv4"""
self.logger.info("ACLP_TEST_START_0015")
port = random.randint(16384, 65535)
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.PERMIT, port,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.PERMIT, port, self.proto[self.IP][self.TCP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
@@ -924,21 +1014,22 @@ class TestACLplugin(VppTestCase):
self.apply_rules(rules, "permit ip4 tcp %d" % port)
# Traffic should still pass
- self.run_verify_test(self.IP, self.IPV4,
- self.proto[self.IP][self.TCP], port)
+ self.run_verify_test(self.IP, self.IPV4, self.proto[self.IP][self.TCP], port)
self.logger.info("ACLP_TEST_FINISH_0015")
def test_0016_udp_permit_port_v4(self):
- """ permit single UDPv4
- """
+ """permit single UDPv4"""
self.logger.info("ACLP_TEST_START_0016")
port = random.randint(16384, 65535)
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.PERMIT, port,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.PERMIT, port, self.proto[self.IP][self.UDP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
@@ -946,21 +1037,22 @@ class TestACLplugin(VppTestCase):
self.apply_rules(rules, "permit ip4 tcp %d" % port)
# Traffic should still pass
- self.run_verify_test(self.IP, self.IPV4,
- self.proto[self.IP][self.UDP], port)
+ self.run_verify_test(self.IP, self.IPV4, self.proto[self.IP][self.UDP], port)
self.logger.info("ACLP_TEST_FINISH_0016")
def test_0017_tcp_permit_port_v6(self):
- """ permit single TCPv6
- """
+ """permit single TCPv6"""
self.logger.info("ACLP_TEST_START_0017")
port = random.randint(16384, 65535)
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV6, self.PERMIT, port,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.PERMIT, port, self.proto[self.IP][self.TCP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0))
@@ -968,90 +1060,89 @@ class TestACLplugin(VppTestCase):
self.apply_rules(rules, "permit ip4 tcp %d" % port)
# Traffic should still pass
- self.run_verify_test(self.IP, self.IPV6,
- self.proto[self.IP][self.TCP], port)
+ self.run_verify_test(self.IP, self.IPV6, self.proto[self.IP][self.TCP], port)
self.logger.info("ACLP_TEST_FINISH_0017")
def test_0018_udp_permit_port_v6(self):
- """ permit single UDPv6
- """
+ """permit single UDPv6"""
self.logger.info("ACLP_TEST_START_0018")
port = random.randint(16384, 65535)
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV6, self.PERMIT, port,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.PERMIT, port, self.proto[self.IP][self.UDP]
+ )
+ )
# deny ip any any in the end
- rules.append(self.create_rule(self.IPV6, self.DENY,
- self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "permit ip4 tcp %d" % port)
# Traffic should still pass
- self.run_verify_test(self.IP, self.IPV6,
- self.proto[self.IP][self.UDP], port)
+ self.run_verify_test(self.IP, self.IPV6, self.proto[self.IP][self.UDP], port)
self.logger.info("ACLP_TEST_FINISH_0018")
def test_0019_udp_deny_port(self):
- """ deny single TCPv4/v6
- """
+ """deny single TCPv4/v6"""
self.logger.info("ACLP_TEST_START_0019")
port = random.randint(16384, 65535)
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, port,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV6, self.DENY, port,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(self.IPV4, self.DENY, port, self.proto[self.IP][self.TCP])
+ )
+ rules.append(
+ self.create_rule(self.IPV6, self.DENY, port, self.proto[self.IP][self.TCP])
+ )
# Permit ip any any in the end
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- self.PORTS_ALL, 0))
- rules.append(self.create_rule(self.IPV6, self.PERMIT,
- self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "deny ip4/ip6 udp %d" % port)
# Traffic should not pass
- self.run_verify_negat_test(self.IP, self.IPRANDOM,
- self.proto[self.IP][self.TCP], port)
+ self.run_verify_negat_test(
+ self.IP, self.IPRANDOM, self.proto[self.IP][self.TCP], port
+ )
self.logger.info("ACLP_TEST_FINISH_0019")
def test_0020_udp_deny_port(self):
- """ deny single UDPv4/v6
- """
+ """deny single UDPv4/v6"""
self.logger.info("ACLP_TEST_START_0020")
port = random.randint(16384, 65535)
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, port,
- self.proto[self.IP][self.UDP]))
- rules.append(self.create_rule(self.IPV6, self.DENY, port,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(self.IPV4, self.DENY, port, self.proto[self.IP][self.UDP])
+ )
+ rules.append(
+ self.create_rule(self.IPV6, self.DENY, port, self.proto[self.IP][self.UDP])
+ )
# Permit ip any any in the end
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- self.PORTS_ALL, 0))
- rules.append(self.create_rule(self.IPV6, self.PERMIT,
- self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "deny ip4/ip6 udp %d" % port)
# Traffic should not pass
- self.run_verify_negat_test(self.IP, self.IPRANDOM,
- self.proto[self.IP][self.UDP], port)
+ self.run_verify_negat_test(
+ self.IP, self.IPRANDOM, self.proto[self.IP][self.UDP], port
+ )
self.logger.info("ACLP_TEST_FINISH_0020")
def test_0021_udp_deny_port_verify_fragment_deny(self):
- """ deny single UDPv4/v6, permit ip any, verify non-initial fragment
+ """deny single UDPv4/v6, permit ip any, verify non-initial fragment
blocked
"""
self.logger.info("ACLP_TEST_START_0021")
@@ -1059,37 +1150,40 @@ class TestACLplugin(VppTestCase):
port = random.randint(16384, 65535)
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, port,
- self.proto[self.IP][self.UDP]))
- rules.append(self.create_rule(self.IPV6, self.DENY, port,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(self.IPV4, self.DENY, port, self.proto[self.IP][self.UDP])
+ )
+ rules.append(
+ self.create_rule(self.IPV6, self.DENY, port, self.proto[self.IP][self.UDP])
+ )
# deny ip any any in the end
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- self.PORTS_ALL, 0))
- rules.append(self.create_rule(self.IPV6, self.PERMIT,
- self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "deny ip4/ip6 udp %d" % port)
# Traffic should not pass
- self.run_verify_negat_test(self.IP, self.IPRANDOM,
- self.proto[self.IP][self.UDP], port, True)
+ self.run_verify_negat_test(
+ self.IP, self.IPRANDOM, self.proto[self.IP][self.UDP], port, True
+ )
self.logger.info("ACLP_TEST_FINISH_0021")
def test_0022_zero_length_udp_ipv4(self):
- """ VPP-687 zero length udp ipv4 packet"""
+ """VPP-687 zero length udp ipv4 packet"""
self.logger.info("ACLP_TEST_START_0022")
port = random.randint(16384, 65535)
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.PERMIT, port,
- self.proto[self.IP][self.UDP]))
- # deny ip any any in the end
rules.append(
- self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
+ self.create_rule(
+ self.IPV4, self.PERMIT, port, self.proto[self.IP][self.UDP]
+ )
+ )
+ # deny ip any any in the end
+ rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "permit empty udp ip4 %d" % port)
@@ -1097,10 +1191,16 @@ class TestACLplugin(VppTestCase):
# Traffic should still pass
# Create incoming packet streams for packet-generator interfaces
pkts_cnt = 0
- pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes,
- self.IP, self.IPV4,
- self.proto[self.IP][self.UDP], port,
- False, False)
+ pkts = self.create_stream(
+ self.pg0,
+ self.pg_if_packet_sizes,
+ self.IP,
+ self.IPV4,
+ self.proto[self.IP][self.UDP],
+ port,
+ False,
+ False,
+ )
if len(pkts) > 0:
self.pg0.add_stream(pkts)
pkts_cnt += len(pkts)
@@ -1114,14 +1214,17 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0022")
def test_0023_zero_length_udp_ipv6(self):
- """ VPP-687 zero length udp ipv6 packet"""
+ """VPP-687 zero length udp ipv6 packet"""
self.logger.info("ACLP_TEST_START_0023")
port = random.randint(16384, 65535)
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV6, self.PERMIT, port,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.PERMIT, port, self.proto[self.IP][self.UDP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0))
@@ -1131,10 +1234,16 @@ class TestACLplugin(VppTestCase):
# Traffic should still pass
# Create incoming packet streams for packet-generator interfaces
pkts_cnt = 0
- pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes,
- self.IP, self.IPV6,
- self.proto[self.IP][self.UDP], port,
- False, False)
+ pkts = self.create_stream(
+ self.pg0,
+ self.pg_if_packet_sizes,
+ self.IP,
+ self.IPV6,
+ self.proto[self.IP][self.UDP],
+ port,
+ False,
+ False,
+ )
if len(pkts) > 0:
self.pg0.add_stream(pkts)
pkts_cnt += len(pkts)
@@ -1149,16 +1258,21 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0023")
def test_0108_tcp_permit_v4(self):
- """ permit TCPv4 + non-match range
- """
+ """permit TCPv4 + non-match range"""
self.logger.info("ACLP_TEST_START_0108")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
@@ -1171,16 +1285,21 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0108")
def test_0109_tcp_permit_v6(self):
- """ permit TCPv6 + non-match range
- """
+ """permit TCPv6 + non-match range"""
self.logger.info("ACLP_TEST_START_0109")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE_2,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0))
@@ -1193,16 +1312,21 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0109")
def test_0110_udp_permit_v4(self):
- """ permit UDPv4 + non-match range
- """
+ """permit UDPv4 + non-match range"""
self.logger.info("ACLP_TEST_START_0110")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2,
- self.proto[self.IP][self.UDP]))
- rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.UDP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.UDP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
@@ -1215,16 +1339,21 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0110")
def test_0111_udp_permit_v6(self):
- """ permit UDPv6 + non-match range
- """
+ """permit UDPv6 + non-match range"""
self.logger.info("ACLP_TEST_START_0111")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE_2,
- self.proto[self.IP][self.UDP]))
- rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.UDP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.UDP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_ALL, 0))
@@ -1237,80 +1366,113 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0111")
def test_0112_tcp_deny(self):
- """ deny TCPv4/v6 + non-match range
- """
+ """deny TCPv4/v6 + non-match range"""
self.logger.info("ACLP_TEST_START_0112")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- self.PORTS_RANGE_2,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV6, self.PERMIT,
- self.PORTS_RANGE_2,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4,
+ self.PERMIT,
+ self.PORTS_RANGE_2,
+ self.proto[self.IP][self.TCP],
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV6,
+ self.PERMIT,
+ self.PORTS_RANGE_2,
+ self.proto[self.IP][self.TCP],
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
# permit ip any any in the end
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- self.PORTS_ALL, 0))
- rules.append(self.create_rule(self.IPV6, self.PERMIT,
- self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "deny ip4/ip6 tcp")
# Traffic should not pass
- self.run_verify_negat_test(self.IP, self.IPRANDOM,
- self.proto[self.IP][self.TCP])
+ self.run_verify_negat_test(
+ self.IP, self.IPRANDOM, self.proto[self.IP][self.TCP]
+ )
self.logger.info("ACLP_TEST_FINISH_0112")
def test_0113_udp_deny(self):
- """ deny UDPv4/v6 + non-match range
- """
+ """deny UDPv4/v6 + non-match range"""
self.logger.info("ACLP_TEST_START_0113")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- self.PORTS_RANGE_2,
- self.proto[self.IP][self.UDP]))
- rules.append(self.create_rule(self.IPV6, self.PERMIT,
- self.PORTS_RANGE_2,
- self.proto[self.IP][self.UDP]))
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE,
- self.proto[self.IP][self.UDP]))
- rules.append(self.create_rule(self.IPV6, self.DENY, self.PORTS_RANGE,
- self.proto[self.IP][self.UDP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4,
+ self.PERMIT,
+ self.PORTS_RANGE_2,
+ self.proto[self.IP][self.UDP],
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV6,
+ self.PERMIT,
+ self.PORTS_RANGE_2,
+ self.proto[self.IP][self.UDP],
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.UDP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV6, self.DENY, self.PORTS_RANGE, self.proto[self.IP][self.UDP]
+ )
+ )
# permit ip any any in the end
- rules.append(self.create_rule(self.IPV4, self.PERMIT,
- self.PORTS_ALL, 0))
- rules.append(self.create_rule(self.IPV6, self.PERMIT,
- self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_ALL, 0))
+ rules.append(self.create_rule(self.IPV6, self.PERMIT, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "deny ip4/ip6 udp")
# Traffic should not pass
- self.run_verify_negat_test(self.IP, self.IPRANDOM,
- self.proto[self.IP][self.UDP])
+ self.run_verify_negat_test(
+ self.IP, self.IPRANDOM, self.proto[self.IP][self.UDP]
+ )
self.logger.info("ACLP_TEST_FINISH_0113")
def test_0300_tcp_permit_v4_etype_aaaa(self):
- """ permit TCPv4, send 0xAAAA etype
- """
+ """permit TCPv4, send 0xAAAA etype"""
self.logger.info("ACLP_TEST_START_0300")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
@@ -1318,33 +1480,39 @@ class TestACLplugin(VppTestCase):
self.apply_rules(rules, "permit ipv4 tcp")
# Traffic should still pass also for an odd ethertype
- self.run_verify_test(self.IP, self.IPV4, self.proto[self.IP][self.TCP],
- 0, False, True, 0xaaaa)
+ self.run_verify_test(
+ self.IP, self.IPV4, self.proto[self.IP][self.TCP], 0, False, True, 0xAAAA
+ )
self.logger.info("ACLP_TEST_FINISH_0300")
def test_0305_tcp_permit_v4_etype_blacklist_aaaa(self):
- """ permit TCPv4, whitelist 0x0BBB ethertype, send 0xAAAA-blocked
- """
+ """permit TCPv4, whitelist 0x0BBB ethertype, send 0xAAAA-blocked"""
self.logger.info("ACLP_TEST_START_0305")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "permit ipv4 tcp")
# whitelist the 0xbbbb etype - so the 0xaaaa should be blocked
- self.etype_whitelist([0xbbb], 1)
+ self.etype_whitelist([0xBBB], 1)
# The oddball ethertype should be blocked
- self.run_verify_negat_test(self.IP, self.IPV4,
- self.proto[self.IP][self.TCP],
- 0, False, 0xaaaa)
+ self.run_verify_negat_test(
+ self.IP, self.IPV4, self.proto[self.IP][self.TCP], 0, False, 0xAAAA
+ )
# remove the whitelist
self.etype_whitelist([], 0, add=False)
@@ -1352,27 +1520,33 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0305")
def test_0306_tcp_permit_v4_etype_blacklist_aaaa(self):
- """ permit TCPv4, whitelist 0x0BBB ethertype, send 0x0BBB - pass
- """
+ """permit TCPv4, whitelist 0x0BBB ethertype, send 0x0BBB - pass"""
self.logger.info("ACLP_TEST_START_0306")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
# Apply rules
self.apply_rules(rules, "permit ipv4 tcp")
# whitelist the 0xbbbb etype - so the 0xaaaa should be blocked
- self.etype_whitelist([0xbbb], 1)
+ self.etype_whitelist([0xBBB], 1)
# The whitelisted traffic, should pass
- self.run_verify_test(self.IP, self.IPV4, self.proto[self.IP][self.TCP],
- 0, False, True, 0x0bbb)
+ self.run_verify_test(
+ self.IP, self.IPV4, self.proto[self.IP][self.TCP], 0, False, True, 0x0BBB
+ )
# remove the whitelist, the previously blocked 0xAAAA should pass now
self.etype_whitelist([], 0, add=False)
@@ -1380,16 +1554,21 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0306")
def test_0307_tcp_permit_v4_etype_blacklist_aaaa(self):
- """ permit TCPv4, whitelist 0x0BBB, remove, send 0xAAAA - pass
- """
+ """permit TCPv4, whitelist 0x0BBB, remove, send 0xAAAA - pass"""
self.logger.info("ACLP_TEST_START_0307")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
@@ -1397,27 +1576,33 @@ class TestACLplugin(VppTestCase):
self.apply_rules(rules, "permit ipv4 tcp")
# whitelist the 0xbbbb etype - so the 0xaaaa should be blocked
- self.etype_whitelist([0xbbb], 1)
+ self.etype_whitelist([0xBBB], 1)
# remove the whitelist, the previously blocked 0xAAAA should pass now
self.etype_whitelist([], 0, add=False)
# The whitelisted traffic, should pass
- self.run_verify_test(self.IP, self.IPV4, self.proto[self.IP][self.TCP],
- 0, False, True, 0xaaaa)
+ self.run_verify_test(
+ self.IP, self.IPV4, self.proto[self.IP][self.TCP], 0, False, True, 0xAAAA
+ )
self.logger.info("ACLP_TEST_FINISH_0306")
def test_0315_del_intf(self):
- """ apply an acl and delete the interface
- """
+ """apply an acl and delete the interface"""
self.logger.info("ACLP_TEST_START_0315")
# Add an ACL
rules = []
- rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_RANGE_2,
- self.proto[self.IP][self.TCP]))
- rules.append(self.create_rule(self.IPV4, self.PERMIT, self.PORTS_RANGE,
- self.proto[self.IP][self.TCP]))
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.DENY, self.PORTS_RANGE_2, self.proto[self.IP][self.TCP]
+ )
+ )
+ rules.append(
+ self.create_rule(
+ self.IPV4, self.PERMIT, self.PORTS_RANGE, self.proto[self.IP][self.TCP]
+ )
+ )
# deny ip any any in the end
rules.append(self.create_rule(self.IPV4, self.DENY, self.PORTS_ALL, 0))
@@ -1434,5 +1619,5 @@ class TestACLplugin(VppTestCase):
self.logger.info("ACLP_TEST_FINISH_0315")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_acl_plugin_conns.py b/test/test_acl_plugin_conns.py
index cbf0ab37cf8..1b41698d6c0 100644
--- a/test/test_acl_plugin_conns.py
+++ b/test/test_acl_plugin_conns.py
@@ -39,14 +39,16 @@ def to_acl_rule(self, is_permit, wildcard_sport=False):
rule_l4_sport_first = rule_l4_sport
rule_l4_sport_last = rule_l4_sport
- new_rule = AclRule(is_permit=is_permit, proto=rule_l4_proto,
- src_prefix=ip_network(
- (p[rule_l3_layer].src, rule_prefix_len)),
- dst_prefix=ip_network(
- (p[rule_l3_layer].dst, rule_prefix_len)),
- sport_from=rule_l4_sport_first,
- sport_to=rule_l4_sport_last,
- dport_from=rule_l4_dport, dport_to=rule_l4_dport)
+ new_rule = AclRule(
+ is_permit=is_permit,
+ proto=rule_l4_proto,
+ src_prefix=ip_network((p[rule_l3_layer].src, rule_prefix_len)),
+ dst_prefix=ip_network((p[rule_l3_layer].dst, rule_prefix_len)),
+ sport_from=rule_l4_sport_first,
+ sport_to=rule_l4_sport_last,
+ dport_from=rule_l4_dport,
+ dport_to=rule_l4_dport,
+ )
return new_rule
@@ -54,7 +56,7 @@ def to_acl_rule(self, is_permit, wildcard_sport=False):
Packet.to_acl_rule = to_acl_rule
-class IterateWithSleep():
+class IterateWithSleep:
def __init__(self, testcase, n_iters, description, sleep_sec):
self.curr = 0
self.testcase = testcase
@@ -87,21 +89,27 @@ class Conn(L4_Conn):
deny_acl.add_vpp_config()
if reflect_side == acl_side:
- acl_if0 = VppAclInterface(self.testcase,
- self.ifs[acl_side].sw_if_index,
- [reflect_acl, deny_acl], n_input=1)
- acl_if1 = VppAclInterface(self.testcase,
- self.ifs[1-acl_side].sw_if_index, [],
- n_input=0)
+ acl_if0 = VppAclInterface(
+ self.testcase,
+ self.ifs[acl_side].sw_if_index,
+ [reflect_acl, deny_acl],
+ n_input=1,
+ )
+ acl_if1 = VppAclInterface(
+ self.testcase, self.ifs[1 - acl_side].sw_if_index, [], n_input=0
+ )
acl_if0.add_vpp_config()
acl_if1.add_vpp_config()
else:
- acl_if0 = VppAclInterface(self.testcase,
- self.ifs[acl_side].sw_if_index,
- [deny_acl, reflect_acl], n_input=1)
- acl_if1 = VppAclInterface(self.testcase,
- self.ifs[1-acl_side].sw_if_index, [],
- n_input=0)
+ acl_if0 = VppAclInterface(
+ self.testcase,
+ self.ifs[acl_side].sw_if_index,
+ [deny_acl, reflect_acl],
+ n_input=1,
+ )
+ acl_if1 = VppAclInterface(
+ self.testcase, self.ifs[1 - acl_side].sw_if_index, [], n_input=0
+ )
acl_if0.add_vpp_config()
acl_if1.add_vpp_config()
@@ -109,19 +117,22 @@ class Conn(L4_Conn):
any_addr = ["0.0.0.0", "::"]
rule_family = self.address_family
is_ip6 = 1 if rule_family == AF_INET6 else 0
- new_rule = AclRule(is_permit=is_permit, proto=0,
- src_prefix=ip_network(
- (any_addr[is_ip6], 0)),
- dst_prefix=ip_network(
- (any_addr[is_ip6], 0)),
- sport_from=0, sport_to=65535, dport_from=0,
- dport_to=65535)
+ new_rule = AclRule(
+ is_permit=is_permit,
+ proto=0,
+ src_prefix=ip_network((any_addr[is_ip6], 0)),
+ dst_prefix=ip_network((any_addr[is_ip6], 0)),
+ sport_from=0,
+ sport_to=65535,
+ dport_from=0,
+ dport_to=65535,
+ )
return new_rule
@unittest.skipUnless(config.extended, "part of extended tests")
class ACLPluginConnTestCase(VppTestCase):
- """ ACL plugin connection-oriented extended testcases """
+ """ACL plugin connection-oriented extended testcases"""
@classmethod
def setUpClass(cls):
@@ -142,8 +153,7 @@ class ACLPluginConnTestCase(VppTestCase):
super(ACLPluginConnTestCase, cls).tearDownClass()
def tearDown(self):
- """Run standard test teardown and log various show commands
- """
+ """Run standard test teardown and log various show commands"""
super(ACLPluginConnTestCase, self).tearDown()
def show_commands_at_teardown(self):
@@ -156,7 +166,7 @@ class ACLPluginConnTestCase(VppTestCase):
self.logger.info(self.vapi.cli("show event-logger all"))
def run_basic_conn_test(self, af, acl_side):
- """ Basic conn timeout test """
+ """Basic conn timeout test"""
conn1 = Conn(self, self.pg0, self.pg1, af, UDP, 42001, 4242)
conn1.apply_acls(0, acl_side)
conn1.send_through(0)
@@ -178,8 +188,8 @@ class ACLPluginConnTestCase(VppTestCase):
self.assert_equal(p2, None, "packet on long-idle conn")
def run_active_conn_test(self, af, acl_side):
- """ Idle connection behind active connection test """
- base = 10000 + 1000*acl_side
+ """Idle connection behind active connection test"""
+ base = 10000 + 1000 * acl_side
conn1 = Conn(self, self.pg0, self.pg1, af, UDP, base + 1, 2323)
conn2 = Conn(self, self.pg0, self.pg1, af, UDP, base + 2, 2323)
conn3 = Conn(self, self.pg0, self.pg1, af, UDP, base + 3, 2323)
@@ -206,7 +216,7 @@ class ACLPluginConnTestCase(VppTestCase):
self.assert_equal(p2, None, "packet on long-idle conn")
def run_clear_conn_test(self, af, acl_side):
- """ Clear the connections via CLI """
+ """Clear the connections via CLI"""
conn1 = Conn(self, self.pg0, self.pg1, af, UDP, 42001, 4242)
conn1.apply_acls(0, acl_side)
conn1.send_through(0)
@@ -229,9 +239,9 @@ class ACLPluginConnTestCase(VppTestCase):
def run_tcp_transient_setup_conn_test(self, af, acl_side):
conn1 = Conn(self, self.pg0, self.pg1, af, TCP, 53001, 5151)
conn1.apply_acls(0, acl_side)
- conn1.send_through(0, 'S')
+ conn1.send_through(0, "S")
# the return packets should pass
- conn1.send_through(1, 'SA')
+ conn1.send_through(1, "SA")
# allow the conn to time out
for i in IterateWithSleep(self, 30, "Wait for timeout", 0.1):
pass
@@ -247,17 +257,17 @@ class ACLPluginConnTestCase(VppTestCase):
def run_tcp_established_conn_test(self, af, acl_side):
conn1 = Conn(self, self.pg0, self.pg1, af, TCP, 53002, 5052)
conn1.apply_acls(0, acl_side)
- conn1.send_through(0, 'S')
+ conn1.send_through(0, "S")
# the return packets should pass
- conn1.send_through(1, 'SA')
+ conn1.send_through(1, "SA")
# complete the threeway handshake
# (NB: sequence numbers not tracked, so not set!)
- conn1.send_through(0, 'A')
+ conn1.send_through(0, "A")
# allow the conn to time out if it's in embryonic timer
for i in IterateWithSleep(self, 30, "Wait for transient timeout", 0.1):
pass
# Try to send the packet from the "forbidden" side - it must pass
- conn1.send_through(1, 'A')
+ conn1.send_through(1, "A")
# ensure conn times out for real
for i in IterateWithSleep(self, 130, "Wait for timeout", 0.1):
pass
@@ -272,19 +282,19 @@ class ACLPluginConnTestCase(VppTestCase):
def run_tcp_transient_teardown_conn_test(self, af, acl_side):
conn1 = Conn(self, self.pg0, self.pg1, af, TCP, 53002, 5052)
conn1.apply_acls(0, acl_side)
- conn1.send_through(0, 'S')
+ conn1.send_through(0, "S")
# the return packets should pass
- conn1.send_through(1, 'SA')
+ conn1.send_through(1, "SA")
# complete the threeway handshake
# (NB: sequence numbers not tracked, so not set!)
- conn1.send_through(0, 'A')
+ conn1.send_through(0, "A")
# allow the conn to time out if it's in embryonic timer
for i in IterateWithSleep(self, 30, "Wait for transient timeout", 0.1):
pass
# Try to send the packet from the "forbidden" side - it must pass
- conn1.send_through(1, 'A')
+ conn1.send_through(1, "A")
# Send the FIN to bounce the session out of established
- conn1.send_through(1, 'FA')
+ conn1.send_through(1, "FA")
# If conn landed on transient timer it will time out here
for i in IterateWithSleep(self, 30, "Wait for transient timeout", 0.1):
pass
@@ -298,59 +308,59 @@ class ACLPluginConnTestCase(VppTestCase):
self.assert_equal(p2, None, "packet on supposedly deleted conn")
def test_0000_conn_prepare_test(self):
- """ Prepare the settings """
+ """Prepare the settings"""
self.vapi.ppcli("set acl-plugin session timeout udp idle 1")
def test_0001_basic_conn_test(self):
- """ IPv4: Basic conn timeout test reflect on ingress """
+ """IPv4: Basic conn timeout test reflect on ingress"""
self.run_basic_conn_test(AF_INET, 0)
def test_0002_basic_conn_test(self):
- """ IPv4: Basic conn timeout test reflect on egress """
+ """IPv4: Basic conn timeout test reflect on egress"""
self.run_basic_conn_test(AF_INET, 1)
def test_0005_clear_conn_test(self):
- """ IPv4: reflect egress, clear conn """
+ """IPv4: reflect egress, clear conn"""
self.run_clear_conn_test(AF_INET, 1)
def test_0006_clear_conn_test(self):
- """ IPv4: reflect ingress, clear conn """
+ """IPv4: reflect ingress, clear conn"""
self.run_clear_conn_test(AF_INET, 0)
def test_0011_active_conn_test(self):
- """ IPv4: Idle conn behind active conn, reflect on ingress """
+ """IPv4: Idle conn behind active conn, reflect on ingress"""
self.run_active_conn_test(AF_INET, 0)
def test_0012_active_conn_test(self):
- """ IPv4: Idle conn behind active conn, reflect on egress """
+ """IPv4: Idle conn behind active conn, reflect on egress"""
self.run_active_conn_test(AF_INET, 1)
def test_1001_basic_conn_test(self):
- """ IPv6: Basic conn timeout test reflect on ingress """
+ """IPv6: Basic conn timeout test reflect on ingress"""
self.run_basic_conn_test(AF_INET6, 0)
def test_1002_basic_conn_test(self):
- """ IPv6: Basic conn timeout test reflect on egress """
+ """IPv6: Basic conn timeout test reflect on egress"""
self.run_basic_conn_test(AF_INET6, 1)
def test_1005_clear_conn_test(self):
- """ IPv6: reflect egress, clear conn """
+ """IPv6: reflect egress, clear conn"""
self.run_clear_conn_test(AF_INET6, 1)
def test_1006_clear_conn_test(self):
- """ IPv6: reflect ingress, clear conn """
+ """IPv6: reflect ingress, clear conn"""
self.run_clear_conn_test(AF_INET6, 0)
def test_1011_active_conn_test(self):
- """ IPv6: Idle conn behind active conn, reflect on ingress """
+ """IPv6: Idle conn behind active conn, reflect on ingress"""
self.run_active_conn_test(AF_INET6, 0)
def test_1012_active_conn_test(self):
- """ IPv6: Idle conn behind active conn, reflect on egress """
+ """IPv6: Idle conn behind active conn, reflect on egress"""
self.run_active_conn_test(AF_INET6, 1)
def test_2000_prepare_for_tcp_test(self):
- """ Prepare for TCP session tests """
+ """Prepare for TCP session tests"""
# ensure the session hangs on if it gets treated as UDP
self.vapi.ppcli("set acl-plugin session timeout udp idle 200")
# let the TCP connection time out at 5 seconds
@@ -358,49 +368,49 @@ class ACLPluginConnTestCase(VppTestCase):
self.vapi.ppcli("set acl-plugin session timeout tcp transient 1")
def test_2001_tcp_transient_conn_test(self):
- """ IPv4: transient TCP session (incomplete 3WHS), ref. on ingress """
+ """IPv4: transient TCP session (incomplete 3WHS), ref. on ingress"""
self.run_tcp_transient_setup_conn_test(AF_INET, 0)
def test_2002_tcp_transient_conn_test(self):
- """ IPv4: transient TCP session (incomplete 3WHS), ref. on egress """
+ """IPv4: transient TCP session (incomplete 3WHS), ref. on egress"""
self.run_tcp_transient_setup_conn_test(AF_INET, 1)
def test_2003_tcp_transient_conn_test(self):
- """ IPv4: established TCP session (complete 3WHS), ref. on ingress """
+ """IPv4: established TCP session (complete 3WHS), ref. on ingress"""
self.run_tcp_established_conn_test(AF_INET, 0)
def test_2004_tcp_transient_conn_test(self):
- """ IPv4: established TCP session (complete 3WHS), ref. on egress """
+ """IPv4: established TCP session (complete 3WHS), ref. on egress"""
self.run_tcp_established_conn_test(AF_INET, 1)
def test_2005_tcp_transient_teardown_conn_test(self):
- """ IPv4: transient TCP session (3WHS,ACK,FINACK), ref. on ingress """
+ """IPv4: transient TCP session (3WHS,ACK,FINACK), ref. on ingress"""
self.run_tcp_transient_teardown_conn_test(AF_INET, 0)
def test_2006_tcp_transient_teardown_conn_test(self):
- """ IPv4: transient TCP session (3WHS,ACK,FINACK), ref. on egress """
+ """IPv4: transient TCP session (3WHS,ACK,FINACK), ref. on egress"""
self.run_tcp_transient_teardown_conn_test(AF_INET, 1)
def test_3001_tcp_transient_conn_test(self):
- """ IPv6: transient TCP session (incomplete 3WHS), ref. on ingress """
+ """IPv6: transient TCP session (incomplete 3WHS), ref. on ingress"""
self.run_tcp_transient_setup_conn_test(AF_INET6, 0)
def test_3002_tcp_transient_conn_test(self):
- """ IPv6: transient TCP session (incomplete 3WHS), ref. on egress """
+ """IPv6: transient TCP session (incomplete 3WHS), ref. on egress"""
self.run_tcp_transient_setup_conn_test(AF_INET6, 1)
def test_3003_tcp_transient_conn_test(self):
- """ IPv6: established TCP session (complete 3WHS), ref. on ingress """
+ """IPv6: established TCP session (complete 3WHS), ref. on ingress"""
self.run_tcp_established_conn_test(AF_INET6, 0)
def test_3004_tcp_transient_conn_test(self):
- """ IPv6: established TCP session (complete 3WHS), ref. on egress """
+ """IPv6: established TCP session (complete 3WHS), ref. on egress"""
self.run_tcp_established_conn_test(AF_INET6, 1)
def test_3005_tcp_transient_teardown_conn_test(self):
- """ IPv6: transient TCP session (3WHS,ACK,FINACK), ref. on ingress """
+ """IPv6: transient TCP session (3WHS,ACK,FINACK), ref. on ingress"""
self.run_tcp_transient_teardown_conn_test(AF_INET6, 0)
def test_3006_tcp_transient_teardown_conn_test(self):
- """ IPv6: transient TCP session (3WHS,ACK,FINACK), ref. on egress """
+ """IPv6: transient TCP session (3WHS,ACK,FINACK), ref. on egress"""
self.run_tcp_transient_teardown_conn_test(AF_INET6, 1)
diff --git a/test/test_acl_plugin_l2l3.py b/test/test_acl_plugin_l2l3.py
index 48faafb7398..343e611751b 100644
--- a/test/test_acl_plugin_l2l3.py
+++ b/test/test_acl_plugin_l2l3.py
@@ -76,12 +76,16 @@ class TestACLpluginL2L3(VppTestCase):
# Create BD with MAC learning enabled and put interfaces to this BD
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.loop0.sw_if_index, bd_id=cls.bd_id,
- port_type=L2_PORT_TYPE.BVI)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=cls.pg0.sw_if_index,
- bd_id=cls.bd_id)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=cls.pg1.sw_if_index,
- bd_id=cls.bd_id)
+ rx_sw_if_index=cls.loop0.sw_if_index,
+ bd_id=cls.bd_id,
+ port_type=L2_PORT_TYPE.BVI,
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=cls.pg0.sw_if_index, bd_id=cls.bd_id
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.bd_id
+ )
# Configure IPv4 addresses on loopback interface and routed interface
cls.loop0.config_ip4()
@@ -125,8 +129,7 @@ class TestACLpluginL2L3(VppTestCase):
self.logger.info(self.vapi.cli("show l2patch"))
self.logger.info(self.vapi.cli("show classify tables"))
self.logger.info(self.vapi.cli("show l2fib verbose"))
- self.logger.info(self.vapi.cli("show bridge-domain %s detail" %
- self.bd_id))
+ self.logger.info(self.vapi.cli("show bridge-domain %s detail" % self.bd_id))
self.logger.info(self.vapi.cli("show ip neighbors"))
cmd = "show acl-plugin sessions verbose 1"
self.logger.info(self.vapi.cli(cmd))
@@ -134,23 +137,33 @@ class TestACLpluginL2L3(VppTestCase):
self.logger.info(self.vapi.cli("show acl-plugin interface"))
self.logger.info(self.vapi.cli("show acl-plugin tables"))
- def create_stream(self, src_ip_if, dst_ip_if, reverse, packet_sizes,
- is_ip6, expect_blocked, expect_established,
- add_extension_header, icmp_stateful=False):
+ def create_stream(
+ self,
+ src_ip_if,
+ dst_ip_if,
+ reverse,
+ packet_sizes,
+ is_ip6,
+ expect_blocked,
+ expect_established,
+ add_extension_header,
+ icmp_stateful=False,
+ ):
pkts = []
rules = []
permit_rules = []
permit_and_reflect_rules = []
total_packet_count = 8
for i in range(0, total_packet_count):
- modulo = (i//2) % 2
+ modulo = (i // 2) % 2
icmp_type_delta = i % 2
icmp_code = i
- is_udp_packet = (modulo == 0)
+ is_udp_packet = modulo == 0
if is_udp_packet and icmp_stateful:
continue
- is_reflectable_icmp = (icmp_stateful and icmp_type_delta == 0 and
- not is_udp_packet)
+ is_reflectable_icmp = (
+ icmp_stateful and icmp_type_delta == 0 and not is_udp_packet
+ )
is_reflected_icmp = is_reflectable_icmp and expect_established
can_reflect_this_packet = is_udp_packet or is_reflectable_icmp
is_permit = i % 2
@@ -161,9 +174,9 @@ class TestACLpluginL2L3(VppTestCase):
payload = self.info_to_payload(info)
else:
to_be_blocked = False
- if (expect_blocked and not expect_established):
+ if expect_blocked and not expect_established:
to_be_blocked = True
- if (not can_reflect_this_packet):
+ if not can_reflect_this_packet:
to_be_blocked = True
if to_be_blocked:
payload = "to be blocked"
@@ -171,7 +184,7 @@ class TestACLpluginL2L3(VppTestCase):
info = self.create_packet_info(src_ip_if, dst_ip_if)
payload = self.info_to_payload(info)
if reverse:
- dst_mac = 'de:ad:00:00:00:00'
+ dst_mac = "de:ad:00:00:00:00"
src_mac = remote_dst_host._mac
dst_ip6 = src_ip_if.remote_ip6
src_ip6 = remote_dst_host.ip6
@@ -201,42 +214,53 @@ class TestACLpluginL2L3(VppTestCase):
ulp_l4 = UDP(sport=src_l4, dport=dst_l4)
if add_extension_header:
# prepend some extension headers
- ulp = (IPv6ExtHdrRouting() / IPv6ExtHdrRouting() /
- IPv6ExtHdrFragment(offset=0, m=1) / ulp_l4)
+ ulp = (
+ IPv6ExtHdrRouting()
+ / IPv6ExtHdrRouting()
+ / IPv6ExtHdrFragment(offset=0, m=1)
+ / ulp_l4
+ )
# uncomment below to test invalid ones
# ulp = IPv6ExtHdrRouting(len = 200) / ulp_l4
else:
ulp = ulp_l4
- p = (Ether(dst=dst_mac, src=src_mac) /
- IPv6(src=src_ip6, dst=dst_ip6) /
- ulp /
- Raw(payload))
+ p = (
+ Ether(dst=dst_mac, src=src_mac)
+ / IPv6(src=src_ip6, dst=dst_ip6)
+ / ulp
+ / Raw(payload)
+ )
else:
ulp_l4 = UDP(sport=src_l4, dport=dst_l4)
# IPv4 does not allow extension headers,
# but we rather make it a first fragment
flags = 1 if add_extension_header else 0
ulp = ulp_l4
- p = (Ether(dst=dst_mac, src=src_mac) /
- IP(src=src_ip4, dst=dst_ip4, frag=0, flags=flags) /
- ulp /
- Raw(payload))
+ p = (
+ Ether(dst=dst_mac, src=src_mac)
+ / IP(src=src_ip4, dst=dst_ip4, frag=0, flags=flags)
+ / ulp
+ / Raw(payload)
+ )
elif modulo == 1:
if is_ip6:
- ulp_l4 = ICMPv6Unknown(type=128 + icmp_type_delta,
- code=icmp_code)
+ ulp_l4 = ICMPv6Unknown(type=128 + icmp_type_delta, code=icmp_code)
ulp = ulp_l4
- p = (Ether(dst=dst_mac, src=src_mac) /
- IPv6(src=src_ip6, dst=dst_ip6) /
- ulp /
- Raw(payload))
+ p = (
+ Ether(dst=dst_mac, src=src_mac)
+ / IPv6(src=src_ip6, dst=dst_ip6)
+ / ulp
+ / Raw(payload)
+ )
else:
- ulp_l4 = ICMP(type=8 - 8*icmp_type_delta, code=icmp_code)
+ ulp_l4 = ICMP(type=8 - 8 * icmp_type_delta, code=icmp_code)
ulp = ulp_l4
- p = (Ether(dst=dst_mac, src=src_mac) /
- IP(src=src_ip4, dst=dst_ip4) /
- ulp /
- Raw(payload))
+ p = (
+ Ether(dst=dst_mac, src=src_mac)
+ / IP(src=src_ip4, dst=dst_ip4)
+ / ulp
+ / Raw(payload)
+ )
if i % 2 == 1:
info.data = p.copy()
@@ -259,19 +283,20 @@ class TestACLpluginL2L3(VppTestCase):
rule_l4_sport = p[ICMPv6Unknown].type
rule_l4_dport = p[ICMPv6Unknown].code
if p.haslayer(IPv6):
- rule_l4_proto = ulp_l4.overload_fields[IPv6]['nh']
+ rule_l4_proto = ulp_l4.overload_fields[IPv6]["nh"]
else:
rule_l4_proto = p[IP].proto
- new_rule = AclRule(is_permit=is_permit, proto=rule_l4_proto,
- src_prefix=ip_network(
- (p[rule_l3_layer].src, rule_prefix_len)),
- dst_prefix=ip_network(
- (p[rule_l3_layer].dst, rule_prefix_len)),
- sport_from=rule_l4_sport,
- sport_to=rule_l4_sport,
- dport_from=rule_l4_dport,
- dport_to=rule_l4_dport)
+ new_rule = AclRule(
+ is_permit=is_permit,
+ proto=rule_l4_proto,
+ src_prefix=ip_network((p[rule_l3_layer].src, rule_prefix_len)),
+ dst_prefix=ip_network((p[rule_l3_layer].dst, rule_prefix_len)),
+ sport_from=rule_l4_sport,
+ sport_to=rule_l4_sport,
+ dport_from=rule_l4_dport,
+ dport_to=rule_l4_dport,
+ )
rules.append(new_rule)
new_rule_permit = copy.copy(new_rule)
@@ -287,10 +312,12 @@ class TestACLpluginL2L3(VppTestCase):
permit_and_reflect_rules.append(new_rule_permit_and_reflect)
self.logger.info("create_stream pkt#%d: %s" % (i, payload))
- return {'stream': pkts,
- 'rules': rules,
- 'permit_rules': permit_rules,
- 'permit_and_reflect_rules': permit_and_reflect_rules}
+ return {
+ "stream": pkts,
+ "rules": rules,
+ "permit_rules": permit_rules,
+ "permit_and_reflect_rules": permit_and_reflect_rules,
+ }
def verify_capture(self, dst_ip_if, src_ip_if, capture, reverse):
last_info = dict()
@@ -316,11 +343,13 @@ class TestACLpluginL2L3(VppTestCase):
data = scapy.compat.raw(packet[UDP][Raw])
else:
if l3 == IP:
- data = scapy.compat.raw(ICMP(
- scapy.compat.raw(packet[l3].payload))[Raw])
+ data = scapy.compat.raw(
+ ICMP(scapy.compat.raw(packet[l3].payload))[Raw]
+ )
else:
- data = scapy.compat.raw(ICMPv6Unknown(
- scapy.compat.raw(packet[l3].payload)).msgbody)
+ data = scapy.compat.raw(
+ ICMPv6Unknown(scapy.compat.raw(packet[l3].payload)).msgbody
+ )
udp_or_icmp = packet[l3].payload
data_obj = Raw(data)
# FIXME: make framework believe we are on object
@@ -330,8 +359,8 @@ class TestACLpluginL2L3(VppTestCase):
self.assertEqual(payload_info.dst, dst_ip_sw_if_index)
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_ip_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_ip_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
self.assertEqual(packet_index, next_info.index)
@@ -400,13 +429,13 @@ class TestACLpluginL2L3(VppTestCase):
# change the ACLs a few times
for i in range(1, 10):
shuffle(all_rules)
- acl1.modify_vpp_config(all_rules[::1+(i % 2)])
+ acl1.modify_vpp_config(all_rules[:: 1 + (i % 2)])
shuffle(all_rules)
- acl2.modify_vpp_config(all_rules[::1+(i % 3)])
+ acl2.modify_vpp_config(all_rules[:: 1 + (i % 3)])
shuffle(all_rules)
- acl3.modify_vpp_config(all_rules[::1+(i % 5)])
+ acl3.modify_vpp_config(all_rules[:: 1 + (i % 5)])
# restore to how it was before and clean up
acl_if.n_input = saved_n_input
@@ -417,143 +446,200 @@ class TestACLpluginL2L3(VppTestCase):
acl2.remove_vpp_config()
acl3.remove_vpp_config()
- def create_acls_for_a_stream(self, stream_dict,
- test_l2_action, is_reflect):
- r = stream_dict['rules']
- r_permit = stream_dict['permit_rules']
- r_permit_reflect = stream_dict['permit_and_reflect_rules']
+ def create_acls_for_a_stream(self, stream_dict, test_l2_action, is_reflect):
+ r = stream_dict["rules"]
+ r_permit = stream_dict["permit_rules"]
+ r_permit_reflect = stream_dict["permit_and_reflect_rules"]
r_action = r_permit_reflect if is_reflect else r
action_acl = VppAcl(self, rules=r_action, tag="act. acl")
action_acl.add_vpp_config()
permit_acl = VppAcl(self, rules=r_permit, tag="perm. acl")
permit_acl.add_vpp_config()
- return {'L2': action_acl if test_l2_action else permit_acl,
- 'L3': permit_acl if test_l2_action else action_acl,
- 'permit': permit_acl, 'action': action_acl}
-
- def apply_acl_ip46_x_to_y(self, bridged_to_routed, test_l2_deny,
- is_ip6, is_reflect, add_eh):
- """ Apply the ACLs
- """
+ return {
+ "L2": action_acl if test_l2_action else permit_acl,
+ "L3": permit_acl if test_l2_action else action_acl,
+ "permit": permit_acl,
+ "action": action_acl,
+ }
+
+ def apply_acl_ip46_x_to_y(
+ self, bridged_to_routed, test_l2_deny, is_ip6, is_reflect, add_eh
+ ):
+ """Apply the ACLs"""
self.reset_packet_infos()
stream_dict = self.create_stream(
- self.pg2, self.loop0,
+ self.pg2,
+ self.loop0,
bridged_to_routed,
- self.pg_if_packet_sizes, is_ip6,
- not is_reflect, False, add_eh)
- stream = stream_dict['stream']
- acl_idx = self.create_acls_for_a_stream(stream_dict, test_l2_deny,
- is_reflect)
+ self.pg_if_packet_sizes,
+ is_ip6,
+ not is_reflect,
+ False,
+ add_eh,
+ )
+ stream = stream_dict["stream"]
+ acl_idx = self.create_acls_for_a_stream(stream_dict, test_l2_deny, is_reflect)
n_input_l3 = 0 if bridged_to_routed else 1
n_input_l2 = 1 if bridged_to_routed else 0
- acl_if_pg2 = VppAclInterface(self, sw_if_index=self.pg2.sw_if_index,
- n_input=n_input_l3, acls=[acl_idx['L3']])
+ acl_if_pg2 = VppAclInterface(
+ self,
+ sw_if_index=self.pg2.sw_if_index,
+ n_input=n_input_l3,
+ acls=[acl_idx["L3"]],
+ )
acl_if_pg2.add_vpp_config()
- acl_if_pg0 = VppAclInterface(self, sw_if_index=self.pg0.sw_if_index,
- n_input=n_input_l2, acls=[acl_idx['L2']])
+ acl_if_pg0 = VppAclInterface(
+ self,
+ sw_if_index=self.pg0.sw_if_index,
+ n_input=n_input_l2,
+ acls=[acl_idx["L2"]],
+ )
acl_if_pg0.add_vpp_config()
- acl_if_pg1 = VppAclInterface(self, sw_if_index=self.pg1.sw_if_index,
- n_input=n_input_l2, acls=[acl_idx['L2']])
+ acl_if_pg1 = VppAclInterface(
+ self,
+ sw_if_index=self.pg1.sw_if_index,
+ n_input=n_input_l2,
+ acls=[acl_idx["L2"]],
+ )
acl_if_pg1.add_vpp_config()
self.applied_acl_shuffle(acl_if_pg0)
self.applied_acl_shuffle(acl_if_pg1)
- return {'L2': acl_idx['L2'], 'L3': acl_idx['L3']}
+ return {"L2": acl_idx["L2"], "L3": acl_idx["L3"]}
- def apply_acl_ip46_both_directions_reflect(self,
- primary_is_bridged_to_routed,
- reflect_on_l2, is_ip6, add_eh,
- stateful_icmp):
+ def apply_acl_ip46_both_directions_reflect(
+ self, primary_is_bridged_to_routed, reflect_on_l2, is_ip6, add_eh, stateful_icmp
+ ):
primary_is_routed_to_bridged = not primary_is_bridged_to_routed
self.reset_packet_infos()
- stream_dict_fwd = self.create_stream(self.pg2, self.loop0,
- primary_is_bridged_to_routed,
- self.pg_if_packet_sizes, is_ip6,
- False, False, add_eh,
- stateful_icmp)
- acl_idx_fwd = self.create_acls_for_a_stream(stream_dict_fwd,
- reflect_on_l2, True)
-
- stream_dict_rev = self.create_stream(self.pg2, self.loop0,
- not primary_is_bridged_to_routed,
- self.pg_if_packet_sizes, is_ip6,
- True, True, add_eh, stateful_icmp)
+ stream_dict_fwd = self.create_stream(
+ self.pg2,
+ self.loop0,
+ primary_is_bridged_to_routed,
+ self.pg_if_packet_sizes,
+ is_ip6,
+ False,
+ False,
+ add_eh,
+ stateful_icmp,
+ )
+ acl_idx_fwd = self.create_acls_for_a_stream(
+ stream_dict_fwd, reflect_on_l2, True
+ )
+
+ stream_dict_rev = self.create_stream(
+ self.pg2,
+ self.loop0,
+ not primary_is_bridged_to_routed,
+ self.pg_if_packet_sizes,
+ is_ip6,
+ True,
+ True,
+ add_eh,
+ stateful_icmp,
+ )
# We want the primary action to be "deny" rather than reflect
- acl_idx_rev = self.create_acls_for_a_stream(stream_dict_rev,
- reflect_on_l2, False)
+ acl_idx_rev = self.create_acls_for_a_stream(
+ stream_dict_rev, reflect_on_l2, False
+ )
if primary_is_bridged_to_routed:
- inbound_l2_acl = acl_idx_fwd['L2']
+ inbound_l2_acl = acl_idx_fwd["L2"]
else:
- inbound_l2_acl = acl_idx_rev['L2']
+ inbound_l2_acl = acl_idx_rev["L2"]
if primary_is_routed_to_bridged:
- outbound_l2_acl = acl_idx_fwd['L2']
+ outbound_l2_acl = acl_idx_fwd["L2"]
else:
- outbound_l2_acl = acl_idx_rev['L2']
+ outbound_l2_acl = acl_idx_rev["L2"]
if primary_is_routed_to_bridged:
- inbound_l3_acl = acl_idx_fwd['L3']
+ inbound_l3_acl = acl_idx_fwd["L3"]
else:
- inbound_l3_acl = acl_idx_rev['L3']
+ inbound_l3_acl = acl_idx_rev["L3"]
if primary_is_bridged_to_routed:
- outbound_l3_acl = acl_idx_fwd['L3']
+ outbound_l3_acl = acl_idx_fwd["L3"]
else:
- outbound_l3_acl = acl_idx_rev['L3']
-
- acl_if_pg2 = VppAclInterface(self, sw_if_index=self.pg2.sw_if_index,
- n_input=1,
- acls=[inbound_l3_acl, outbound_l3_acl])
+ outbound_l3_acl = acl_idx_rev["L3"]
+
+ acl_if_pg2 = VppAclInterface(
+ self,
+ sw_if_index=self.pg2.sw_if_index,
+ n_input=1,
+ acls=[inbound_l3_acl, outbound_l3_acl],
+ )
acl_if_pg2.add_vpp_config()
- acl_if_pg0 = VppAclInterface(self, sw_if_index=self.pg0.sw_if_index,
- n_input=1,
- acls=[inbound_l2_acl, outbound_l2_acl])
+ acl_if_pg0 = VppAclInterface(
+ self,
+ sw_if_index=self.pg0.sw_if_index,
+ n_input=1,
+ acls=[inbound_l2_acl, outbound_l2_acl],
+ )
acl_if_pg0.add_vpp_config()
- acl_if_pg1 = VppAclInterface(self, sw_if_index=self.pg1.sw_if_index,
- n_input=1,
- acls=[inbound_l2_acl, outbound_l2_acl])
+ acl_if_pg1 = VppAclInterface(
+ self,
+ sw_if_index=self.pg1.sw_if_index,
+ n_input=1,
+ acls=[inbound_l2_acl, outbound_l2_acl],
+ )
acl_if_pg1.add_vpp_config()
self.applied_acl_shuffle(acl_if_pg0)
self.applied_acl_shuffle(acl_if_pg2)
- def apply_acl_ip46_routed_to_bridged(self, test_l2_deny, is_ip6,
- is_reflect, add_eh):
- return self.apply_acl_ip46_x_to_y(False, test_l2_deny, is_ip6,
- is_reflect, add_eh)
+ def apply_acl_ip46_routed_to_bridged(
+ self, test_l2_deny, is_ip6, is_reflect, add_eh
+ ):
+ return self.apply_acl_ip46_x_to_y(
+ False, test_l2_deny, is_ip6, is_reflect, add_eh
+ )
- def apply_acl_ip46_bridged_to_routed(self, test_l2_deny, is_ip6,
- is_reflect, add_eh):
- return self.apply_acl_ip46_x_to_y(True, test_l2_deny, is_ip6,
- is_reflect, add_eh)
+ def apply_acl_ip46_bridged_to_routed(
+ self, test_l2_deny, is_ip6, is_reflect, add_eh
+ ):
+ return self.apply_acl_ip46_x_to_y(
+ True, test_l2_deny, is_ip6, is_reflect, add_eh
+ )
def verify_acl_packet_count(self, acl_idx, packet_count):
- matches = self.statistics.get_counter('/acl/%d/matches' % acl_idx)
+ matches = self.statistics.get_counter("/acl/%d/matches" % acl_idx)
self.logger.info("stat seg for ACL %d: %s" % (acl_idx, repr(matches)))
total_count = 0
for m in matches:
for p in m:
- total_count = total_count + p['packets']
+ total_count = total_count + p["packets"]
self.assertEqual(total_count, packet_count)
- def run_traffic_ip46_x_to_y(self, bridged_to_routed,
- test_l2_deny, is_ip6,
- is_reflect, is_established, add_eh,
- stateful_icmp=False):
+ def run_traffic_ip46_x_to_y(
+ self,
+ bridged_to_routed,
+ test_l2_deny,
+ is_ip6,
+ is_reflect,
+ is_established,
+ add_eh,
+ stateful_icmp=False,
+ ):
self.reset_packet_infos()
- stream_dict = self.create_stream(self.pg2, self.loop0,
- bridged_to_routed,
- self.pg_if_packet_sizes, is_ip6,
- not is_reflect, is_established,
- add_eh, stateful_icmp)
- stream = stream_dict['stream']
+ stream_dict = self.create_stream(
+ self.pg2,
+ self.loop0,
+ bridged_to_routed,
+ self.pg_if_packet_sizes,
+ is_ip6,
+ not is_reflect,
+ is_established,
+ add_eh,
+ stateful_icmp,
+ )
+ stream = stream_dict["stream"]
tx_if = self.pg0 if bridged_to_routed else self.pg2
rx_if = self.pg2 if bridged_to_routed else self.pg0
@@ -566,68 +652,90 @@ class TestACLpluginL2L3(VppTestCase):
self.verify_capture(self.loop0, self.pg2, rcvd1, bridged_to_routed)
return len(stream)
- def run_traffic_ip46_routed_to_bridged(self, test_l2_deny, is_ip6,
- is_reflect, is_established, add_eh,
- stateful_icmp=False):
- return self.run_traffic_ip46_x_to_y(False, test_l2_deny, is_ip6,
- is_reflect, is_established, add_eh,
- stateful_icmp)
-
- def run_traffic_ip46_bridged_to_routed(self, test_l2_deny, is_ip6,
- is_reflect, is_established, add_eh,
- stateful_icmp=False):
- return self.run_traffic_ip46_x_to_y(True, test_l2_deny, is_ip6,
- is_reflect, is_established, add_eh,
- stateful_icmp)
-
- def run_test_ip46_routed_to_bridged(self, test_l2_deny,
- is_ip6, is_reflect, add_eh):
- acls = self.apply_acl_ip46_routed_to_bridged(test_l2_deny,
- is_ip6, is_reflect,
- add_eh)
- pkts = self.run_traffic_ip46_routed_to_bridged(test_l2_deny, is_ip6,
- is_reflect, False,
- add_eh)
- self.verify_acl_packet_count(acls['L3'].acl_index, pkts)
-
- def run_test_ip46_bridged_to_routed(self, test_l2_deny,
- is_ip6, is_reflect, add_eh):
- acls = self.apply_acl_ip46_bridged_to_routed(test_l2_deny,
- is_ip6, is_reflect,
- add_eh)
- pkts = self.run_traffic_ip46_bridged_to_routed(test_l2_deny, is_ip6,
- is_reflect, False,
- add_eh)
- self.verify_acl_packet_count(acls['L2'].acl_index, pkts)
-
- def run_test_ip46_routed_to_bridged_and_back(self, test_l2_action,
- is_ip6, add_eh,
- stateful_icmp=False):
- self.apply_acl_ip46_both_directions_reflect(False, test_l2_action,
- is_ip6, add_eh,
- stateful_icmp)
- self.run_traffic_ip46_routed_to_bridged(test_l2_action, is_ip6,
- True, False, add_eh,
- stateful_icmp)
- self.run_traffic_ip46_bridged_to_routed(test_l2_action, is_ip6,
- False, True, add_eh,
- stateful_icmp)
-
- def run_test_ip46_bridged_to_routed_and_back(self, test_l2_action,
- is_ip6, add_eh,
- stateful_icmp=False):
- self.apply_acl_ip46_both_directions_reflect(True, test_l2_action,
- is_ip6, add_eh,
- stateful_icmp)
- self.run_traffic_ip46_bridged_to_routed(test_l2_action, is_ip6,
- True, False, add_eh,
- stateful_icmp)
- self.run_traffic_ip46_routed_to_bridged(test_l2_action, is_ip6,
- False, True, add_eh,
- stateful_icmp)
+ def run_traffic_ip46_routed_to_bridged(
+ self,
+ test_l2_deny,
+ is_ip6,
+ is_reflect,
+ is_established,
+ add_eh,
+ stateful_icmp=False,
+ ):
+ return self.run_traffic_ip46_x_to_y(
+ False,
+ test_l2_deny,
+ is_ip6,
+ is_reflect,
+ is_established,
+ add_eh,
+ stateful_icmp,
+ )
+
+ def run_traffic_ip46_bridged_to_routed(
+ self,
+ test_l2_deny,
+ is_ip6,
+ is_reflect,
+ is_established,
+ add_eh,
+ stateful_icmp=False,
+ ):
+ return self.run_traffic_ip46_x_to_y(
+ True,
+ test_l2_deny,
+ is_ip6,
+ is_reflect,
+ is_established,
+ add_eh,
+ stateful_icmp,
+ )
+
+ def run_test_ip46_routed_to_bridged(self, test_l2_deny, is_ip6, is_reflect, add_eh):
+ acls = self.apply_acl_ip46_routed_to_bridged(
+ test_l2_deny, is_ip6, is_reflect, add_eh
+ )
+ pkts = self.run_traffic_ip46_routed_to_bridged(
+ test_l2_deny, is_ip6, is_reflect, False, add_eh
+ )
+ self.verify_acl_packet_count(acls["L3"].acl_index, pkts)
+
+ def run_test_ip46_bridged_to_routed(self, test_l2_deny, is_ip6, is_reflect, add_eh):
+ acls = self.apply_acl_ip46_bridged_to_routed(
+ test_l2_deny, is_ip6, is_reflect, add_eh
+ )
+ pkts = self.run_traffic_ip46_bridged_to_routed(
+ test_l2_deny, is_ip6, is_reflect, False, add_eh
+ )
+ self.verify_acl_packet_count(acls["L2"].acl_index, pkts)
+
+ def run_test_ip46_routed_to_bridged_and_back(
+ self, test_l2_action, is_ip6, add_eh, stateful_icmp=False
+ ):
+ self.apply_acl_ip46_both_directions_reflect(
+ False, test_l2_action, is_ip6, add_eh, stateful_icmp
+ )
+ self.run_traffic_ip46_routed_to_bridged(
+ test_l2_action, is_ip6, True, False, add_eh, stateful_icmp
+ )
+ self.run_traffic_ip46_bridged_to_routed(
+ test_l2_action, is_ip6, False, True, add_eh, stateful_icmp
+ )
+
+ def run_test_ip46_bridged_to_routed_and_back(
+ self, test_l2_action, is_ip6, add_eh, stateful_icmp=False
+ ):
+ self.apply_acl_ip46_both_directions_reflect(
+ True, test_l2_action, is_ip6, add_eh, stateful_icmp
+ )
+ self.run_traffic_ip46_bridged_to_routed(
+ test_l2_action, is_ip6, True, False, add_eh, stateful_icmp
+ )
+ self.run_traffic_ip46_routed_to_bridged(
+ test_l2_action, is_ip6, False, True, add_eh, stateful_icmp
+ )
def test_0000_ip6_irb_1(self):
- """ ACL plugin prepare"""
+ """ACL plugin prepare"""
if not self.vpp_dead:
cmd = "set acl-plugin session timeout udp idle 2000"
self.logger.info(self.vapi.ppcli(cmd))
@@ -646,219 +754,188 @@ class TestACLpluginL2L3(VppTestCase):
# "set acl-plugin l2-datapath old"))
def test_0001_ip6_irb_1(self):
- """ ACL IPv6 routed -> bridged, L2 ACL deny"""
- self.run_test_ip46_routed_to_bridged(True, True, False,
- self.WITHOUT_EH)
+ """ACL IPv6 routed -> bridged, L2 ACL deny"""
+ self.run_test_ip46_routed_to_bridged(True, True, False, self.WITHOUT_EH)
def test_0002_ip6_irb_1(self):
- """ ACL IPv6 routed -> bridged, L3 ACL deny"""
- self.run_test_ip46_routed_to_bridged(False, True, False,
- self.WITHOUT_EH)
+ """ACL IPv6 routed -> bridged, L3 ACL deny"""
+ self.run_test_ip46_routed_to_bridged(False, True, False, self.WITHOUT_EH)
def test_0003_ip4_irb_1(self):
- """ ACL IPv4 routed -> bridged, L2 ACL deny"""
- self.run_test_ip46_routed_to_bridged(True, False, False,
- self.WITHOUT_EH)
+ """ACL IPv4 routed -> bridged, L2 ACL deny"""
+ self.run_test_ip46_routed_to_bridged(True, False, False, self.WITHOUT_EH)
def test_0004_ip4_irb_1(self):
- """ ACL IPv4 routed -> bridged, L3 ACL deny"""
- self.run_test_ip46_routed_to_bridged(False, False, False,
- self.WITHOUT_EH)
+ """ACL IPv4 routed -> bridged, L3 ACL deny"""
+ self.run_test_ip46_routed_to_bridged(False, False, False, self.WITHOUT_EH)
def test_0005_ip6_irb_1(self):
- """ ACL IPv6 bridged -> routed, L2 ACL deny """
- self.run_test_ip46_bridged_to_routed(True, True, False,
- self.WITHOUT_EH)
+ """ACL IPv6 bridged -> routed, L2 ACL deny"""
+ self.run_test_ip46_bridged_to_routed(True, True, False, self.WITHOUT_EH)
def test_0006_ip6_irb_1(self):
- """ ACL IPv6 bridged -> routed, L3 ACL deny """
- self.run_test_ip46_bridged_to_routed(False, True, False,
- self.WITHOUT_EH)
+ """ACL IPv6 bridged -> routed, L3 ACL deny"""
+ self.run_test_ip46_bridged_to_routed(False, True, False, self.WITHOUT_EH)
def test_0007_ip6_irb_1(self):
- """ ACL IPv4 bridged -> routed, L2 ACL deny """
- self.run_test_ip46_bridged_to_routed(True, False, False,
- self.WITHOUT_EH)
+ """ACL IPv4 bridged -> routed, L2 ACL deny"""
+ self.run_test_ip46_bridged_to_routed(True, False, False, self.WITHOUT_EH)
def test_0008_ip6_irb_1(self):
- """ ACL IPv4 bridged -> routed, L3 ACL deny """
- self.run_test_ip46_bridged_to_routed(False, False, False,
- self.WITHOUT_EH)
+ """ACL IPv4 bridged -> routed, L3 ACL deny"""
+ self.run_test_ip46_bridged_to_routed(False, False, False, self.WITHOUT_EH)
# Stateful ACL tests
def test_0101_ip6_irb_1(self):
- """ ACL IPv6 routed -> bridged, L2 ACL permit+reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(True, True,
- self.WITHOUT_EH)
+ """ACL IPv6 routed -> bridged, L2 ACL permit+reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(True, True, self.WITHOUT_EH)
def test_0102_ip6_irb_1(self):
- """ ACL IPv6 bridged -> routed, L2 ACL permit+reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(True, True,
- self.WITHOUT_EH)
+ """ACL IPv6 bridged -> routed, L2 ACL permit+reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(True, True, self.WITHOUT_EH)
def test_0103_ip6_irb_1(self):
- """ ACL IPv4 routed -> bridged, L2 ACL permit+reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(True, False,
- self.WITHOUT_EH)
+ """ACL IPv4 routed -> bridged, L2 ACL permit+reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(True, False, self.WITHOUT_EH)
def test_0104_ip6_irb_1(self):
- """ ACL IPv4 bridged -> routed, L2 ACL permit+reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(True, False,
- self.WITHOUT_EH)
+ """ACL IPv4 bridged -> routed, L2 ACL permit+reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(True, False, self.WITHOUT_EH)
def test_0111_ip6_irb_1(self):
- """ ACL IPv6 routed -> bridged, L3 ACL permit+reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(False, True,
- self.WITHOUT_EH)
+ """ACL IPv6 routed -> bridged, L3 ACL permit+reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(False, True, self.WITHOUT_EH)
def test_0112_ip6_irb_1(self):
- """ ACL IPv6 bridged -> routed, L3 ACL permit+reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(False, True,
- self.WITHOUT_EH)
+ """ACL IPv6 bridged -> routed, L3 ACL permit+reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(False, True, self.WITHOUT_EH)
def test_0113_ip6_irb_1(self):
- """ ACL IPv4 routed -> bridged, L3 ACL permit+reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(False, False,
- self.WITHOUT_EH)
+ """ACL IPv4 routed -> bridged, L3 ACL permit+reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(False, False, self.WITHOUT_EH)
def test_0114_ip6_irb_1(self):
- """ ACL IPv4 bridged -> routed, L3 ACL permit+reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(False, False,
- self.WITHOUT_EH)
+ """ACL IPv4 bridged -> routed, L3 ACL permit+reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(False, False, self.WITHOUT_EH)
# A block of tests with extension headers
def test_1001_ip6_irb_1(self):
- """ ACL IPv6+EH routed -> bridged, L2 ACL deny"""
- self.run_test_ip46_routed_to_bridged(True, True, False,
- self.WITH_EH)
+ """ACL IPv6+EH routed -> bridged, L2 ACL deny"""
+ self.run_test_ip46_routed_to_bridged(True, True, False, self.WITH_EH)
def test_1002_ip6_irb_1(self):
- """ ACL IPv6+EH routed -> bridged, L3 ACL deny"""
- self.run_test_ip46_routed_to_bridged(False, True, False,
- self.WITH_EH)
+ """ACL IPv6+EH routed -> bridged, L3 ACL deny"""
+ self.run_test_ip46_routed_to_bridged(False, True, False, self.WITH_EH)
def test_1005_ip6_irb_1(self):
- """ ACL IPv6+EH bridged -> routed, L2 ACL deny """
- self.run_test_ip46_bridged_to_routed(True, True, False,
- self.WITH_EH)
+ """ACL IPv6+EH bridged -> routed, L2 ACL deny"""
+ self.run_test_ip46_bridged_to_routed(True, True, False, self.WITH_EH)
def test_1006_ip6_irb_1(self):
- """ ACL IPv6+EH bridged -> routed, L3 ACL deny """
- self.run_test_ip46_bridged_to_routed(False, True, False,
- self.WITH_EH)
+ """ACL IPv6+EH bridged -> routed, L3 ACL deny"""
+ self.run_test_ip46_bridged_to_routed(False, True, False, self.WITH_EH)
def test_1101_ip6_irb_1(self):
- """ ACL IPv6+EH routed -> bridged, L2 ACL permit+reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(True, True,
- self.WITH_EH)
+ """ACL IPv6+EH routed -> bridged, L2 ACL permit+reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(True, True, self.WITH_EH)
def test_1102_ip6_irb_1(self):
- """ ACL IPv6+EH bridged -> routed, L2 ACL permit+reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(True, True,
- self.WITH_EH)
+ """ACL IPv6+EH bridged -> routed, L2 ACL permit+reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(True, True, self.WITH_EH)
def test_1111_ip6_irb_1(self):
- """ ACL IPv6+EH routed -> bridged, L3 ACL permit+reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(False, True,
- self.WITH_EH)
+ """ACL IPv6+EH routed -> bridged, L3 ACL permit+reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(False, True, self.WITH_EH)
def test_1112_ip6_irb_1(self):
- """ ACL IPv6+EH bridged -> routed, L3 ACL permit+reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(False, True,
- self.WITH_EH)
+ """ACL IPv6+EH bridged -> routed, L3 ACL permit+reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(False, True, self.WITH_EH)
# IPv4 with "MF" bit set
def test_1201_ip6_irb_1(self):
- """ ACL IPv4+MF routed -> bridged, L2 ACL deny"""
- self.run_test_ip46_routed_to_bridged(True, False, False,
- self.WITH_EH)
+ """ACL IPv4+MF routed -> bridged, L2 ACL deny"""
+ self.run_test_ip46_routed_to_bridged(True, False, False, self.WITH_EH)
def test_1202_ip6_irb_1(self):
- """ ACL IPv4+MF routed -> bridged, L3 ACL deny"""
- self.run_test_ip46_routed_to_bridged(False, False, False,
- self.WITH_EH)
+ """ACL IPv4+MF routed -> bridged, L3 ACL deny"""
+ self.run_test_ip46_routed_to_bridged(False, False, False, self.WITH_EH)
def test_1205_ip6_irb_1(self):
- """ ACL IPv4+MF bridged -> routed, L2 ACL deny """
- self.run_test_ip46_bridged_to_routed(True, False, False,
- self.WITH_EH)
+ """ACL IPv4+MF bridged -> routed, L2 ACL deny"""
+ self.run_test_ip46_bridged_to_routed(True, False, False, self.WITH_EH)
def test_1206_ip6_irb_1(self):
- """ ACL IPv4+MF bridged -> routed, L3 ACL deny """
- self.run_test_ip46_bridged_to_routed(False, False, False,
- self.WITH_EH)
+ """ACL IPv4+MF bridged -> routed, L3 ACL deny"""
+ self.run_test_ip46_bridged_to_routed(False, False, False, self.WITH_EH)
def test_1301_ip6_irb_1(self):
- """ ACL IPv4+MF routed -> bridged, L2 ACL permit+reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(True, False,
- self.WITH_EH)
+ """ACL IPv4+MF routed -> bridged, L2 ACL permit+reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(True, False, self.WITH_EH)
def test_1302_ip6_irb_1(self):
- """ ACL IPv4+MF bridged -> routed, L2 ACL permit+reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(True, False,
- self.WITH_EH)
+ """ACL IPv4+MF bridged -> routed, L2 ACL permit+reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(True, False, self.WITH_EH)
def test_1311_ip6_irb_1(self):
- """ ACL IPv4+MF routed -> bridged, L3 ACL permit+reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(False, False,
- self.WITH_EH)
+ """ACL IPv4+MF routed -> bridged, L3 ACL permit+reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(False, False, self.WITH_EH)
def test_1312_ip6_irb_1(self):
- """ ACL IPv4+MF bridged -> routed, L3 ACL permit+reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(False, False,
- self.WITH_EH)
+ """ACL IPv4+MF bridged -> routed, L3 ACL permit+reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(False, False, self.WITH_EH)
+
# Stateful ACL tests with stateful ICMP
def test_1401_ip6_irb_1(self):
- """ IPv6 routed -> bridged, L2 ACL permit+reflect, ICMP reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(True, True,
- self.WITHOUT_EH,
- self.STATEFUL_ICMP)
+ """IPv6 routed -> bridged, L2 ACL permit+reflect, ICMP reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(
+ True, True, self.WITHOUT_EH, self.STATEFUL_ICMP
+ )
def test_1402_ip6_irb_1(self):
- """ IPv6 bridged -> routed, L2 ACL permit+reflect, ICMP reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(True, True,
- self.WITHOUT_EH,
- self.STATEFUL_ICMP)
+ """IPv6 bridged -> routed, L2 ACL permit+reflect, ICMP reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(
+ True, True, self.WITHOUT_EH, self.STATEFUL_ICMP
+ )
def test_1403_ip4_irb_1(self):
- """ IPv4 routed -> bridged, L2 ACL permit+reflect, ICMP reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(True, False,
- self.WITHOUT_EH,
- self.STATEFUL_ICMP)
+ """IPv4 routed -> bridged, L2 ACL permit+reflect, ICMP reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(
+ True, False, self.WITHOUT_EH, self.STATEFUL_ICMP
+ )
def test_1404_ip4_irb_1(self):
- """ IPv4 bridged -> routed, L2 ACL permit+reflect, ICMP reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(True, False,
- self.WITHOUT_EH,
- self.STATEFUL_ICMP)
+ """IPv4 bridged -> routed, L2 ACL permit+reflect, ICMP reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(
+ True, False, self.WITHOUT_EH, self.STATEFUL_ICMP
+ )
def test_1411_ip6_irb_1(self):
- """ IPv6 routed -> bridged, L3 ACL permit+reflect, ICMP reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(False, True,
- self.WITHOUT_EH,
- self.STATEFUL_ICMP)
+ """IPv6 routed -> bridged, L3 ACL permit+reflect, ICMP reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(
+ False, True, self.WITHOUT_EH, self.STATEFUL_ICMP
+ )
def test_1412_ip6_irb_1(self):
- """ IPv6 bridged -> routed, L3 ACL permit+reflect, ICMP reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(False, True,
- self.WITHOUT_EH,
- self.STATEFUL_ICMP)
+ """IPv6 bridged -> routed, L3 ACL permit+reflect, ICMP reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(
+ False, True, self.WITHOUT_EH, self.STATEFUL_ICMP
+ )
def test_1413_ip4_irb_1(self):
- """ IPv4 routed -> bridged, L3 ACL permit+reflect, ICMP reflect"""
- self.run_test_ip46_routed_to_bridged_and_back(False, False,
- self.WITHOUT_EH,
- self.STATEFUL_ICMP)
+ """IPv4 routed -> bridged, L3 ACL permit+reflect, ICMP reflect"""
+ self.run_test_ip46_routed_to_bridged_and_back(
+ False, False, self.WITHOUT_EH, self.STATEFUL_ICMP
+ )
def test_1414_ip4_irb_1(self):
- """ IPv4 bridged -> routed, L3 ACL permit+reflect, ICMP reflect"""
- self.run_test_ip46_bridged_to_routed_and_back(False, False,
- self.WITHOUT_EH,
- self.STATEFUL_ICMP)
+ """IPv4 bridged -> routed, L3 ACL permit+reflect, ICMP reflect"""
+ self.run_test_ip46_bridged_to_routed_and_back(
+ False, False, self.WITHOUT_EH, self.STATEFUL_ICMP
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_acl_plugin_macip.py b/test/test_acl_plugin_macip.py
index 5353c16d331..6a1ba589182 100644
--- a/test/test_acl_plugin_macip.py
+++ b/test/test_acl_plugin_macip.py
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
from __future__ import print_function
+
"""ACL plugin - MACIP tests
"""
import binascii
@@ -20,10 +21,21 @@ from scapy.layers.inet6 import IPv6
from framework import VppTestCase, VppTestRunner
from vpp_lo_interface import VppLoInterface
from vpp_l2 import L2_PORT_TYPE
-from vpp_sub_interface import L2_VTR_OP, VppSubInterface, VppDot1QSubint, \
- VppDot1ADSubint
-from vpp_acl import AclRule, VppAcl, VppAclInterface, VppEtypeWhitelist, \
- VppMacipAclInterface, VppMacipAcl, MacipRule
+from vpp_sub_interface import (
+ L2_VTR_OP,
+ VppSubInterface,
+ VppDot1QSubint,
+ VppDot1ADSubint,
+)
+from vpp_acl import (
+ AclRule,
+ VppAcl,
+ VppAclInterface,
+ VppEtypeWhitelist,
+ VppMacipAclInterface,
+ VppMacipAcl,
+ MacipRule,
+)
from vpp_papi import MACAddress
@@ -79,16 +91,13 @@ class MethodHolder(VppTestCase):
VppDot1QSubint(cls, cls.pg1, 10),
VppDot1ADSubint(cls, cls.pg2, 20, 300, 400),
VppDot1QSubint(cls, cls.pg3, 30),
- VppDot1ADSubint(cls, cls.pg3, 40, 600, 700)]
+ VppDot1ADSubint(cls, cls.pg3, 40, 600, 700),
+ ]
- cls.subifs[0].set_vtr(L2_VTR_OP.L2_POP_1,
- inner=10, push1q=1)
- cls.subifs[1].set_vtr(L2_VTR_OP.L2_POP_2,
- outer=300, inner=400, push1q=1)
- cls.subifs[2].set_vtr(L2_VTR_OP.L2_POP_1,
- inner=30, push1q=1)
- cls.subifs[3].set_vtr(L2_VTR_OP.L2_POP_2,
- outer=600, inner=700, push1q=1)
+ cls.subifs[0].set_vtr(L2_VTR_OP.L2_POP_1, inner=10, push1q=1)
+ cls.subifs[1].set_vtr(L2_VTR_OP.L2_POP_2, outer=300, inner=400, push1q=1)
+ cls.subifs[2].set_vtr(L2_VTR_OP.L2_POP_1, inner=30, push1q=1)
+ cls.subifs[3].set_vtr(L2_VTR_OP.L2_POP_2, outer=600, inner=700, push1q=1)
cls.interfaces = list(cls.pg_interfaces)
cls.interfaces.extend(cls.lo_interfaces)
@@ -99,16 +108,22 @@ class MethodHolder(VppTestCase):
# Create BD with MAC learning enabled and put interfaces to this BD
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.loop0.sw_if_index, bd_id=cls.bd_id,
- port_type=L2_PORT_TYPE.BVI)
+ rx_sw_if_index=cls.loop0.sw_if_index,
+ bd_id=cls.bd_id,
+ port_type=L2_PORT_TYPE.BVI,
+ )
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg0.sw_if_index, bd_id=cls.bd_id)
+ rx_sw_if_index=cls.pg0.sw_if_index, bd_id=cls.bd_id
+ )
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.bd_id)
+ rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.bd_id
+ )
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.subifs[0].sw_if_index, bd_id=cls.bd_id)
+ rx_sw_if_index=cls.subifs[0].sw_if_index, bd_id=cls.bd_id
+ )
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.subifs[1].sw_if_index, bd_id=cls.bd_id)
+ rx_sw_if_index=cls.subifs[1].sw_if_index, bd_id=cls.bd_id
+ )
# Configure IPv4/6 addresses on loop interface and routed interface
cls.loop0.config_ip4()
@@ -122,7 +137,7 @@ class MethodHolder(VppTestCase):
cls.loop0.generate_remote_hosts(cls.remote_hosts_count)
# Modify host mac addresses to have different OUI parts
for i in range(2, cls.remote_hosts_count + 2):
- mac = cls.loop0.remote_hosts[i-2]._mac.split(':')
+ mac = cls.loop0.remote_hosts[i - 2]._mac.split(":")
mac[2] = format(int(mac[2], 16) + i, "02x")
cls.loop0.remote_hosts[i - 2]._mac = ":".join(mac)
@@ -198,18 +213,19 @@ class MethodHolder(VppTestCase):
"""
return acls
- def create_rules(self, mac_type=EXACT_MAC, ip_type=EXACT_IP,
- acl_count=1, rules_count=None):
+ def create_rules(
+ self, mac_type=EXACT_MAC, ip_type=EXACT_IP, acl_count=1, rules_count=None
+ ):
acls = []
if rules_count is None:
rules_count = [1]
src_mac = int("220000dead00", 16)
- for acl in range(2, (acl_count+1) * 2):
+ for acl in range(2, (acl_count + 1) * 2):
rules = []
host = random.choice(self.loop0.remote_hosts)
is_ip6 = acl % 2
- ip4 = host.ip4.split('.')
- ip6 = list(unpack('<16B', inet_pton(AF_INET6, host.ip6)))
+ ip4 = host.ip4.split(".")
+ ip6 = list(unpack("<16B", inet_pton(AF_INET6, host.ip6)))
if ip_type == self.EXACT_IP:
prefix_len4 = 32
@@ -241,11 +257,12 @@ class MethodHolder(VppTestCase):
if mac_type == self.WILD_MAC:
mac = "00:00:00:00:00:00"
elif mac_type == self.OUI_MAC:
- mac = ':'.join(re.findall('..', '{:02x}'.format(
- src_mac))[:3])+":00:00:00"
+ mac = (
+ ":".join(re.findall("..", "{:02x}".format(src_mac))[:3])
+ + ":00:00:00"
+ )
else:
- mac = ':'.join(re.findall(
- '..', '{:02x}'.format(src_mac)))
+ mac = ":".join(re.findall("..", "{:02x}".format(src_mac)))
if ip_type == self.EXACT_IP:
ip4[3] = random.randint(100, 200)
@@ -255,14 +272,16 @@ class MethodHolder(VppTestCase):
ip4[3] = 0
ip6[7] = random.randint(100, 200)
ip6[15] = 0
- ip_pack = b''
+ ip_pack = b""
for j in range(0, len(ip)):
- ip_pack += pack('<B', int(ip[j]))
-
- rule = MacipRule(is_permit=self.PERMIT,
- src_prefix=ip_network((ip_pack, ip_len)),
- src_mac=MACAddress(mac).packed,
- src_mac_mask=MACAddress(mask).packed)
+ ip_pack += pack("<B", int(ip[j]))
+
+ rule = MacipRule(
+ is_permit=self.PERMIT,
+ src_prefix=ip_network((ip_pack, ip_len)),
+ src_mac=MACAddress(mac).packed,
+ src_mac_mask=MACAddress(mask).packed,
+ )
rules.append(rule)
if ip_type == self.WILD_IP:
break
@@ -281,8 +300,8 @@ class MethodHolder(VppTestCase):
def verify_macip_acls(self, acl_count, rules_count, expected_count=2):
reply = self.macip_acl_dump_debug()
- for acl in range(2, (acl_count+1) * 2):
- self.assertEqual(reply[acl - 2].count, rules_count[acl//2-1])
+ for acl in range(2, (acl_count + 1) * 2):
+ self.assertEqual(reply[acl - 2].count, rules_count[acl // 2 - 1])
self.vapi.macip_acl_interface_get()
@@ -292,8 +311,17 @@ class MethodHolder(VppTestCase):
reply = self.vapi.macip_acl_interface_get()
self.assertEqual(reply.count, expected_count)
- def create_stream(self, mac_type, ip_type, packet_count,
- src_if, dst_if, traffic, is_ip6, tags=PERMIT_TAGS):
+ def create_stream(
+ self,
+ mac_type,
+ ip_type,
+ packet_count,
+ src_if,
+ dst_if,
+ traffic,
+ is_ip6,
+ tags=PERMIT_TAGS,
+ ):
# exact MAC and exact IP
# exact MAC and subnet of IPs
# exact MAC and wildcard IP
@@ -329,7 +357,7 @@ class MethodHolder(VppTestCase):
if traffic == self.BRIDGED:
if is_permit:
src_mac = remote_dst_host._mac
- dst_mac = 'de:ad:00:00:00:00'
+ dst_mac = "de:ad:00:00:00:00"
src_ip4 = remote_dst_host.ip4
dst_ip4 = src_if.remote_ip4
src_ip6 = remote_dst_host.ip6
@@ -337,8 +365,8 @@ class MethodHolder(VppTestCase):
ip_permit = src_ip6 if is_ip6 else src_ip4
mac_permit = src_mac
if denyMAC:
- mac = src_mac.split(':')
- mac[0] = format(int(mac[0], 16)+1, "02x")
+ mac = src_mac.split(":")
+ mac[0] = format(int(mac[0], 16) + 1, "02x")
src_mac = ":".join(mac)
if is_ip6:
src_ip6 = ip_permit
@@ -362,7 +390,7 @@ class MethodHolder(VppTestCase):
ip_permit = src_ip6 if is_ip6 else src_ip4
mac_permit = src_mac
if denyMAC:
- mac = src_mac.split(':')
+ mac = src_mac.split(":")
mac[0] = format(int(mac[0], 16) + 1, "02x")
src_mac = ":".join(mac)
if is_ip6:
@@ -385,7 +413,7 @@ class MethodHolder(VppTestCase):
payload = "to be blocked"
if mac_type == self.WILD_MAC:
- mac = src_mac.split(':')
+ mac = src_mac.split(":")
for i in range(1, 5):
mac[i] = format(random.randint(0, 255), "02x")
src_mac = ":".join(mac)
@@ -395,7 +423,7 @@ class MethodHolder(VppTestCase):
ip_rule = src_ip6 if is_ip6 else src_ip4
if is_ip6:
if ip_type != self.EXACT_IP:
- sub_ip = list(unpack('<16B', inet_pton(AF_INET6, ip_rule)))
+ sub_ip = list(unpack("<16B", inet_pton(AF_INET6, ip_rule)))
if ip_type == self.WILD_IP:
sub_ip[0] = random.randint(240, 254)
sub_ip[1] = random.randint(230, 239)
@@ -406,13 +434,12 @@ class MethodHolder(VppTestCase):
sub_ip[2] = int(sub_ip[2]) + 1
sub_ip[14] = random.randint(100, 199)
sub_ip[15] = random.randint(200, 255)
- packed_src_ip6 = b''.join(
- [scapy.compat.chb(x) for x in sub_ip])
+ packed_src_ip6 = b"".join([scapy.compat.chb(x) for x in sub_ip])
src_ip6 = inet_ntop(AF_INET6, packed_src_ip6)
packet /= IPv6(src=src_ip6, dst=dst_ip6)
else:
if ip_type != self.EXACT_IP:
- sub_ip = ip_rule.split('.')
+ sub_ip = ip_rule.split(".")
if ip_type == self.WILD_IP:
sub_ip[0] = random.randint(1, 49)
sub_ip[1] = random.randint(50, 99)
@@ -420,15 +447,15 @@ class MethodHolder(VppTestCase):
sub_ip[3] = random.randint(200, 255)
elif ip_type == self.SUBNET_IP:
if denyIP:
- sub_ip[1] = int(sub_ip[1])+1
+ sub_ip[1] = int(sub_ip[1]) + 1
sub_ip[2] = random.randint(100, 199)
sub_ip[3] = random.randint(200, 255)
- src_ip4 = '.'.join(['{!s}'.format(x) for x in sub_ip])
+ src_ip4 = ".".join(["{!s}".format(x) for x in sub_ip])
packet /= IP(src=src_ip4, dst=dst_ip4, frag=0, flags=0)
- packet /= UDP(sport=src_port, dport=dst_port)/Raw(payload)
+ packet /= UDP(sport=src_port, dport=dst_port) / Raw(payload)
- packet[Raw].load += b" mac:%s" % src_mac.encode('utf-8')
+ packet[Raw].load += b" mac:%s" % src_mac.encode("utf-8")
size = self.pg_if_packet_sizes[p % len(self.pg_if_packet_sizes)]
if isinstance(src_if, VppSubInterface):
@@ -466,8 +493,8 @@ class MethodHolder(VppTestCase):
mac_rule = "00:00:00:00:00:00"
mac_mask = "00:00:00:00:00:00"
elif mac_type == self.OUI_MAC:
- mac = src_mac.split(':')
- mac[3] = mac[4] = mac[5] = '00'
+ mac = src_mac.split(":")
+ mac[3] = mac[4] = mac[5] = "00"
mac_rule = ":".join(mac)
mac_mask = "ff:ff:ff:00:00:00"
@@ -477,11 +504,10 @@ class MethodHolder(VppTestCase):
else:
ip = src_ip6
if ip_type == self.SUBNET_IP:
- sub_ip = list(unpack('<16B', inet_pton(AF_INET6, ip)))
+ sub_ip = list(unpack("<16B", inet_pton(AF_INET6, ip)))
for i in range(8, 16):
sub_ip[i] = 0
- packed_ip = b''.join(
- [scapy.compat.chb(x) for x in sub_ip])
+ packed_ip = b"".join([scapy.compat.chb(x) for x in sub_ip])
ip = inet_ntop(AF_INET6, packed_ip)
else:
if ip_type == self.WILD_IP:
@@ -489,8 +515,8 @@ class MethodHolder(VppTestCase):
else:
ip = src_ip4
if ip_type == self.SUBNET_IP:
- sub_ip = ip.split('.')
- sub_ip[2] = sub_ip[3] = '0'
+ sub_ip = ip.split(".")
+ sub_ip[2] = sub_ip[3] = "0"
ip = ".".join(sub_ip)
prefix_len = 128 if is_ip6 else 32
@@ -508,21 +534,22 @@ class MethodHolder(VppTestCase):
rule_prefix_len = 128 if packet.haslayer(IPv6) else 32
rule_l3_layer = IPv6 if packet.haslayer(IPv6) else IP
if packet.haslayer(IPv6):
- rule_l4_proto = packet[UDP].overload_fields[IPv6]['nh']
+ rule_l4_proto = packet[UDP].overload_fields[IPv6]["nh"]
else:
rule_l4_proto = packet[IP].proto
- src_network = ip_network(
- (packet[rule_l3_layer].src, rule_prefix_len))
- dst_network = ip_network(
- (packet[rule_l3_layer].dst, rule_prefix_len))
- acl_rule = AclRule(is_permit=is_permit, proto=rule_l4_proto,
- src_prefix=src_network,
- dst_prefix=dst_network,
- sport_from=rule_l4_sport,
- sport_to=rule_l4_sport,
- dport_from=rule_l4_dport,
- dport_to=rule_l4_dport)
+ src_network = ip_network((packet[rule_l3_layer].src, rule_prefix_len))
+ dst_network = ip_network((packet[rule_l3_layer].dst, rule_prefix_len))
+ acl_rule = AclRule(
+ is_permit=is_permit,
+ proto=rule_l4_proto,
+ src_prefix=src_network,
+ dst_prefix=dst_network,
+ sport_from=rule_l4_sport,
+ sport_to=rule_l4_sport,
+ dport_from=rule_l4_dport,
+ dport_to=rule_l4_dport,
+ )
acl_rules.append(acl_rule)
if mac_type == self.WILD_MAC and ip_type == self.WILD_IP and p > 0:
@@ -531,10 +558,10 @@ class MethodHolder(VppTestCase):
if is_permit:
macip_rule = MacipRule(
is_permit=is_permit,
- src_prefix=ip_network(
- (ip_rule, prefix_len)),
+ src_prefix=ip_network((ip_rule, prefix_len)),
src_mac=MACAddress(mac_rule).packed,
- src_mac_mask=MACAddress(mac_mask).packed)
+ src_mac_mask=MACAddress(mac_mask).packed,
+ )
macip_rules.append(macip_rule)
# deny all other packets
@@ -544,16 +571,22 @@ class MethodHolder(VppTestCase):
is_permit=0,
src_prefix=network,
src_mac=MACAddress("00:00:00:00:00:00").packed,
- src_mac_mask=MACAddress("00:00:00:00:00:00").packed)
+ src_mac_mask=MACAddress("00:00:00:00:00:00").packed,
+ )
macip_rules.append(macip_rule)
network = IPv6Network((0, 0)) if is_ip6 else IPv4Network((0, 0))
- acl_rule = AclRule(is_permit=0, src_prefix=network, dst_prefix=network,
- sport_from=0, sport_to=0, dport_from=0, dport_to=0)
+ acl_rule = AclRule(
+ is_permit=0,
+ src_prefix=network,
+ dst_prefix=network,
+ sport_from=0,
+ sport_to=0,
+ dport_from=0,
+ dport_to=0,
+ )
acl_rules.append(acl_rule)
- return {'stream': packets,
- 'macip_rules': macip_rules,
- 'acl_rules': acl_rules}
+ return {"stream": packets, "macip_rules": macip_rules, "acl_rules": acl_rules}
def verify_capture(self, stream, capture, is_ip6):
"""
@@ -582,10 +615,20 @@ class MethodHolder(VppTestCase):
# data = p[Raw].load.split(':',1)[1])
# print(p[p_l3].src, data)
- def run_traffic(self, mac_type, ip_type, traffic, is_ip6, packets,
- do_not_expected_capture=False, tags=None,
- apply_rules=True, isMACIP=True, permit_tags=PERMIT_TAGS,
- try_replace=False):
+ def run_traffic(
+ self,
+ mac_type,
+ ip_type,
+ traffic,
+ is_ip6,
+ packets,
+ do_not_expected_capture=False,
+ tags=None,
+ apply_rules=True,
+ isMACIP=True,
+ permit_tags=PERMIT_TAGS,
+ try_replace=False,
+ ):
self.reset_packet_infos()
if tags is None:
@@ -619,21 +662,28 @@ class MethodHolder(VppTestCase):
else:
return
- test_dict = self.create_stream(mac_type, ip_type, packets,
- src_if, dst_if,
- traffic, is_ip6,
- tags=permit_tags)
+ test_dict = self.create_stream(
+ mac_type,
+ ip_type,
+ packets,
+ src_if,
+ dst_if,
+ traffic,
+ is_ip6,
+ tags=permit_tags,
+ )
if apply_rules:
if isMACIP:
- self.acl = VppMacipAcl(self, rules=test_dict['macip_rules'])
+ self.acl = VppMacipAcl(self, rules=test_dict["macip_rules"])
else:
- self.acl = VppAcl(self, rules=test_dict['acl_rules'])
+ self.acl = VppAcl(self, rules=test_dict["acl_rules"])
self.acl.add_vpp_config()
if isMACIP:
self.acl_if = VppMacipAclInterface(
- self, sw_if_index=tx_if.sw_if_index, acls=[self.acl])
+ self, sw_if_index=tx_if.sw_if_index, acls=[self.acl]
+ )
self.acl_if.add_vpp_config()
dump = self.acl_if.dump()
@@ -641,45 +691,51 @@ class MethodHolder(VppTestCase):
self.assertEqual(dump[0].acls[0], self.acl.acl_index)
else:
self.acl_if = VppAclInterface(
- self, sw_if_index=tx_if.sw_if_index, n_input=1,
- acls=[self.acl])
+ self, sw_if_index=tx_if.sw_if_index, n_input=1, acls=[self.acl]
+ )
self.acl_if.add_vpp_config()
else:
if hasattr(self, "acl_if"):
self.acl_if.remove_vpp_config()
if try_replace and hasattr(self, "acl"):
if isMACIP:
- self.acl.modify_vpp_config(test_dict['macip_rules'])
+ self.acl.modify_vpp_config(test_dict["macip_rules"])
else:
- self.acl.modify_vpp_config(test_dict['acl_rules'])
+ self.acl.modify_vpp_config(test_dict["acl_rules"])
if not isinstance(src_if, VppSubInterface):
- tx_if.add_stream(test_dict['stream'])
+ tx_if.add_stream(test_dict["stream"])
else:
- tx_if.parent.add_stream(test_dict['stream'])
+ tx_if.parent.add_stream(test_dict["stream"])
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
if do_not_expected_capture:
rx_if.get_capture(0)
else:
- if traffic == self.BRIDGED and mac_type == self.WILD_MAC and \
- ip_type == self.WILD_IP:
+ if (
+ traffic == self.BRIDGED
+ and mac_type == self.WILD_MAC
+ and ip_type == self.WILD_IP
+ ):
capture = rx_if.get_capture(packets)
else:
capture = rx_if.get_capture(
- self.get_packet_count_for_if_idx(dst_if.sw_if_index))
- self.verify_capture(test_dict['stream'], capture, is_ip6)
+ self.get_packet_count_for_if_idx(dst_if.sw_if_index)
+ )
+ self.verify_capture(test_dict["stream"], capture, is_ip6)
if not isMACIP:
if hasattr(self, "acl_if"):
self.acl_if.remove_vpp_config()
if hasattr(self, "acl"):
self.acl.remove_vpp_config()
- def run_test_acls(self, mac_type, ip_type, acl_count,
- rules_count, traffic=None, ip=None):
- self.apply_macip_rules(self.create_rules(mac_type, ip_type, acl_count,
- rules_count))
+ def run_test_acls(
+ self, mac_type, ip_type, acl_count, rules_count, traffic=None, ip=None
+ ):
+ self.apply_macip_rules(
+ self.create_rules(mac_type, ip_type, acl_count, rules_count)
+ )
self.verify_macip_acls(acl_count, rules_count)
if traffic is not None:
@@ -698,134 +754,104 @@ class TestMACIP_IP4(MethodHolder):
super(TestMACIP_IP4, cls).tearDownClass()
def test_acl_bridged_ip4_exactMAC_exactIP(self):
- """ IP4 MACIP exactMAC|exactIP ACL bridged traffic
- """
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP,
- self.BRIDGED, self.IS_IP4, 9)
+ """IP4 MACIP exactMAC|exactIP ACL bridged traffic"""
+ self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP4, 9)
def test_acl_bridged_ip4_exactMAC_subnetIP(self):
- """ IP4 MACIP exactMAC|subnetIP ACL bridged traffic
- """
+ """IP4 MACIP exactMAC|subnetIP ACL bridged traffic"""
- self.run_traffic(self.EXACT_MAC, self.SUBNET_IP,
- self.BRIDGED, self.IS_IP4, 9)
+ self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP4, 9)
def test_acl_bridged_ip4_exactMAC_wildIP(self):
- """ IP4 MACIP exactMAC|wildIP ACL bridged traffic
- """
+ """IP4 MACIP exactMAC|wildIP ACL bridged traffic"""
- self.run_traffic(self.EXACT_MAC, self.WILD_IP,
- self.BRIDGED, self.IS_IP4, 9)
+ self.run_traffic(self.EXACT_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP4, 9)
def test_acl_bridged_ip4_ouiMAC_exactIP(self):
- """ IP4 MACIP ouiMAC|exactIP ACL bridged traffic
- """
+ """IP4 MACIP ouiMAC|exactIP ACL bridged traffic"""
- self.run_traffic(self.OUI_MAC, self.EXACT_IP,
- self.BRIDGED, self.IS_IP4, 3)
+ self.run_traffic(self.OUI_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP4, 3)
def test_acl_bridged_ip4_ouiMAC_subnetIP(self):
- """ IP4 MACIP ouiMAC|subnetIP ACL bridged traffic
- """
+ """IP4 MACIP ouiMAC|subnetIP ACL bridged traffic"""
- self.run_traffic(self.OUI_MAC, self.SUBNET_IP,
- self.BRIDGED, self.IS_IP4, 9)
+ self.run_traffic(self.OUI_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP4, 9)
def test_acl_bridged_ip4_ouiMAC_wildIP(self):
- """ IP4 MACIP ouiMAC|wildIP ACL bridged traffic
- """
+ """IP4 MACIP ouiMAC|wildIP ACL bridged traffic"""
- self.run_traffic(self.OUI_MAC, self.WILD_IP,
- self.BRIDGED, self.IS_IP4, 9)
+ self.run_traffic(self.OUI_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP4, 9)
def test_ac_bridgedl_ip4_wildMAC_exactIP(self):
- """ IP4 MACIP wildcardMAC|exactIP ACL bridged traffic
- """
+ """IP4 MACIP wildcardMAC|exactIP ACL bridged traffic"""
- self.run_traffic(self.WILD_MAC, self.EXACT_IP,
- self.BRIDGED, self.IS_IP4, 9)
+ self.run_traffic(self.WILD_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP4, 9)
def test_acl_bridged_ip4_wildMAC_subnetIP(self):
- """ IP4 MACIP wildcardMAC|subnetIP ACL bridged traffic
- """
+ """IP4 MACIP wildcardMAC|subnetIP ACL bridged traffic"""
- self.run_traffic(self.WILD_MAC, self.SUBNET_IP,
- self.BRIDGED, self.IS_IP4, 9)
+ self.run_traffic(self.WILD_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP4, 9)
def test_acl_bridged_ip4_wildMAC_wildIP(self):
- """ IP4 MACIP wildcardMAC|wildIP ACL bridged traffic
- """
+ """IP4 MACIP wildcardMAC|wildIP ACL bridged traffic"""
- self.run_traffic(self.WILD_MAC, self.WILD_IP,
- self.BRIDGED, self.IS_IP4, 9)
+ self.run_traffic(self.WILD_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP4, 9)
def test_acl_routed_ip4_exactMAC_exactIP(self):
- """ IP4 MACIP exactMAC|exactIP ACL routed traffic
- """
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP,
- self.ROUTED, self.IS_IP4, 9)
+ """IP4 MACIP exactMAC|exactIP ACL routed traffic"""
+ self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP4, 9)
def test_acl_routed_ip4_exactMAC_subnetIP(self):
- """ IP4 MACIP exactMAC|subnetIP ACL routed traffic
- """
- self.run_traffic(self.EXACT_MAC, self.SUBNET_IP,
- self.ROUTED, self.IS_IP4, 9)
+ """IP4 MACIP exactMAC|subnetIP ACL routed traffic"""
+ self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP4, 9)
def test_acl_routed_ip4_exactMAC_wildIP(self):
- """ IP4 MACIP exactMAC|wildIP ACL routed traffic
- """
- self.run_traffic(self.EXACT_MAC, self.WILD_IP,
- self.ROUTED, self.IS_IP4, 9)
+ """IP4 MACIP exactMAC|wildIP ACL routed traffic"""
+ self.run_traffic(self.EXACT_MAC, self.WILD_IP, self.ROUTED, self.IS_IP4, 9)
def test_acl_routed_ip4_ouiMAC_exactIP(self):
- """ IP4 MACIP ouiMAC|exactIP ACL routed traffic
- """
+ """IP4 MACIP ouiMAC|exactIP ACL routed traffic"""
- self.run_traffic(self.OUI_MAC, self.EXACT_IP,
- self.ROUTED, self.IS_IP4, 9)
+ self.run_traffic(self.OUI_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP4, 9)
def test_acl_routed_ip4_ouiMAC_subnetIP(self):
- """ IP4 MACIP ouiMAC|subnetIP ACL routed traffic
- """
+ """IP4 MACIP ouiMAC|subnetIP ACL routed traffic"""
- self.run_traffic(self.OUI_MAC, self.SUBNET_IP,
- self.ROUTED, self.IS_IP4, 9)
+ self.run_traffic(self.OUI_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP4, 9)
def test_acl_routed_ip4_ouiMAC_wildIP(self):
- """ IP4 MACIP ouiMAC|wildIP ACL routed traffic
- """
+ """IP4 MACIP ouiMAC|wildIP ACL routed traffic"""
- self.run_traffic(self.OUI_MAC, self.WILD_IP,
- self.ROUTED, self.IS_IP4, 9)
+ self.run_traffic(self.OUI_MAC, self.WILD_IP, self.ROUTED, self.IS_IP4, 9)
def test_acl_routed_ip4_wildMAC_exactIP(self):
- """ IP4 MACIP wildcardMAC|exactIP ACL routed traffic
- """
+ """IP4 MACIP wildcardMAC|exactIP ACL routed traffic"""
- self.run_traffic(self.WILD_MAC, self.EXACT_IP,
- self.ROUTED, self.IS_IP4, 9)
+ self.run_traffic(self.WILD_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP4, 9)
def test_acl_routed_ip4_wildMAC_subnetIP(self):
- """ IP4 MACIP wildcardMAC|subnetIP ACL routed traffic
- """
+ """IP4 MACIP wildcardMAC|subnetIP ACL routed traffic"""
- self.run_traffic(self.WILD_MAC, self.SUBNET_IP,
- self.ROUTED, self.IS_IP4, 9)
+ self.run_traffic(self.WILD_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP4, 9)
def test_acl_routed_ip4_wildMAC_wildIP(self):
- """ IP4 MACIP wildcardMAC|wildIP ACL
- """
+ """IP4 MACIP wildcardMAC|wildIP ACL"""
- self.run_traffic(self.WILD_MAC, self.WILD_IP,
- self.ROUTED, self.IS_IP4, 9)
+ self.run_traffic(self.WILD_MAC, self.WILD_IP, self.ROUTED, self.IS_IP4, 9)
def test_acl_replace_traffic_ip4(self):
- """ MACIP replace ACL with IP4 traffic
- """
- self.run_traffic(self.OUI_MAC, self.SUBNET_IP,
- self.BRIDGED, self.IS_IP4, 9, try_replace=True)
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP,
- self.BRIDGED, self.IS_IP4, 9, try_replace=True)
+ """MACIP replace ACL with IP4 traffic"""
+ self.run_traffic(
+ self.OUI_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP4, 9, try_replace=True
+ )
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.BRIDGED,
+ self.IS_IP4,
+ 9,
+ try_replace=True,
+ )
class TestMACIP_IP6(MethodHolder):
@@ -840,138 +866,108 @@ class TestMACIP_IP6(MethodHolder):
super(TestMACIP_IP6, cls).tearDownClass()
def test_acl_bridged_ip6_exactMAC_exactIP(self):
- """ IP6 MACIP exactMAC|exactIP ACL bridged traffic
- """
+ """IP6 MACIP exactMAC|exactIP ACL bridged traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP,
- self.BRIDGED, self.IS_IP6, 9)
+ self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP6, 9)
def test_acl_bridged_ip6_exactMAC_subnetIP(self):
- """ IP6 MACIP exactMAC|subnetIP ACL bridged traffic
- """
+ """IP6 MACIP exactMAC|subnetIP ACL bridged traffic"""
- self.run_traffic(self.EXACT_MAC, self.SUBNET_IP,
- self.BRIDGED, self.IS_IP6, 9)
+ self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP6, 9)
def test_acl_bridged_ip6_exactMAC_wildIP(self):
- """ IP6 MACIP exactMAC|wildIP ACL bridged traffic
- """
+ """IP6 MACIP exactMAC|wildIP ACL bridged traffic"""
- self.run_traffic(self.EXACT_MAC, self.WILD_IP,
- self.BRIDGED, self.IS_IP6, 9)
+ self.run_traffic(self.EXACT_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP6, 9)
def test_acl_bridged_ip6_ouiMAC_exactIP(self):
- """ IP6 MACIP oui_MAC|exactIP ACL bridged traffic
- """
+ """IP6 MACIP oui_MAC|exactIP ACL bridged traffic"""
- self.run_traffic(self.OUI_MAC, self.EXACT_IP,
- self.BRIDGED, self.IS_IP6, 9)
+ self.run_traffic(self.OUI_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP6, 9)
def test_acl_bridged_ip6_ouiMAC_subnetIP(self):
- """ IP6 MACIP ouiMAC|subnetIP ACL bridged traffic
- """
+ """IP6 MACIP ouiMAC|subnetIP ACL bridged traffic"""
- self.run_traffic(self.OUI_MAC, self.SUBNET_IP,
- self.BRIDGED, self.IS_IP6, 9)
+ self.run_traffic(self.OUI_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP6, 9)
def test_acl_bridged_ip6_ouiMAC_wildIP(self):
- """ IP6 MACIP ouiMAC|wildIP ACL bridged traffic
- """
+ """IP6 MACIP ouiMAC|wildIP ACL bridged traffic"""
- self.run_traffic(self.OUI_MAC, self.WILD_IP,
- self.BRIDGED, self.IS_IP6, 9)
+ self.run_traffic(self.OUI_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP6, 9)
def test_acl_bridged_ip6_wildMAC_exactIP(self):
- """ IP6 MACIP wildcardMAC|exactIP ACL bridged traffic
- """
+ """IP6 MACIP wildcardMAC|exactIP ACL bridged traffic"""
- self.run_traffic(self.WILD_MAC, self.EXACT_IP,
- self.BRIDGED, self.IS_IP6, 9)
+ self.run_traffic(self.WILD_MAC, self.EXACT_IP, self.BRIDGED, self.IS_IP6, 9)
def test_acl_bridged_ip6_wildMAC_subnetIP(self):
- """ IP6 MACIP wildcardMAC|subnetIP ACL bridged traffic
- """
+ """IP6 MACIP wildcardMAC|subnetIP ACL bridged traffic"""
- self.run_traffic(self.WILD_MAC, self.SUBNET_IP,
- self.BRIDGED, self.IS_IP6, 9)
+ self.run_traffic(self.WILD_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP6, 9)
def test_acl_bridged_ip6_wildMAC_wildIP(self):
- """ IP6 MACIP wildcardMAC|wildIP ACL bridged traffic
- """
+ """IP6 MACIP wildcardMAC|wildIP ACL bridged traffic"""
- self.run_traffic(self.WILD_MAC, self.WILD_IP,
- self.BRIDGED, self.IS_IP6, 9)
+ self.run_traffic(self.WILD_MAC, self.WILD_IP, self.BRIDGED, self.IS_IP6, 9)
def test_acl_routed_ip6_exactMAC_exactIP(self):
- """ IP6 MACIP exactMAC|exactIP ACL routed traffic
- """
+ """IP6 MACIP exactMAC|exactIP ACL routed traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP,
- self.ROUTED, self.IS_IP6, 9)
+ self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP6, 9)
def test_acl_routed_ip6_exactMAC_subnetIP(self):
- """ IP6 MACIP exactMAC|subnetIP ACL routed traffic
- """
+ """IP6 MACIP exactMAC|subnetIP ACL routed traffic"""
- self.run_traffic(self.EXACT_MAC, self.SUBNET_IP,
- self.ROUTED, self.IS_IP6, 9)
+ self.run_traffic(self.EXACT_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP6, 9)
def test_acl_routed_ip6_exactMAC_wildIP(self):
- """ IP6 MACIP exactMAC|wildIP ACL routed traffic
- """
+ """IP6 MACIP exactMAC|wildIP ACL routed traffic"""
- self.run_traffic(self.EXACT_MAC, self.WILD_IP,
- self.ROUTED, self.IS_IP6, 9)
+ self.run_traffic(self.EXACT_MAC, self.WILD_IP, self.ROUTED, self.IS_IP6, 9)
def test_acl_routed_ip6_ouiMAC_exactIP(self):
- """ IP6 MACIP ouiMAC|exactIP ACL routed traffic
- """
+ """IP6 MACIP ouiMAC|exactIP ACL routed traffic"""
- self.run_traffic(self.OUI_MAC, self.EXACT_IP,
- self.ROUTED, self.IS_IP6, 9)
+ self.run_traffic(self.OUI_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP6, 9)
def test_acl_routed_ip6_ouiMAC_subnetIP(self):
- """ IP6 MACIP ouiMAC|subnetIP ACL routed traffic
- """
+ """IP6 MACIP ouiMAC|subnetIP ACL routed traffic"""
- self.run_traffic(self.OUI_MAC, self.SUBNET_IP,
- self.ROUTED, self.IS_IP6, 9)
+ self.run_traffic(self.OUI_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP6, 9)
def test_acl_routed_ip6_ouiMAC_wildIP(self):
- """ IP6 MACIP ouiMAC|wildIP ACL routed traffic
- """
+ """IP6 MACIP ouiMAC|wildIP ACL routed traffic"""
- self.run_traffic(self.OUI_MAC, self.WILD_IP,
- self.ROUTED, self.IS_IP6, 9)
+ self.run_traffic(self.OUI_MAC, self.WILD_IP, self.ROUTED, self.IS_IP6, 9)
def test_acl_routed_ip6_wildMAC_exactIP(self):
- """ IP6 MACIP wildcardMAC|exactIP ACL routed traffic
- """
+ """IP6 MACIP wildcardMAC|exactIP ACL routed traffic"""
- self.run_traffic(self.WILD_MAC, self.EXACT_IP,
- self.ROUTED, self.IS_IP6, 9)
+ self.run_traffic(self.WILD_MAC, self.EXACT_IP, self.ROUTED, self.IS_IP6, 9)
def test_acl_routed_ip6_wildMAC_subnetIP(self):
- """ IP6 MACIP wildcardMAC|subnetIP ACL routed traffic
- """
+ """IP6 MACIP wildcardMAC|subnetIP ACL routed traffic"""
- self.run_traffic(self.WILD_MAC, self.SUBNET_IP,
- self.ROUTED, self.IS_IP6, 9)
+ self.run_traffic(self.WILD_MAC, self.SUBNET_IP, self.ROUTED, self.IS_IP6, 9)
def test_acl_routed_ip6_wildMAC_wildIP(self):
- """ IP6 MACIP wildcardMAC|wildIP ACL
- """
+ """IP6 MACIP wildcardMAC|wildIP ACL"""
- self.run_traffic(self.WILD_MAC, self.WILD_IP,
- self.ROUTED, self.IS_IP6, 9)
+ self.run_traffic(self.WILD_MAC, self.WILD_IP, self.ROUTED, self.IS_IP6, 9)
def test_acl_replace_traffic_ip6(self):
- """ MACIP replace ACL with IP6 traffic
- """
- self.run_traffic(self.OUI_MAC, self.SUBNET_IP,
- self.BRIDGED, self.IS_IP6, 9, try_replace=True)
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP,
- self.BRIDGED, self.IS_IP6, 9, try_replace=True)
+ """MACIP replace ACL with IP6 traffic"""
+ self.run_traffic(
+ self.OUI_MAC, self.SUBNET_IP, self.BRIDGED, self.IS_IP6, 9, try_replace=True
+ )
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.BRIDGED,
+ self.IS_IP6,
+ 9,
+ try_replace=True,
+ )
class TestMACIP(MethodHolder):
@@ -986,73 +982,76 @@ class TestMACIP(MethodHolder):
super(TestMACIP, cls).tearDownClass()
def test_acl_1_2(self):
- """ MACIP ACL with 2 entries
- """
+ """MACIP ACL with 2 entries"""
self.run_test_acls(self.EXACT_MAC, self.WILD_IP, 1, [2])
def test_acl_1_5(self):
- """ MACIP ACL with 5 entries
- """
+ """MACIP ACL with 5 entries"""
self.run_test_acls(self.EXACT_MAC, self.SUBNET_IP, 1, [5])
def test_acl_1_10(self):
- """ MACIP ACL with 10 entries
- """
+ """MACIP ACL with 10 entries"""
self.run_test_acls(self.EXACT_MAC, self.EXACT_IP, 1, [10])
def test_acl_1_20(self):
- """ MACIP ACL with 20 entries
- """
+ """MACIP ACL with 20 entries"""
self.run_test_acls(self.OUI_MAC, self.WILD_IP, 1, [20])
def test_acl_1_50(self):
- """ MACIP ACL with 50 entries
- """
+ """MACIP ACL with 50 entries"""
self.run_test_acls(self.OUI_MAC, self.SUBNET_IP, 1, [50])
def test_acl_1_100(self):
- """ MACIP ACL with 100 entries
- """
+ """MACIP ACL with 100 entries"""
self.run_test_acls(self.OUI_MAC, self.EXACT_IP, 1, [100])
def test_acl_2_X(self):
- """ MACIP 2 ACLs each with 100+ entries
- """
+ """MACIP 2 ACLs each with 100+ entries"""
self.run_test_acls(self.OUI_MAC, self.SUBNET_IP, 2, [100, 200])
def test_acl_10_X(self):
- """ MACIP 10 ACLs each with 100+ entries
- """
+ """MACIP 10 ACLs each with 100+ entries"""
- self.run_test_acls(self.EXACT_MAC, self.EXACT_IP, 10,
- [100, 120, 140, 160, 180, 200, 210, 220, 230, 240])
+ self.run_test_acls(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ 10,
+ [100, 120, 140, 160, 180, 200, 210, 220, 230, 240],
+ )
def test_acl_10_X_traffic_ip4(self):
- """ MACIP 10 ACLs each with 100+ entries with IP4 traffic
- """
+ """MACIP 10 ACLs each with 100+ entries with IP4 traffic"""
- self.run_test_acls(self.EXACT_MAC, self.EXACT_IP, 10,
- [100, 120, 140, 160, 180, 200, 210, 220, 230, 240],
- self.BRIDGED, self.IS_IP4)
+ self.run_test_acls(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ 10,
+ [100, 120, 140, 160, 180, 200, 210, 220, 230, 240],
+ self.BRIDGED,
+ self.IS_IP4,
+ )
def test_acl_10_X_traffic_ip6(self):
- """ MACIP 10 ACLs each with 100+ entries with IP6 traffic
- """
+ """MACIP 10 ACLs each with 100+ entries with IP6 traffic"""
- self.run_test_acls(self.EXACT_MAC, self.EXACT_IP, 10,
- [100, 120, 140, 160, 180, 200, 210, 220, 230, 240],
- self.BRIDGED, self.IS_IP6)
+ self.run_test_acls(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ 10,
+ [100, 120, 140, 160, 180, 200, 210, 220, 230, 240],
+ self.BRIDGED,
+ self.IS_IP6,
+ )
def test_acl_replace(self):
- """ MACIP replace ACL
- """
+ """MACIP replace ACL"""
r1 = self.create_rules(acl_count=3, rules_count=[2, 2, 2])
r2 = self.create_rules(mac_type=self.OUI_MAC, ip_type=self.SUBNET_IP)
@@ -1069,17 +1068,15 @@ class TestMACIP(MethodHolder):
# verify changes
self.assertEqual(len(acls_before), len(acls_after))
for acl1, acl2 in zip(
- acls_before[:2]+acls_before[4:],
- acls_after[:2]+acls_after[4:]):
+ acls_before[:2] + acls_before[4:], acls_after[:2] + acls_after[4:]
+ ):
self.assertEqual(len(acl1), len(acl2))
self.assertEqual(len(acl1.r), len(acl2.r))
for r1, r2 in zip(acl1.r, acl2.r):
self.assertEqual(len(acl1.r), len(acl2.r))
self.assertEqual(acl1.r, acl2.r)
- for acl1, acl2 in zip(
- acls_before[2:4],
- acls_after[2:4]):
+ for acl1, acl2 in zip(acls_before[2:4], acls_after[2:4]):
self.assertEqual(len(acl1), len(acl2))
self.assertNotEqual(len(acl1.r), len(acl2.r))
@@ -1088,38 +1085,40 @@ class TestMACIP(MethodHolder):
self.assertNotEqual(acl1.r, acl2.r)
def test_delete_intf(self):
- """ MACIP ACL delete intf with acl
- """
+ """MACIP ACL delete intf with acl"""
- intf_count = len(self.interfaces)+1
+ intf_count = len(self.interfaces) + 1
intf = []
macip_alcs = self.apply_macip_rules(
- self.create_rules(acl_count=3, rules_count=[3, 5, 4]))
+ self.create_rules(acl_count=3, rules_count=[3, 5, 4])
+ )
intf.append(VppLoInterface(self))
intf.append(VppLoInterface(self))
sw_if_index0 = intf[0].sw_if_index
macip_acl_if0 = VppMacipAclInterface(
- self, sw_if_index=sw_if_index0, acls=[macip_alcs[1]])
+ self, sw_if_index=sw_if_index0, acls=[macip_alcs[1]]
+ )
macip_acl_if0.add_vpp_config()
reply = self.vapi.macip_acl_interface_get()
- self.assertEqual(reply.count, intf_count+1)
+ self.assertEqual(reply.count, intf_count + 1)
self.assertEqual(reply.acls[sw_if_index0], 1)
sw_if_index1 = intf[1].sw_if_index
macip_acl_if1 = VppMacipAclInterface(
- self, sw_if_index=sw_if_index1, acls=[macip_alcs[0]])
+ self, sw_if_index=sw_if_index1, acls=[macip_alcs[0]]
+ )
macip_acl_if1.add_vpp_config()
reply = self.vapi.macip_acl_interface_get()
- self.assertEqual(reply.count, intf_count+2)
+ self.assertEqual(reply.count, intf_count + 2)
self.assertEqual(reply.acls[sw_if_index1], 0)
intf[0].remove_vpp_config()
reply = self.vapi.macip_acl_interface_get()
- self.assertEqual(reply.count, intf_count+2)
+ self.assertEqual(reply.count, intf_count + 2)
self.assertEqual(reply.acls[sw_if_index0], 4294967295)
self.assertEqual(reply.acls[sw_if_index1], 0)
@@ -1128,14 +1127,16 @@ class TestMACIP(MethodHolder):
sw_if_index2 = intf[2].sw_if_index
sw_if_index3 = intf[3].sw_if_index
macip_acl_if2 = VppMacipAclInterface(
- self, sw_if_index=sw_if_index2, acls=[macip_alcs[1]])
+ self, sw_if_index=sw_if_index2, acls=[macip_alcs[1]]
+ )
macip_acl_if2.add_vpp_config()
macip_acl_if3 = VppMacipAclInterface(
- self, sw_if_index=sw_if_index3, acls=[macip_alcs[1]])
+ self, sw_if_index=sw_if_index3, acls=[macip_alcs[1]]
+ )
macip_acl_if3.add_vpp_config()
reply = self.vapi.macip_acl_interface_get()
- self.assertEqual(reply.count, intf_count+3)
+ self.assertEqual(reply.count, intf_count + 3)
self.assertEqual(reply.acls[sw_if_index1], 0)
self.assertEqual(reply.acls[sw_if_index2], 1)
self.assertEqual(reply.acls[sw_if_index3], 1)
@@ -1150,7 +1151,7 @@ class TestMACIP(MethodHolder):
intf[1].remove_vpp_config()
reply = self.vapi.macip_acl_interface_get()
- self.assertEqual(reply.count, intf_count+3)
+ self.assertEqual(reply.count, intf_count + 3)
self.assertEqual(reply.acls[sw_if_index0], 4294967295)
self.assertEqual(reply.acls[sw_if_index1], 4294967295)
self.assertEqual(reply.acls[sw_if_index2], 4294967295)
@@ -1174,14 +1175,28 @@ class TestACL_dot1q_bridged(MethodHolder):
super(TestACL_dot1q_bridged, cls).tearDownClass()
def test_acl_bridged_ip4_subif_dot1q(self):
- """ IP4 ACL SubIf Dot1Q bridged traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED,
- self.IS_IP4, 9, tags=self.DOT1Q, isMACIP=False)
+ """IP4 ACL SubIf Dot1Q bridged traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.BRIDGED,
+ self.IS_IP4,
+ 9,
+ tags=self.DOT1Q,
+ isMACIP=False,
+ )
def test_acl_bridged_ip6_subif_dot1q(self):
- """ IP6 ACL SubIf Dot1Q bridged traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED,
- self.IS_IP6, 9, tags=self.DOT1Q, isMACIP=False)
+ """IP6 ACL SubIf Dot1Q bridged traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.BRIDGED,
+ self.IS_IP6,
+ 9,
+ tags=self.DOT1Q,
+ isMACIP=False,
+ )
class TestACL_dot1ad_bridged(MethodHolder):
@@ -1196,14 +1211,28 @@ class TestACL_dot1ad_bridged(MethodHolder):
super(TestACL_dot1ad_bridged, cls).tearDownClass()
def test_acl_bridged_ip4_subif_dot1ad(self):
- """ IP4 ACL SubIf Dot1AD bridged traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED,
- self.IS_IP4, 9, tags=self.DOT1AD, isMACIP=False)
+ """IP4 ACL SubIf Dot1AD bridged traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.BRIDGED,
+ self.IS_IP4,
+ 9,
+ tags=self.DOT1AD,
+ isMACIP=False,
+ )
def test_acl_bridged_ip6_subif_dot1ad(self):
- """ IP6 ACL SubIf Dot1AD bridged traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.BRIDGED,
- self.IS_IP6, 9, tags=self.DOT1AD, isMACIP=False)
+ """IP6 ACL SubIf Dot1AD bridged traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.BRIDGED,
+ self.IS_IP6,
+ 9,
+ tags=self.DOT1AD,
+ isMACIP=False,
+ )
class TestACL_dot1q_routed(MethodHolder):
@@ -1218,26 +1247,56 @@ class TestACL_dot1q_routed(MethodHolder):
super(TestACL_dot1q_routed, cls).tearDownClass()
def test_acl_routed_ip4_subif_dot1q(self):
- """ IP4 ACL SubIf Dot1Q routed traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED,
- self.IS_IP4, 9, tags=self.DOT1Q, isMACIP=False)
+ """IP4 ACL SubIf Dot1Q routed traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.ROUTED,
+ self.IS_IP4,
+ 9,
+ tags=self.DOT1Q,
+ isMACIP=False,
+ )
def test_acl_routed_ip6_subif_dot1q(self):
- """ IP6 ACL SubIf Dot1Q routed traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED,
- self.IS_IP6, 9, tags=self.DOT1Q, isMACIP=False)
+ """IP6 ACL SubIf Dot1Q routed traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.ROUTED,
+ self.IS_IP6,
+ 9,
+ tags=self.DOT1Q,
+ isMACIP=False,
+ )
def test_acl_routed_ip4_subif_dot1q_deny_by_tags(self):
- """ IP4 ACL SubIf wrong tags Dot1Q routed traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED,
- self.IS_IP4, 9, True, tags=self.DOT1Q, isMACIP=False,
- permit_tags=self.DENY_TAGS)
+ """IP4 ACL SubIf wrong tags Dot1Q routed traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.ROUTED,
+ self.IS_IP4,
+ 9,
+ True,
+ tags=self.DOT1Q,
+ isMACIP=False,
+ permit_tags=self.DENY_TAGS,
+ )
def test_acl_routed_ip6_subif_dot1q_deny_by_tags(self):
- """ IP6 ACL SubIf wrong tags Dot1Q routed traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED,
- self.IS_IP6, 9, True, tags=self.DOT1Q, isMACIP=False,
- permit_tags=self.DENY_TAGS)
+ """IP6 ACL SubIf wrong tags Dot1Q routed traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.ROUTED,
+ self.IS_IP6,
+ 9,
+ True,
+ tags=self.DOT1Q,
+ isMACIP=False,
+ permit_tags=self.DENY_TAGS,
+ )
class TestACL_dot1ad_routed(MethodHolder):
@@ -1252,27 +1311,57 @@ class TestACL_dot1ad_routed(MethodHolder):
super(TestACL_dot1ad_routed, cls).tearDownClass()
def test_acl_routed_ip6_subif_dot1ad(self):
- """ IP6 ACL SubIf Dot1AD routed traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED,
- self.IS_IP6, 9, tags=self.DOT1AD, isMACIP=False)
+ """IP6 ACL SubIf Dot1AD routed traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.ROUTED,
+ self.IS_IP6,
+ 9,
+ tags=self.DOT1AD,
+ isMACIP=False,
+ )
def test_acl_routed_ip4_subif_dot1ad(self):
- """ IP4 ACL SubIf Dot1AD routed traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED,
- self.IS_IP4, 9, tags=self.DOT1AD, isMACIP=False)
+ """IP4 ACL SubIf Dot1AD routed traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.ROUTED,
+ self.IS_IP4,
+ 9,
+ tags=self.DOT1AD,
+ isMACIP=False,
+ )
def test_acl_routed_ip6_subif_dot1ad_deny_by_tags(self):
- """ IP6 ACL SubIf wrong tags Dot1AD routed traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED,
- self.IS_IP6, 9, True, tags=self.DOT1AD, isMACIP=False,
- permit_tags=self.DENY_TAGS)
+ """IP6 ACL SubIf wrong tags Dot1AD routed traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.ROUTED,
+ self.IS_IP6,
+ 9,
+ True,
+ tags=self.DOT1AD,
+ isMACIP=False,
+ permit_tags=self.DENY_TAGS,
+ )
def test_acl_routed_ip4_subif_dot1ad_deny_by_tags(self):
- """ IP4 ACL SubIf wrong tags Dot1AD routed traffic"""
- self.run_traffic(self.EXACT_MAC, self.EXACT_IP, self.ROUTED,
- self.IS_IP4, 9, True, tags=self.DOT1AD, isMACIP=False,
- permit_tags=self.DENY_TAGS)
-
-
-if __name__ == '__main__':
+ """IP4 ACL SubIf wrong tags Dot1AD routed traffic"""
+ self.run_traffic(
+ self.EXACT_MAC,
+ self.EXACT_IP,
+ self.ROUTED,
+ self.IS_IP4,
+ 9,
+ True,
+ tags=self.DOT1AD,
+ isMACIP=False,
+ permit_tags=self.DENY_TAGS,
+ )
+
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_adl.py b/test/test_adl.py
index 0463e258013..f58147d2d58 100644
--- a/test/test_adl.py
+++ b/test/test_adl.py
@@ -7,7 +7,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
class TestAdl(VppTestCase):
- """ Allow/Deny Plugin Unit Test Cases """
+ """Allow/Deny Plugin Unit Test Cases"""
@classmethod
def setUpClass(cls):
@@ -24,80 +24,86 @@ class TestAdl(VppTestCase):
super(TestAdl, self).tearDown()
def test_adl1_unittest(self):
- """ Plugin API Test """
- cmds = ["loop create\n",
- "set int ip address loop0 192.168.1.1/24\n",
- "set int ip6 table loop0 0\n",
- "set int ip address loop0 2001:db01::1/64\n",
- "set int state loop0 up\n",
- "packet-generator new {\n"
- " name ip4\n"
- " limit 100\n"
- " rate 0\n"
- " size 128-128\n"
- " interface loop0\n"
- " node adl-input\n"
- " data { IP4: 1.2.40 -> 3cfd.fed0.b6c8\n"
- " UDP: 192.168.1.2-192.168.1.10 -> 192.168.2.1\n"
- " UDP: 1234 -> 2345\n"
- " incrementing 114\n"
- " }\n"
- " }\n",
- "packet-generator new {\n"
- " name ip6-allow\n"
- " limit 50\n"
- " rate 0\n"
- " size 128-128\n"
- " interface loop0\n"
- " node adl-input\n"
- " data { IP6: 1.2.40 -> 3cfd.fed0.b6c8\n"
- " UDP: 2001:db01::2 -> 2001:db01::1\n"
- " UDP: 1234 -> 2345\n"
- " incrementing 80\n"
- " }\n"
- " }\n",
- "packet-generator new {\n"
- " name ip6-drop\n"
- " limit 50\n"
- " rate 0\n"
- " size 128-128\n"
- " interface loop0\n"
- " node adl-input\n"
- " data { IP6: 1.2.40 -> 3cfd.fed0.b6c8\n"
- " UDP: 2001:db01::3 -> 2001:db01::1\n"
- " UDP: 1234 -> 2345\n"
- " incrementing 80\n"
- " }\n"
- " }\n",
- "ip table 1\n",
- "ip route add 192.168.2.1/32 via drop\n",
- "ip route add table 1 192.168.1.2/32 via local\n",
- "ip6 table 1\n",
- "ip route add 2001:db01::1/128 via drop\n",
- "ip route add table 1 2001:db01::2/128 via local\n",
- "bin adl_interface_enable_disable loop0\n",
- "bin adl_allowlist_enable_disable loop0 fib-id 1 ip4 ip6\n",
- "pa en\n"]
+ """Plugin API Test"""
+ cmds = [
+ "loop create\n",
+ "set int ip address loop0 192.168.1.1/24\n",
+ "set int ip6 table loop0 0\n",
+ "set int ip address loop0 2001:db01::1/64\n",
+ "set int state loop0 up\n",
+ "packet-generator new {\n"
+ " name ip4\n"
+ " limit 100\n"
+ " rate 0\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " node adl-input\n"
+ " data { IP4: 1.2.40 -> 3cfd.fed0.b6c8\n"
+ " UDP: 192.168.1.2-192.168.1.10 -> 192.168.2.1\n"
+ " UDP: 1234 -> 2345\n"
+ " incrementing 114\n"
+ " }\n"
+ " }\n",
+ "packet-generator new {\n"
+ " name ip6-allow\n"
+ " limit 50\n"
+ " rate 0\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " node adl-input\n"
+ " data { IP6: 1.2.40 -> 3cfd.fed0.b6c8\n"
+ " UDP: 2001:db01::2 -> 2001:db01::1\n"
+ " UDP: 1234 -> 2345\n"
+ " incrementing 80\n"
+ " }\n"
+ " }\n",
+ "packet-generator new {\n"
+ " name ip6-drop\n"
+ " limit 50\n"
+ " rate 0\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " node adl-input\n"
+ " data { IP6: 1.2.40 -> 3cfd.fed0.b6c8\n"
+ " UDP: 2001:db01::3 -> 2001:db01::1\n"
+ " UDP: 1234 -> 2345\n"
+ " incrementing 80\n"
+ " }\n"
+ " }\n",
+ "ip table 1\n",
+ "ip route add 192.168.2.1/32 via drop\n",
+ "ip route add table 1 192.168.1.2/32 via local\n",
+ "ip6 table 1\n",
+ "ip route add 2001:db01::1/128 via drop\n",
+ "ip route add table 1 2001:db01::2/128 via local\n",
+ "bin adl_interface_enable_disable loop0\n",
+ "bin adl_allowlist_enable_disable loop0 fib-id 1 ip4 ip6\n",
+ "pa en\n",
+ ]
for cmd in cmds:
r = self.vapi.cli_return_response(cmd)
if r.retval != 0:
- if hasattr(r, 'reply'):
+ if hasattr(r, "reply"):
self.logger.info(cmd + " FAIL reply " + r.reply)
else:
self.logger.info(cmd + " FAIL retval " + str(r.retval))
total_pkts = self.statistics.get_err_counter(
- "/err/adl-input/Allow/Deny packets processed")
+ "/err/adl-input/Allow/Deny packets processed"
+ )
self.assertEqual(total_pkts, 200)
ip4_allow = self.statistics.get_err_counter(
- "/err/ip4-adl-allowlist/ip4 allowlist allowed")
+ "/err/ip4-adl-allowlist/ip4 allowlist allowed"
+ )
self.assertEqual(ip4_allow, 12)
ip6_allow = self.statistics.get_err_counter(
- "/err/ip6-adl-allowlist/ip6 allowlist allowed")
+ "/err/ip6-adl-allowlist/ip6 allowlist allowed"
+ )
self.assertEqual(ip6_allow, 50)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_api_client.py b/test/test_api_client.py
index ec44be7e370..200835b0878 100644
--- a/test/test_api_client.py
+++ b/test/test_api_client.py
@@ -7,14 +7,15 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
class TestAPIClient(VppTestCase):
- """ API Internal client Test Cases """
+ """API Internal client Test Cases"""
def test_client_unittest(self):
- """ Internal API client """
+ """Internal API client"""
error = self.vapi.cli("test api internal")
if error:
self.logger.critical(error)
- self.assertNotIn('failed', error)
+ self.assertNotIn("failed", error)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_api_trace.py b/test/test_api_trace.py
index 6524878a10d..ae70666d66c 100644
--- a/test/test_api_trace.py
+++ b/test/test_api_trace.py
@@ -6,7 +6,7 @@ import json
class TestJsonApiTrace(VppTestCase):
- """ JSON API trace related tests """
+ """JSON API trace related tests"""
@classmethod
def setUpClass(cls):
@@ -24,24 +24,24 @@ class TestJsonApiTrace(VppTestCase):
def test_json_api_trace_save(self):
self.vapi.show_version()
- fname = 'test_api_trace-%d.json' % self.vpp.pid
+ fname = "test_api_trace-%d.json" % self.vpp.pid
tmp_api_trace = "/tmp/%s" % fname
- fpath = '%s/%s' % (self.tempdir, fname)
+ fpath = "%s/%s" % (self.tempdir, fname)
self.vapi.cli("api trace save-json {}".format(fname))
os.rename(tmp_api_trace, fpath)
- with open(fpath, encoding='utf-8') as f:
+ with open(fpath, encoding="utf-8") as f:
s = f.read()
trace = json.loads(s)
found = False
for o in trace:
- if o['_msgname'] == 'show_version':
+ if o["_msgname"] == "show_version":
found = True
break
self.assertTrue(found)
- self.assertEquals(o['_msgname'], 'show_version')
+ self.assertEquals(o["_msgname"], "show_version")
def test_json_api_trace_replay(self):
- fname = '/tmp/create_loop.json'
+ fname = "/tmp/create_loop.json"
req = """
[
{
@@ -50,14 +50,13 @@ class TestJsonApiTrace(VppTestCase):
"mac_address": "00:00:00:00:00:00"
}]
"""
- with open(fname, 'w') as f:
+ with open(fname, "w") as f:
f.write(req)
self.vapi.cli("api trace replay-json {}".format(fname))
- r = self.vapi.sw_interface_dump(name_filter='loop',
- name_filter_valid=True)
+ r = self.vapi.sw_interface_dump(name_filter="loop", name_filter_valid=True)
self.assertEqual(len(r), 1)
- self.assertEqual(r[0].interface_name, 'loop0')
+ self.assertEqual(r[0].interface_name, "loop0")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_arping.py b/test/test_arping.py
index bd8b6250a54..a3e7e041ba1 100644
--- a/test/test_arping.py
+++ b/test/test_arping.py
@@ -11,7 +11,7 @@ Basic test for sanity check of arping.
class TestArping(VppTestCase):
- """ Arping Test Case """
+ """Arping Test Case"""
@classmethod
def setUpClass(cls):
@@ -65,7 +65,7 @@ class TestArping(VppTestCase):
self.assertEqual(src, ipv6.src)
def test_arping_ip4_arp_request_cli(self):
- """ arping IP4 arp request CLI test """
+ """arping IP4 arp request CLI test"""
try:
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -81,19 +81,19 @@ class TestArping(VppTestCase):
out = self.pg1.get_capture(6)
for p in out:
- self.verify_arping_request(p, self.pg1.local_ip4,
- self.pg1.remote_ip4)
+ self.verify_arping_request(p, self.pg1.local_ip4, self.pg1.remote_ip4)
finally:
self.vapi.cli("show error")
def test_arping_ip4_garp_cli(self):
- """ arping ip4 gratuitous arp CLI test """
+ """arping ip4 gratuitous arp CLI test"""
try:
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- ping_cmd = ("arping gratuitous" + self.pg1.local_ip4 +
- "pg1 repeat 5 interval 0.1")
+ ping_cmd = (
+ "arping gratuitous" + self.pg1.local_ip4 + "pg1 repeat 5 interval 0.1"
+ )
ret = self.vapi.cli(ping_cmd)
self.logger.info(ret)
@@ -103,60 +103,65 @@ class TestArping(VppTestCase):
out = self.pg1.get_capture(6)
for p in out:
- self.verify_arping_request(p, self.pg1.local_ip4,
- self.pg1.local_ip4)
+ self.verify_arping_request(p, self.pg1.local_ip4, self.pg1.local_ip4)
finally:
self.vapi.cli("show error")
def test_arping_ip4_arp_request_api(self):
- """ arping ip4 arp request API test """
+ """arping ip4 arp request API test"""
try:
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
remote_ip4 = self.pg1.remote_ip4
- ret = self.vapi.arping(address=remote_ip4,
- sw_if_index=self.pg1.sw_if_index,
- is_garp=0, repeat=5, interval=0.1)
+ ret = self.vapi.arping(
+ address=remote_ip4,
+ sw_if_index=self.pg1.sw_if_index,
+ is_garp=0,
+ repeat=5,
+ interval=0.1,
+ )
self.logger.info(ret)
- ret = self.vapi.arping(address=remote_ip4,
- sw_if_index=self.pg1.sw_if_index,
- is_garp=0)
+ ret = self.vapi.arping(
+ address=remote_ip4, sw_if_index=self.pg1.sw_if_index, is_garp=0
+ )
self.logger.info(ret)
out = self.pg1.get_capture(6)
for p in out:
- self.verify_arping_request(p, self.pg1.local_ip4,
- self.pg1.remote_ip4)
+ self.verify_arping_request(p, self.pg1.local_ip4, self.pg1.remote_ip4)
finally:
self.vapi.cli("show error")
def test_arping_ip4_garp_api(self):
- """ arping ip4 gratuitous arp API test """
+ """arping ip4 gratuitous arp API test"""
try:
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- ret = self.vapi.arping(address=self.pg1.local_ip4,
- sw_if_index=self.pg1.sw_if_index,
- is_garp=1, repeat=5, interval=0.1)
+ ret = self.vapi.arping(
+ address=self.pg1.local_ip4,
+ sw_if_index=self.pg1.sw_if_index,
+ is_garp=1,
+ repeat=5,
+ interval=0.1,
+ )
self.logger.info(ret)
- ret = self.vapi.arping(address=self.pg1.local_ip4,
- sw_if_index=self.pg1.sw_if_index,
- is_garp=1)
+ ret = self.vapi.arping(
+ address=self.pg1.local_ip4, sw_if_index=self.pg1.sw_if_index, is_garp=1
+ )
self.logger.info(ret)
out = self.pg1.get_capture(6)
for p in out:
- self.verify_arping_request(p, self.pg1.local_ip4,
- self.pg1.local_ip4)
+ self.verify_arping_request(p, self.pg1.local_ip4, self.pg1.local_ip4)
finally:
self.vapi.cli("show error")
def test_arping_ip6_ns_cli(self):
- """ arping IP6 neighbor solicitation CLI test """
+ """arping IP6 neighbor solicitation CLI test"""
try:
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -172,43 +177,46 @@ class TestArping(VppTestCase):
out = self.pg1.get_capture(6)
for p in out:
- self.verify_arping_ip6_ns(p, self.pg1.local_ip6,
- self.pg1.remote_ip6)
+ self.verify_arping_ip6_ns(p, self.pg1.local_ip6, self.pg1.remote_ip6)
finally:
self.vapi.cli("show error")
def test_arping_ip6_ns_api(self):
- """ arping ip6 neighbor solicitation API test """
+ """arping ip6 neighbor solicitation API test"""
try:
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
remote_ip6 = self.pg1.remote_ip6
- ret = self.vapi.arping(address=remote_ip6,
- sw_if_index=self.pg1.sw_if_index,
- is_garp=0, repeat=5, interval=0.1)
+ ret = self.vapi.arping(
+ address=remote_ip6,
+ sw_if_index=self.pg1.sw_if_index,
+ is_garp=0,
+ repeat=5,
+ interval=0.1,
+ )
self.logger.info(ret)
- ret = self.vapi.arping(address=remote_ip6,
- sw_if_index=self.pg1.sw_if_index,
- is_garp=0)
+ ret = self.vapi.arping(
+ address=remote_ip6, sw_if_index=self.pg1.sw_if_index, is_garp=0
+ )
self.logger.info(ret)
out = self.pg1.get_capture(6)
for p in out:
- self.verify_arping_ip6_ns(p, self.pg1.local_ip6,
- self.pg1.remote_ip6)
+ self.verify_arping_ip6_ns(p, self.pg1.local_ip6, self.pg1.remote_ip6)
finally:
self.vapi.cli("show error")
def test_arping_ip6_na_cli(self):
- """ arping ip6 neighbor advertisement CLI test """
+ """arping ip6 neighbor advertisement CLI test"""
try:
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- ping_cmd = ("arping gratuitous" + self.pg1.local_ip6 +
- "pg1 repeat 5 interval 0.1")
+ ping_cmd = (
+ "arping gratuitous" + self.pg1.local_ip6 + "pg1 repeat 5 interval 0.1"
+ )
ret = self.vapi.cli(ping_cmd)
self.logger.info(ret)
@@ -218,34 +226,36 @@ class TestArping(VppTestCase):
out = self.pg1.get_capture(6)
for p in out:
- self.verify_arping_ip6_na(p, self.pg1.local_ip6,
- self.pg1.local_ip6)
+ self.verify_arping_ip6_na(p, self.pg1.local_ip6, self.pg1.local_ip6)
finally:
self.vapi.cli("show error")
def test_arping_ip6_na_api(self):
- """ arping ip6 neighbor advertisement API test """
+ """arping ip6 neighbor advertisement API test"""
try:
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- ret = self.vapi.arping(address=self.pg1.local_ip6,
- sw_if_index=self.pg1.sw_if_index,
- is_garp=1, repeat=5, interval=0.1)
+ ret = self.vapi.arping(
+ address=self.pg1.local_ip6,
+ sw_if_index=self.pg1.sw_if_index,
+ is_garp=1,
+ repeat=5,
+ interval=0.1,
+ )
self.logger.info(ret)
- ret = self.vapi.arping(address=self.pg1.local_ip6,
- sw_if_index=self.pg1.sw_if_index,
- is_garp=1)
+ ret = self.vapi.arping(
+ address=self.pg1.local_ip6, sw_if_index=self.pg1.sw_if_index, is_garp=1
+ )
self.logger.info(ret)
out = self.pg1.get_capture(6)
for p in out:
- self.verify_arping_ip6_na(p, self.pg1.local_ip6,
- self.pg1.local_ip6)
+ self.verify_arping_ip6_na(p, self.pg1.local_ip6, self.pg1.local_ip6)
finally:
self.vapi.cli("show error")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_bfd.py b/test/test_bfd.py
index d1c7b92d89d..c7ea79abfd0 100644
--- a/test/test_bfd.py
+++ b/test/test_bfd.py
@@ -21,8 +21,15 @@ from scapy.layers.l2 import Ether, GRE
from scapy.packet import Raw
from config import config
-from bfd import VppBFDAuthKey, BFD, BFDAuthType, VppBFDUDPSession, \
- BFDDiagCode, BFDState, BFD_vpp_echo
+from bfd import (
+ VppBFDAuthKey,
+ BFD,
+ BFDAuthType,
+ VppBFDUDPSession,
+ BFDDiagCode,
+ BFDState,
+ BFD_vpp_echo,
+)
from framework import tag_fixme_vpp_workers
from framework import VppTestCase, VppTestRunner
from framework import tag_run_solo
@@ -30,8 +37,7 @@ from util import ppp
from vpp_ip import DpoProto
from vpp_ip_route import VppIpRoute, VppRoutePath
from vpp_lo_interface import VppLoInterface
-from vpp_papi_provider import UnexpectedApiReturnValueError, \
- CliFailedCommandError
+from vpp_papi_provider import UnexpectedApiReturnValueError, CliFailedCommandError
from vpp_pg_interface import CaptureTimeoutError, is_ipv6_misc
from vpp_gre_interface import VppGreInterface
from vpp_papi import VppEnum
@@ -46,15 +52,17 @@ class AuthKeyFactory(object):
self._conf_key_ids = {}
def create_random_key(self, test, auth_type=BFDAuthType.keyed_sha1):
- """ create a random key with unique conf key id """
+ """create a random key with unique conf key id"""
conf_key_id = randint(0, 0xFFFFFFFF)
while conf_key_id in self._conf_key_ids:
conf_key_id = randint(0, 0xFFFFFFFF)
self._conf_key_ids[conf_key_id] = 1
key = scapy.compat.raw(
- bytearray([randint(0, 255) for _ in range(randint(1, 20))]))
- return VppBFDAuthKey(test=test, auth_type=auth_type,
- conf_key_id=conf_key_id, key=key)
+ bytearray([randint(0, 255) for _ in range(randint(1, 20))])
+ )
+ return VppBFDAuthKey(
+ test=test, auth_type=auth_type, conf_key_id=conf_key_id, key=key
+ )
class BFDAPITestCase(VppTestCase):
@@ -87,7 +95,7 @@ class BFDAPITestCase(VppTestCase):
self.factory = AuthKeyFactory()
def test_add_bfd(self):
- """ create a BFD session """
+ """create a BFD session"""
session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
session.add_vpp_config()
self.logger.debug("Session state is %s", session.state)
@@ -97,7 +105,7 @@ class BFDAPITestCase(VppTestCase):
session.remove_vpp_config()
def test_double_add(self):
- """ create the same BFD session twice (negative case) """
+ """create the same BFD session twice (negative case)"""
session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
session.add_vpp_config()
@@ -107,9 +115,8 @@ class BFDAPITestCase(VppTestCase):
session.remove_vpp_config()
def test_add_bfd6(self):
- """ create IPv6 BFD session """
- session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip6, af=AF_INET6)
+ """create IPv6 BFD session"""
+ session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip6, af=AF_INET6)
session.add_vpp_config()
self.logger.debug("Session state is %s", session.state)
session.remove_vpp_config()
@@ -118,65 +125,76 @@ class BFDAPITestCase(VppTestCase):
session.remove_vpp_config()
def test_mod_bfd(self):
- """ modify BFD session parameters """
- session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4,
- desired_min_tx=50000,
- required_min_rx=10000,
- detect_mult=1)
+ """modify BFD session parameters"""
+ session = VppBFDUDPSession(
+ self,
+ self.pg0,
+ self.pg0.remote_ip4,
+ desired_min_tx=50000,
+ required_min_rx=10000,
+ detect_mult=1,
+ )
session.add_vpp_config()
s = session.get_bfd_udp_session_dump_entry()
- self.assert_equal(session.desired_min_tx,
- s.desired_min_tx,
- "desired min transmit interval")
- self.assert_equal(session.required_min_rx,
- s.required_min_rx,
- "required min receive interval")
+ self.assert_equal(
+ session.desired_min_tx, s.desired_min_tx, "desired min transmit interval"
+ )
+ self.assert_equal(
+ session.required_min_rx, s.required_min_rx, "required min receive interval"
+ )
self.assert_equal(session.detect_mult, s.detect_mult, "detect mult")
- session.modify_parameters(desired_min_tx=session.desired_min_tx * 2,
- required_min_rx=session.required_min_rx * 2,
- detect_mult=session.detect_mult * 2)
+ session.modify_parameters(
+ desired_min_tx=session.desired_min_tx * 2,
+ required_min_rx=session.required_min_rx * 2,
+ detect_mult=session.detect_mult * 2,
+ )
s = session.get_bfd_udp_session_dump_entry()
- self.assert_equal(session.desired_min_tx,
- s.desired_min_tx,
- "desired min transmit interval")
- self.assert_equal(session.required_min_rx,
- s.required_min_rx,
- "required min receive interval")
+ self.assert_equal(
+ session.desired_min_tx, s.desired_min_tx, "desired min transmit interval"
+ )
+ self.assert_equal(
+ session.required_min_rx, s.required_min_rx, "required min receive interval"
+ )
self.assert_equal(session.detect_mult, s.detect_mult, "detect mult")
def test_upd_bfd(self):
- """ Create/Modify w/ Update BFD session parameters """
- session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4,
- desired_min_tx=50000,
- required_min_rx=10000,
- detect_mult=1)
+ """Create/Modify w/ Update BFD session parameters"""
+ session = VppBFDUDPSession(
+ self,
+ self.pg0,
+ self.pg0.remote_ip4,
+ desired_min_tx=50000,
+ required_min_rx=10000,
+ detect_mult=1,
+ )
session.upd_vpp_config()
s = session.get_bfd_udp_session_dump_entry()
- self.assert_equal(session.desired_min_tx,
- s.desired_min_tx,
- "desired min transmit interval")
- self.assert_equal(session.required_min_rx,
- s.required_min_rx,
- "required min receive interval")
+ self.assert_equal(
+ session.desired_min_tx, s.desired_min_tx, "desired min transmit interval"
+ )
+ self.assert_equal(
+ session.required_min_rx, s.required_min_rx, "required min receive interval"
+ )
self.assert_equal(session.detect_mult, s.detect_mult, "detect mult")
- session.upd_vpp_config(desired_min_tx=session.desired_min_tx * 2,
- required_min_rx=session.required_min_rx * 2,
- detect_mult=session.detect_mult * 2)
+ session.upd_vpp_config(
+ desired_min_tx=session.desired_min_tx * 2,
+ required_min_rx=session.required_min_rx * 2,
+ detect_mult=session.detect_mult * 2,
+ )
s = session.get_bfd_udp_session_dump_entry()
- self.assert_equal(session.desired_min_tx,
- s.desired_min_tx,
- "desired min transmit interval")
- self.assert_equal(session.required_min_rx,
- s.required_min_rx,
- "required min receive interval")
+ self.assert_equal(
+ session.desired_min_tx, s.desired_min_tx, "desired min transmit interval"
+ )
+ self.assert_equal(
+ session.required_min_rx, s.required_min_rx, "required min receive interval"
+ )
self.assert_equal(session.detect_mult, s.detect_mult, "detect mult")
def test_add_sha1_keys(self):
- """ add SHA1 keys """
+ """add SHA1 keys"""
key_count = 10
- keys = [self.factory.create_random_key(
- self) for i in range(0, key_count)]
+ keys = [self.factory.create_random_key(self) for i in range(0, key_count)]
for key in keys:
self.assertFalse(key.query_vpp_config())
for key in keys:
@@ -211,11 +229,10 @@ class BFDAPITestCase(VppTestCase):
self.assertFalse(key.query_vpp_config())
def test_add_bfd_sha1(self):
- """ create a BFD session (SHA1) """
+ """create a BFD session (SHA1)"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
- session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4,
- sha1_key=key)
+ session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, sha1_key=key)
session.add_vpp_config()
self.logger.debug("Session state is %s", session.state)
session.remove_vpp_config()
@@ -224,51 +241,56 @@ class BFDAPITestCase(VppTestCase):
session.remove_vpp_config()
def test_double_add_sha1(self):
- """ create the same BFD session twice (negative case) (SHA1) """
+ """create the same BFD session twice (negative case) (SHA1)"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
- session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4,
- sha1_key=key)
+ session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, sha1_key=key)
session.add_vpp_config()
with self.assertRaises(Exception):
session.add_vpp_config()
def test_add_auth_nonexistent_key(self):
- """ create BFD session using non-existent SHA1 (negative case) """
+ """create BFD session using non-existent SHA1 (negative case)"""
session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip4,
- sha1_key=self.factory.create_random_key(self))
+ self,
+ self.pg0,
+ self.pg0.remote_ip4,
+ sha1_key=self.factory.create_random_key(self),
+ )
with self.assertRaises(Exception):
session.add_vpp_config()
def test_shared_sha1_key(self):
- """ single SHA1 key shared by multiple BFD sessions """
+ """single SHA1 key shared by multiple BFD sessions"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
sessions = [
- VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4,
- sha1_key=key),
- VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip6,
- sha1_key=key, af=AF_INET6),
- VppBFDUDPSession(self, self.pg1, self.pg1.remote_ip4,
- sha1_key=key),
- VppBFDUDPSession(self, self.pg1, self.pg1.remote_ip6,
- sha1_key=key, af=AF_INET6)]
+ VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, sha1_key=key),
+ VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip6, sha1_key=key, af=AF_INET6
+ ),
+ VppBFDUDPSession(self, self.pg1, self.pg1.remote_ip4, sha1_key=key),
+ VppBFDUDPSession(
+ self, self.pg1, self.pg1.remote_ip6, sha1_key=key, af=AF_INET6
+ ),
+ ]
for s in sessions:
s.add_vpp_config()
removed = 0
for s in sessions:
e = key.get_bfd_auth_keys_dump_entry()
- self.assert_equal(e.use_count, len(sessions) - removed,
- "Use count for shared key")
+ self.assert_equal(
+ e.use_count, len(sessions) - removed, "Use count for shared key"
+ )
s.remove_vpp_config()
removed += 1
e = key.get_bfd_auth_keys_dump_entry()
- self.assert_equal(e.use_count, len(sessions) - removed,
- "Use count for shared key")
+ self.assert_equal(
+ e.use_count, len(sessions) - removed, "Use count for shared key"
+ )
def test_activate_auth(self):
- """ activate SHA1 authentication """
+ """activate SHA1 authentication"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
@@ -276,7 +298,7 @@ class BFDAPITestCase(VppTestCase):
session.activate_auth(key)
def test_deactivate_auth(self):
- """ deactivate SHA1 authentication """
+ """deactivate SHA1 authentication"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
@@ -285,20 +307,19 @@ class BFDAPITestCase(VppTestCase):
session.deactivate_auth()
def test_change_key(self):
- """ change SHA1 key """
+ """change SHA1 key"""
key1 = self.factory.create_random_key(self)
key2 = self.factory.create_random_key(self)
while key2.conf_key_id == key1.conf_key_id:
key2 = self.factory.create_random_key(self)
key1.add_vpp_config()
key2.add_vpp_config()
- session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4,
- sha1_key=key1)
+ session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4, sha1_key=key1)
session.add_vpp_config()
session.activate_auth(key2)
def test_set_del_udp_echo_source(self):
- """ set/del udp echo source """
+ """set/del udp echo source"""
self.create_loopback_interfaces(1)
self.loopback0 = self.lo_interfaces[0]
self.loopback0.admin_up()
@@ -307,8 +328,7 @@ class BFDAPITestCase(VppTestCase):
self.assertFalse(echo_source.have_usable_ip4)
self.assertFalse(echo_source.have_usable_ip6)
- self.vapi.bfd_udp_set_echo_source(
- sw_if_index=self.loopback0.sw_if_index)
+ self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index)
echo_source = self.vapi.bfd_udp_get_echo_source()
self.assertTrue(echo_source.is_set)
self.assertEqual(echo_source.sw_if_index, self.loopback0.sw_if_index)
@@ -316,8 +336,9 @@ class BFDAPITestCase(VppTestCase):
self.assertFalse(echo_source.have_usable_ip6)
self.loopback0.config_ip4()
- echo_ip4 = ipaddress.IPv4Address(int(ipaddress.IPv4Address(
- self.loopback0.local_ip4)) ^ 1).packed
+ echo_ip4 = ipaddress.IPv4Address(
+ int(ipaddress.IPv4Address(self.loopback0.local_ip4)) ^ 1
+ ).packed
echo_source = self.vapi.bfd_udp_get_echo_source()
self.assertTrue(echo_source.is_set)
self.assertEqual(echo_source.sw_if_index, self.loopback0.sw_if_index)
@@ -326,8 +347,9 @@ class BFDAPITestCase(VppTestCase):
self.assertFalse(echo_source.have_usable_ip6)
self.loopback0.config_ip6()
- echo_ip6 = ipaddress.IPv6Address(int(ipaddress.IPv6Address(
- self.loopback0.local_ip6)) ^ 1).packed
+ echo_ip6 = ipaddress.IPv6Address(
+ int(ipaddress.IPv6Address(self.loopback0.local_ip6)) ^ 1
+ ).packed
echo_source = self.vapi.bfd_udp_get_echo_source()
self.assertTrue(echo_source.is_set)
@@ -345,11 +367,20 @@ class BFDAPITestCase(VppTestCase):
class BFDTestSession(object):
- """ BFD session as seen from test framework side """
-
- def __init__(self, test, interface, af, detect_mult=3, sha1_key=None,
- bfd_key_id=None, our_seq_number=None,
- tunnel_header=None, phy_interface=None):
+ """BFD session as seen from test framework side"""
+
+ def __init__(
+ self,
+ test,
+ interface,
+ af,
+ detect_mult=3,
+ sha1_key=None,
+ bfd_key_id=None,
+ our_seq_number=None,
+ tunnel_header=None,
+ phy_interface=None,
+ ):
self.test = test
self.af = af
self.sha1_key = sha1_key
@@ -381,17 +412,25 @@ class BFDTestSession(object):
self.rx_packets_echo = 0
def inc_seq_num(self):
- """ increment sequence number, wrapping if needed """
+ """increment sequence number, wrapping if needed"""
if self.our_seq_number == 0xFFFFFFFF:
self.our_seq_number = 0
else:
self.our_seq_number += 1
- def update(self, my_discriminator=None, your_discriminator=None,
- desired_min_tx=None, required_min_rx=None,
- required_min_echo_rx=None, detect_mult=None,
- diag=None, state=None, auth_type=None):
- """ update BFD parameters associated with session """
+ def update(
+ self,
+ my_discriminator=None,
+ your_discriminator=None,
+ desired_min_tx=None,
+ required_min_rx=None,
+ required_min_echo_rx=None,
+ detect_mult=None,
+ diag=None,
+ state=None,
+ auth_type=None,
+ ):
+ """update BFD parameters associated with session"""
if my_discriminator is not None:
self.my_discriminator = my_discriminator
if your_discriminator is not None:
@@ -412,34 +451,37 @@ class BFDTestSession(object):
self.auth_type = auth_type
def fill_packet_fields(self, packet):
- """ set packet fields with known values in packet """
+ """set packet fields with known values in packet"""
bfd = packet[BFD]
if self.my_discriminator:
- self.test.logger.debug("BFD: setting packet.my_discriminator=%s",
- self.my_discriminator)
+ self.test.logger.debug(
+ "BFD: setting packet.my_discriminator=%s", self.my_discriminator
+ )
bfd.my_discriminator = self.my_discriminator
if self.your_discriminator:
- self.test.logger.debug("BFD: setting packet.your_discriminator=%s",
- self.your_discriminator)
+ self.test.logger.debug(
+ "BFD: setting packet.your_discriminator=%s", self.your_discriminator
+ )
bfd.your_discriminator = self.your_discriminator
if self.required_min_rx:
self.test.logger.debug(
- "BFD: setting packet.required_min_rx_interval=%s",
- self.required_min_rx)
+ "BFD: setting packet.required_min_rx_interval=%s", self.required_min_rx
+ )
bfd.required_min_rx_interval = self.required_min_rx
if self.required_min_echo_rx:
self.test.logger.debug(
- "BFD: setting packet.required_min_echo_rx=%s",
- self.required_min_echo_rx)
+ "BFD: setting packet.required_min_echo_rx=%s", self.required_min_echo_rx
+ )
bfd.required_min_echo_rx_interval = self.required_min_echo_rx
if self.desired_min_tx:
self.test.logger.debug(
- "BFD: setting packet.desired_min_tx_interval=%s",
- self.desired_min_tx)
+ "BFD: setting packet.desired_min_tx_interval=%s", self.desired_min_tx
+ )
bfd.desired_min_tx_interval = self.desired_min_tx
if self.detect_mult:
self.test.logger.debug(
- "BFD: setting packet.detect_mult=%s", self.detect_mult)
+ "BFD: setting packet.detect_mult=%s", self.detect_mult
+ )
bfd.detect_mult = self.detect_mult
if self.diag:
self.test.logger.debug("BFD: setting packet.diag=%s", self.diag)
@@ -449,12 +491,11 @@ class BFDTestSession(object):
bfd.state = self.state
if self.auth_type:
# this is used by a negative test-case
- self.test.logger.debug("BFD: setting packet.auth_type=%s",
- self.auth_type)
+ self.test.logger.debug("BFD: setting packet.auth_type=%s", self.auth_type)
bfd.auth_type = self.auth_type
def create_packet(self):
- """ create a BFD packet, reflecting the current state of session """
+ """create a BFD packet, reflecting the current state of session"""
if self.sha1_key:
bfd = BFD(flags="A")
bfd.auth_type = self.sha1_key.auth_type
@@ -464,37 +505,48 @@ class BFDTestSession(object):
bfd.length = BFD.sha1_auth_len + BFD.bfd_pkt_len
else:
bfd = BFD()
- packet = Ether(src=self.phy_interface.remote_mac,
- dst=self.phy_interface.local_mac)
+ packet = Ether(
+ src=self.phy_interface.remote_mac, dst=self.phy_interface.local_mac
+ )
if self.tunnel_header:
packet = packet / self.tunnel_header
if self.af == AF_INET6:
- packet = (packet /
- IPv6(src=self.interface.remote_ip6,
- dst=self.interface.local_ip6,
- hlim=255) /
- UDP(sport=self.udp_sport, dport=BFD.udp_dport) /
- bfd)
+ packet = (
+ packet
+ / IPv6(
+ src=self.interface.remote_ip6,
+ dst=self.interface.local_ip6,
+ hlim=255,
+ )
+ / UDP(sport=self.udp_sport, dport=BFD.udp_dport)
+ / bfd
+ )
else:
- packet = (packet /
- IP(src=self.interface.remote_ip4,
- dst=self.interface.local_ip4,
- ttl=255) /
- UDP(sport=self.udp_sport, dport=BFD.udp_dport) /
- bfd)
+ packet = (
+ packet
+ / IP(
+ src=self.interface.remote_ip4, dst=self.interface.local_ip4, ttl=255
+ )
+ / UDP(sport=self.udp_sport, dport=BFD.udp_dport)
+ / bfd
+ )
self.test.logger.debug("BFD: Creating packet")
self.fill_packet_fields(packet)
if self.sha1_key:
- hash_material = scapy.compat.raw(
- packet[BFD])[:32] + self.sha1_key.key + \
- b"\0" * (20 - len(self.sha1_key.key))
- self.test.logger.debug("BFD: Calculated SHA1 hash: %s" %
- hashlib.sha1(hash_material).hexdigest())
+ hash_material = (
+ scapy.compat.raw(packet[BFD])[:32]
+ + self.sha1_key.key
+ + b"\0" * (20 - len(self.sha1_key.key))
+ )
+ self.test.logger.debug(
+ "BFD: Calculated SHA1 hash: %s"
+ % hashlib.sha1(hash_material).hexdigest()
+ )
packet[BFD].auth_key_hash = hashlib.sha1(hash_material).digest()
return packet
def send_packet(self, packet=None, interface=None):
- """ send packet on interface, creating the packet if needed """
+ """send packet on interface, creating the packet if needed"""
if packet is None:
packet = self.create_packet()
if interface is None:
@@ -505,82 +557,95 @@ class BFDTestSession(object):
self.test.pg_start()
def verify_sha1_auth(self, packet):
- """ Verify correctness of authentication in BFD layer. """
+ """Verify correctness of authentication in BFD layer."""
bfd = packet[BFD]
self.test.assert_equal(bfd.auth_len, 28, "Auth section length")
- self.test.assert_equal(bfd.auth_type, self.sha1_key.auth_type,
- BFDAuthType)
+ self.test.assert_equal(bfd.auth_type, self.sha1_key.auth_type, BFDAuthType)
self.test.assert_equal(bfd.auth_key_id, self.bfd_key_id, "Key ID")
self.test.assert_equal(bfd.auth_reserved, 0, "Reserved")
if self.vpp_seq_number is None:
self.vpp_seq_number = bfd.auth_seq_num
- self.test.logger.debug("Received initial sequence number: %s" %
- self.vpp_seq_number)
+ self.test.logger.debug(
+ "Received initial sequence number: %s" % self.vpp_seq_number
+ )
else:
recvd_seq_num = bfd.auth_seq_num
- self.test.logger.debug("Received followup sequence number: %s" %
- recvd_seq_num)
- if self.vpp_seq_number < 0xffffffff:
- if self.sha1_key.auth_type == \
- BFDAuthType.meticulous_keyed_sha1:
- self.test.assert_equal(recvd_seq_num,
- self.vpp_seq_number + 1,
- "BFD sequence number")
+ self.test.logger.debug(
+ "Received followup sequence number: %s" % recvd_seq_num
+ )
+ if self.vpp_seq_number < 0xFFFFFFFF:
+ if self.sha1_key.auth_type == BFDAuthType.meticulous_keyed_sha1:
+ self.test.assert_equal(
+ recvd_seq_num, self.vpp_seq_number + 1, "BFD sequence number"
+ )
else:
- self.test.assert_in_range(recvd_seq_num,
- self.vpp_seq_number,
- self.vpp_seq_number + 1,
- "BFD sequence number")
+ self.test.assert_in_range(
+ recvd_seq_num,
+ self.vpp_seq_number,
+ self.vpp_seq_number + 1,
+ "BFD sequence number",
+ )
else:
- if self.sha1_key.auth_type == \
- BFDAuthType.meticulous_keyed_sha1:
- self.test.assert_equal(recvd_seq_num, 0,
- "BFD sequence number")
+ if self.sha1_key.auth_type == BFDAuthType.meticulous_keyed_sha1:
+ self.test.assert_equal(recvd_seq_num, 0, "BFD sequence number")
else:
- self.test.assertIn(recvd_seq_num, (self.vpp_seq_number, 0),
- "BFD sequence number not one of "
- "(%s, 0)" % self.vpp_seq_number)
+ self.test.assertIn(
+ recvd_seq_num,
+ (self.vpp_seq_number, 0),
+ "BFD sequence number not one of "
+ "(%s, 0)" % self.vpp_seq_number,
+ )
self.vpp_seq_number = recvd_seq_num
# last 20 bytes represent the hash - so replace them with the key,
# pad the result with zeros and hash the result
- hash_material = bfd.original[:-20] + self.sha1_key.key + \
- b"\0" * (20 - len(self.sha1_key.key))
+ hash_material = (
+ bfd.original[:-20]
+ + self.sha1_key.key
+ + b"\0" * (20 - len(self.sha1_key.key))
+ )
expected_hash = hashlib.sha1(hash_material).hexdigest()
- self.test.assert_equal(binascii.hexlify(bfd.auth_key_hash),
- expected_hash.encode(), "Auth key hash")
+ self.test.assert_equal(
+ binascii.hexlify(bfd.auth_key_hash), expected_hash.encode(), "Auth key hash"
+ )
def verify_bfd(self, packet):
- """ Verify correctness of BFD layer. """
+ """Verify correctness of BFD layer."""
bfd = packet[BFD]
self.test.assert_equal(bfd.version, 1, "BFD version")
- self.test.assert_equal(bfd.your_discriminator,
- self.my_discriminator,
- "BFD - your discriminator")
+ self.test.assert_equal(
+ bfd.your_discriminator, self.my_discriminator, "BFD - your discriminator"
+ )
if self.sha1_key:
self.verify_sha1_auth(packet)
def bfd_session_up(test):
- """ Bring BFD session up """
+ """Bring BFD session up"""
test.logger.info("BFD: Waiting for slow hello")
p = wait_for_bfd_packet(test, 2, is_tunnel=test.vpp_session.is_tunnel)
old_offset = None
- if hasattr(test, 'vpp_clock_offset'):
+ if hasattr(test, "vpp_clock_offset"):
old_offset = test.vpp_clock_offset
test.vpp_clock_offset = time.time() - float(p.time)
- test.logger.debug("BFD: Calculated vpp clock offset: %s",
- test.vpp_clock_offset)
+ test.logger.debug("BFD: Calculated vpp clock offset: %s", test.vpp_clock_offset)
if old_offset:
test.assertAlmostEqual(
- old_offset, test.vpp_clock_offset, delta=0.5,
- msg="vpp clock offset not stable (new: %s, old: %s)" %
- (test.vpp_clock_offset, old_offset))
+ old_offset,
+ test.vpp_clock_offset,
+ delta=0.5,
+ msg="vpp clock offset not stable (new: %s, old: %s)"
+ % (test.vpp_clock_offset, old_offset),
+ )
test.logger.info("BFD: Sending Init")
- test.test_session.update(my_discriminator=randint(0, 40000000),
- your_discriminator=p[BFD].my_discriminator,
- state=BFDState.init)
- if test.test_session.sha1_key and test.test_session.sha1_key.auth_type == \
- BFDAuthType.meticulous_keyed_sha1:
+ test.test_session.update(
+ my_discriminator=randint(0, 40000000),
+ your_discriminator=p[BFD].my_discriminator,
+ state=BFDState.init,
+ )
+ if (
+ test.test_session.sha1_key
+ and test.test_session.sha1_key.auth_type == BFDAuthType.meticulous_keyed_sha1
+ ):
test.test_session.inc_seq_num()
test.test_session.send_packet()
test.logger.info("BFD: Waiting for event")
@@ -588,19 +653,23 @@ def bfd_session_up(test):
verify_event(test, e, expected_state=BFDState.up)
test.logger.info("BFD: Session is Up")
test.test_session.update(state=BFDState.up)
- if test.test_session.sha1_key and test.test_session.sha1_key.auth_type == \
- BFDAuthType.meticulous_keyed_sha1:
+ if (
+ test.test_session.sha1_key
+ and test.test_session.sha1_key.auth_type == BFDAuthType.meticulous_keyed_sha1
+ ):
test.test_session.inc_seq_num()
test.test_session.send_packet()
test.assert_equal(test.vpp_session.state, BFDState.up, BFDState)
def bfd_session_down(test):
- """ Bring BFD session down """
+ """Bring BFD session down"""
test.assert_equal(test.vpp_session.state, BFDState.up, BFDState)
test.test_session.update(state=BFDState.down)
- if test.test_session.sha1_key and test.test_session.sha1_key.auth_type == \
- BFDAuthType.meticulous_keyed_sha1:
+ if (
+ test.test_session.sha1_key
+ and test.test_session.sha1_key.auth_type == BFDAuthType.meticulous_keyed_sha1
+ ):
test.test_session.inc_seq_num()
test.test_session.send_packet()
test.logger.info("BFD: Waiting for event")
@@ -617,25 +686,25 @@ def verify_bfd_session_config(test, session, state=None):
# are valid (in get_bfd_udp_session_dump_entry)
if state:
test.assert_equal(dump.state, state, "session state")
- test.assert_equal(dump.required_min_rx, session.required_min_rx,
- "required min rx interval")
- test.assert_equal(dump.desired_min_tx, session.desired_min_tx,
- "desired min tx interval")
- test.assert_equal(dump.detect_mult, session.detect_mult,
- "detect multiplier")
+ test.assert_equal(
+ dump.required_min_rx, session.required_min_rx, "required min rx interval"
+ )
+ test.assert_equal(
+ dump.desired_min_tx, session.desired_min_tx, "desired min tx interval"
+ )
+ test.assert_equal(dump.detect_mult, session.detect_mult, "detect multiplier")
if session.sha1_key is None:
test.assert_equal(dump.is_authenticated, 0, "is_authenticated flag")
else:
test.assert_equal(dump.is_authenticated, 1, "is_authenticated flag")
- test.assert_equal(dump.bfd_key_id, session.bfd_key_id,
- "bfd key id")
- test.assert_equal(dump.conf_key_id,
- session.sha1_key.conf_key_id,
- "config key id")
+ test.assert_equal(dump.bfd_key_id, session.bfd_key_id, "bfd key id")
+ test.assert_equal(
+ dump.conf_key_id, session.sha1_key.conf_key_id, "config key id"
+ )
def verify_ip(test, packet):
- """ Verify correctness of IP layer. """
+ """Verify correctness of IP layer."""
if test.vpp_session.af == AF_INET6:
ip = packet[IPv6]
local_ip = test.vpp_session.interface.local_ip6
@@ -651,30 +720,31 @@ def verify_ip(test, packet):
def verify_udp(test, packet):
- """ Verify correctness of UDP layer. """
+ """Verify correctness of UDP layer."""
udp = packet[UDP]
test.assert_equal(udp.dport, BFD.udp_dport, "UDP destination port")
- test.assert_in_range(udp.sport, BFD.udp_sport_min, BFD.udp_sport_max,
- "UDP source port")
+ test.assert_in_range(
+ udp.sport, BFD.udp_sport_min, BFD.udp_sport_max, "UDP source port"
+ )
def verify_event(test, event, expected_state):
- """ Verify correctness of event values. """
+ """Verify correctness of event values."""
e = event
test.logger.debug("BFD: Event: %s" % reprlib.repr(e))
- test.assert_equal(e.sw_if_index,
- test.vpp_session.interface.sw_if_index,
- "BFD interface index")
-
- test.assert_equal(str(e.local_addr), test.vpp_session.local_addr,
- "Local IPv6 address")
- test.assert_equal(str(e.peer_addr), test.vpp_session.peer_addr,
- "Peer IPv6 address")
+ test.assert_equal(
+ e.sw_if_index, test.vpp_session.interface.sw_if_index, "BFD interface index"
+ )
+
+ test.assert_equal(
+ str(e.local_addr), test.vpp_session.local_addr, "Local IPv6 address"
+ )
+ test.assert_equal(str(e.peer_addr), test.vpp_session.peer_addr, "Peer IPv6 address")
test.assert_equal(e.state, expected_state, BFDState)
def wait_for_bfd_packet(test, timeout=1, pcap_time_min=None, is_tunnel=False):
- """ wait for BFD packet and verify its correctness
+ """wait for BFD packet and verify its correctness
:param timeout: how long to wait
:param pcap_time_min: ignore packets with pcap timestamp lower than this
@@ -695,9 +765,13 @@ def wait_for_bfd_packet(test, timeout=1, pcap_time_min=None, is_tunnel=False):
test.test_session.rx_packets += 1
test.logger.debug(ppp("BFD: Got packet:", p))
if pcap_time_min is not None and p.time < pcap_time_min:
- test.logger.debug(ppp("BFD: ignoring packet (pcap time %s < "
- "pcap time min %s):" %
- (p.time, pcap_time_min), p))
+ test.logger.debug(
+ ppp(
+ "BFD: ignoring packet (pcap time %s < "
+ "pcap time min %s):" % (p.time, pcap_time_min),
+ p,
+ )
+ )
else:
break
if is_tunnel:
@@ -722,15 +796,15 @@ def bfd_grab_stats_snapshot(test, bs_idx=0, thread_index=None):
s = test.statistics
ti = thread_index
if ti is None:
- rx = s['/bfd/rx-session-counters'][:, bs_idx].sum_packets()
- rx_echo = s['/bfd/rx-session-echo-counters'][:, bs_idx].sum_packets()
- tx = s['/bfd/tx-session-counters'][:, bs_idx].sum_packets()
- tx_echo = s['/bfd/tx-session-echo-counters'][:, bs_idx].sum_packets()
+ rx = s["/bfd/rx-session-counters"][:, bs_idx].sum_packets()
+ rx_echo = s["/bfd/rx-session-echo-counters"][:, bs_idx].sum_packets()
+ tx = s["/bfd/tx-session-counters"][:, bs_idx].sum_packets()
+ tx_echo = s["/bfd/tx-session-echo-counters"][:, bs_idx].sum_packets()
else:
- rx = s['/bfd/rx-session-counters'][ti, bs_idx].sum_packets()
- rx_echo = s['/bfd/rx-session-echo-counters'][ti, bs_idx].sum_packets()
- tx = s['/bfd/tx-session-counters'][ti, bs_idx].sum_packets()
- tx_echo = s['/bfd/tx-session-echo-counters'][ti, bs_idx].sum_packets()
+ rx = s["/bfd/rx-session-counters"][ti, bs_idx].sum_packets()
+ rx_echo = s["/bfd/rx-session-echo-counters"][ti, bs_idx].sum_packets()
+ tx = s["/bfd/tx-session-counters"][ti, bs_idx].sum_packets()
+ tx_echo = s["/bfd/tx-session-echo-counters"][ti, bs_idx].sum_packets()
return BFDStats(rx, rx_echo, tx, tx_echo)
@@ -780,10 +854,9 @@ class BFD4TestCase(VppTestCase):
self.vapi.want_bfd_events()
self.pg0.enable_capture()
try:
- self.bfd_udp4_sessions = self.statistics['/bfd/udp4/sessions']
- self.bfd_udp6_sessions = self.statistics['/bfd/udp6/sessions']
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4)
+ self.bfd_udp4_sessions = self.statistics["/bfd/udp4/sessions"]
+ self.bfd_udp6_sessions = self.statistics["/bfd/udp6/sessions"]
+ self.vpp_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
self.vpp_session.add_vpp_config()
self.vpp_session.admin_up()
self.test_session = BFDTestSession(self, self.pg0, AF_INET)
@@ -798,26 +871,29 @@ class BFD4TestCase(VppTestCase):
super(BFD4TestCase, self).tearDown()
def test_session_up(self):
- """ bring BFD session up """
+ """bring BFD session up"""
bfd_session_up(self)
- bfd_udp4_sessions = self.statistics['/bfd/udp4/sessions']
- bfd_udp6_sessions = self.statistics['/bfd/udp6/sessions']
+ bfd_udp4_sessions = self.statistics["/bfd/udp4/sessions"]
+ bfd_udp6_sessions = self.statistics["/bfd/udp6/sessions"]
self.assert_equal(bfd_udp4_sessions - self.bfd_udp4_sessions, 1)
self.assert_equal(bfd_udp6_sessions, self.bfd_udp6_sessions)
def test_session_up_by_ip(self):
- """ bring BFD session up - first frame looked up by address pair """
+ """bring BFD session up - first frame looked up by address pair"""
self.logger.info("BFD: Sending Slow control frame")
self.test_session.update(my_discriminator=randint(0, 40000000))
self.test_session.send_packet()
self.pg0.enable_capture()
p = self.pg0.wait_for_packet(1)
- self.assert_equal(p[BFD].your_discriminator,
- self.test_session.my_discriminator,
- "BFD - your discriminator")
+ self.assert_equal(
+ p[BFD].your_discriminator,
+ self.test_session.my_discriminator,
+ "BFD - your discriminator",
+ )
self.assert_equal(p[BFD].state, BFDState.init, BFDState)
- self.test_session.update(your_discriminator=p[BFD].my_discriminator,
- state=BFDState.up)
+ self.test_session.update(
+ your_discriminator=p[BFD].my_discriminator, state=BFDState.up
+ )
self.logger.info("BFD: Waiting for event")
e = self.vapi.wait_for_event(1, "bfd_udp_session_event")
verify_event(self, e, expected_state=BFDState.init)
@@ -832,21 +908,20 @@ class BFD4TestCase(VppTestCase):
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
def test_session_down(self):
- """ bring BFD session down """
+ """bring BFD session down"""
bfd_session_up(self)
bfd_session_down(self)
def test_hold_up(self):
- """ hold BFD session up """
+ """hold BFD session up"""
bfd_session_up(self)
for dummy in range(self.test_session.detect_mult * 2):
wait_for_bfd_packet(self)
self.test_session.send_packet()
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events")
def test_slow_timer(self):
- """ verify slow periodic control frames while session down """
+ """verify slow periodic control frames while session down"""
packet_count = 3
self.logger.info("BFD: Waiting for %d BFD packets", packet_count)
prev_packet = wait_for_bfd_packet(self, 2)
@@ -855,55 +930,60 @@ class BFD4TestCase(VppTestCase):
time_diff = next_packet.time - prev_packet.time
# spec says the range should be <0.75, 1>, allow extra 0.05 margin
# to work around timing issues
- self.assert_in_range(
- time_diff, 0.70, 1.05, "time between slow packets")
+ self.assert_in_range(time_diff, 0.70, 1.05, "time between slow packets")
prev_packet = next_packet
def test_zero_remote_min_rx(self):
- """ no packets when zero remote required min rx interval """
+ """no packets when zero remote required min rx interval"""
bfd_session_up(self)
self.test_session.update(required_min_rx=0)
self.test_session.send_packet()
for dummy in range(self.test_session.detect_mult):
- self.sleep(self.vpp_session.required_min_rx / USEC_IN_SEC,
- "sleep before transmitting bfd packet")
+ self.sleep(
+ self.vpp_session.required_min_rx / USEC_IN_SEC,
+ "sleep before transmitting bfd packet",
+ )
self.test_session.send_packet()
try:
p = wait_for_bfd_packet(self, timeout=0)
self.logger.error(ppp("Received unexpected packet:", p))
except CaptureTimeoutError:
pass
- self.assert_equal(
- len(self.vapi.collect_events()), 0, "number of bfd events")
+ self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events")
self.test_session.update(required_min_rx=300000)
for dummy in range(3):
self.test_session.send_packet()
wait_for_bfd_packet(
- self, timeout=self.test_session.required_min_rx / USEC_IN_SEC)
- self.assert_equal(
- len(self.vapi.collect_events()), 0, "number of bfd events")
+ self, timeout=self.test_session.required_min_rx / USEC_IN_SEC
+ )
+ self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events")
def test_conn_down(self):
- """ verify session goes down after inactivity """
+ """verify session goes down after inactivity"""
bfd_session_up(self)
- detection_time = self.test_session.detect_mult *\
- self.vpp_session.required_min_rx / USEC_IN_SEC
+ detection_time = (
+ self.test_session.detect_mult
+ * self.vpp_session.required_min_rx
+ / USEC_IN_SEC
+ )
self.sleep(detection_time, "waiting for BFD session time-out")
e = self.vapi.wait_for_event(1, "bfd_udp_session_event")
verify_event(self, e, expected_state=BFDState.down)
def test_peer_discr_reset_sess_down(self):
- """ peer discriminator reset after session goes down """
+ """peer discriminator reset after session goes down"""
bfd_session_up(self)
- detection_time = self.test_session.detect_mult *\
- self.vpp_session.required_min_rx / USEC_IN_SEC
+ detection_time = (
+ self.test_session.detect_mult
+ * self.vpp_session.required_min_rx
+ / USEC_IN_SEC
+ )
self.sleep(detection_time, "waiting for BFD session time-out")
self.test_session.my_discriminator = 0
- wait_for_bfd_packet(self,
- pcap_time_min=time.time() - self.vpp_clock_offset)
+ wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
def test_large_required_min_rx(self):
- """ large remote required min rx interval """
+ """large remote required min rx interval"""
bfd_session_up(self)
p = wait_for_bfd_packet(self)
interval = 3000000
@@ -932,14 +1012,14 @@ class BFD4TestCase(VppTestCase):
self.assert_equal(count, 0, "number of packets received")
def test_immediate_remote_min_rx_reduction(self):
- """ immediately honor remote required min rx reduction """
+ """immediately honor remote required min rx reduction"""
self.vpp_session.remove_vpp_config()
self.vpp_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip4, desired_min_tx=10000)
+ self, self.pg0, self.pg0.remote_ip4, desired_min_tx=10000
+ )
self.pg0.enable_capture()
self.vpp_session.add_vpp_config()
- self.test_session.update(desired_min_tx=1000000,
- required_min_rx=1000000)
+ self.test_session.update(desired_min_tx=1000000, required_min_rx=1000000)
bfd_session_up(self)
reference_packet = wait_for_bfd_packet(self)
time_mark = time.time()
@@ -950,131 +1030,143 @@ class BFD4TestCase(VppTestCase):
p = wait_for_bfd_packet(self)
# first packet is allowed to be late by time we spent doing the update
# calculated in extra_time
- self.assert_in_range(p.time - reference_packet.time,
- .95 * 0.75 * interval / USEC_IN_SEC,
- 1.05 * interval / USEC_IN_SEC + extra_time,
- "time between BFD packets")
+ self.assert_in_range(
+ p.time - reference_packet.time,
+ 0.95 * 0.75 * interval / USEC_IN_SEC,
+ 1.05 * interval / USEC_IN_SEC + extra_time,
+ "time between BFD packets",
+ )
reference_packet = p
for dummy in range(3):
p = wait_for_bfd_packet(self)
diff = p.time - reference_packet.time
- self.assert_in_range(diff, .95 * .75 * interval / USEC_IN_SEC,
- 1.05 * interval / USEC_IN_SEC,
- "time between BFD packets")
+ self.assert_in_range(
+ diff,
+ 0.95 * 0.75 * interval / USEC_IN_SEC,
+ 1.05 * interval / USEC_IN_SEC,
+ "time between BFD packets",
+ )
reference_packet = p
def test_modify_req_min_rx_double(self):
- """ modify session - double required min rx """
+ """modify session - double required min rx"""
bfd_session_up(self)
p = wait_for_bfd_packet(self)
- self.test_session.update(desired_min_tx=10000,
- required_min_rx=10000)
+ self.test_session.update(desired_min_tx=10000, required_min_rx=10000)
self.test_session.send_packet()
# double required min rx
self.vpp_session.modify_parameters(
- required_min_rx=2 * self.vpp_session.required_min_rx)
- p = wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ required_min_rx=2 * self.vpp_session.required_min_rx
+ )
+ p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
# poll bit needs to be set
- self.assertIn("P", p.sprintf("%BFD.flags%"),
- "Poll bit not set in BFD packet")
+ self.assertIn("P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet")
# finish poll sequence with final packet
final = self.test_session.create_packet()
final[BFD].flags = "F"
- timeout = self.test_session.detect_mult * \
- max(self.test_session.desired_min_tx,
- self.vpp_session.required_min_rx) / USEC_IN_SEC
+ timeout = (
+ self.test_session.detect_mult
+ * max(self.test_session.desired_min_tx, self.vpp_session.required_min_rx)
+ / USEC_IN_SEC
+ )
self.test_session.send_packet(final)
time_mark = time.time()
e = self.vapi.wait_for_event(2 * timeout, "bfd_udp_session_event")
verify_event(self, e, expected_state=BFDState.down)
time_to_event = time.time() - time_mark
- self.assert_in_range(time_to_event, .9 * timeout,
- 1.1 * timeout, "session timeout")
+ self.assert_in_range(
+ time_to_event, 0.9 * timeout, 1.1 * timeout, "session timeout"
+ )
def test_modify_req_min_rx_halve(self):
- """ modify session - halve required min rx """
+ """modify session - halve required min rx"""
self.vpp_session.modify_parameters(
- required_min_rx=2 * self.vpp_session.required_min_rx)
+ required_min_rx=2 * self.vpp_session.required_min_rx
+ )
bfd_session_up(self)
p = wait_for_bfd_packet(self)
- self.test_session.update(desired_min_tx=10000,
- required_min_rx=10000)
+ self.test_session.update(desired_min_tx=10000, required_min_rx=10000)
self.test_session.send_packet()
- p = wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
# halve required min rx
old_required_min_rx = self.vpp_session.required_min_rx
self.vpp_session.modify_parameters(
- required_min_rx=self.vpp_session.required_min_rx // 2)
+ required_min_rx=self.vpp_session.required_min_rx // 2
+ )
# now we wait 0.8*3*old-req-min-rx and the session should still be up
- self.sleep(0.8 * self.vpp_session.detect_mult *
- old_required_min_rx / USEC_IN_SEC,
- "wait before finishing poll sequence")
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.sleep(
+ 0.8 * self.vpp_session.detect_mult * old_required_min_rx / USEC_IN_SEC,
+ "wait before finishing poll sequence",
+ )
+ self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events")
p = wait_for_bfd_packet(self)
# poll bit needs to be set
- self.assertIn("P", p.sprintf("%BFD.flags%"),
- "Poll bit not set in BFD packet")
+ self.assertIn("P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet")
# finish poll sequence with final packet
final = self.test_session.create_packet()
final[BFD].flags = "F"
self.test_session.send_packet(final)
# now the session should time out under new conditions
- detection_time = self.test_session.detect_mult *\
- self.vpp_session.required_min_rx / USEC_IN_SEC
+ detection_time = (
+ self.test_session.detect_mult
+ * self.vpp_session.required_min_rx
+ / USEC_IN_SEC
+ )
before = time.time()
- e = self.vapi.wait_for_event(
- 2 * detection_time, "bfd_udp_session_event")
+ e = self.vapi.wait_for_event(2 * detection_time, "bfd_udp_session_event")
after = time.time()
- self.assert_in_range(after - before,
- 0.9 * detection_time,
- 1.1 * detection_time,
- "time before bfd session goes down")
+ self.assert_in_range(
+ after - before,
+ 0.9 * detection_time,
+ 1.1 * detection_time,
+ "time before bfd session goes down",
+ )
verify_event(self, e, expected_state=BFDState.down)
def test_modify_detect_mult(self):
- """ modify detect multiplier """
+ """modify detect multiplier"""
bfd_session_up(self)
p = wait_for_bfd_packet(self)
self.vpp_session.modify_parameters(detect_mult=1)
- p = wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
- self.assert_equal(self.vpp_session.detect_mult,
- p[BFD].detect_mult,
- "detect mult")
+ p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ self.assert_equal(
+ self.vpp_session.detect_mult, p[BFD].detect_mult, "detect mult"
+ )
# poll bit must not be set
- self.assertNotIn("P", p.sprintf("%BFD.flags%"),
- "Poll bit not set in BFD packet")
+ self.assertNotIn(
+ "P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet"
+ )
self.vpp_session.modify_parameters(detect_mult=10)
- p = wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
- self.assert_equal(self.vpp_session.detect_mult,
- p[BFD].detect_mult,
- "detect mult")
+ p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ self.assert_equal(
+ self.vpp_session.detect_mult, p[BFD].detect_mult, "detect mult"
+ )
# poll bit must not be set
- self.assertNotIn("P", p.sprintf("%BFD.flags%"),
- "Poll bit not set in BFD packet")
+ self.assertNotIn(
+ "P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet"
+ )
def test_queued_poll(self):
- """ test poll sequence queueing """
+ """test poll sequence queueing"""
bfd_session_up(self)
p = wait_for_bfd_packet(self)
self.vpp_session.modify_parameters(
- required_min_rx=2 * self.vpp_session.required_min_rx)
+ required_min_rx=2 * self.vpp_session.required_min_rx
+ )
p = wait_for_bfd_packet(self)
poll_sequence_start = time.time()
poll_sequence_length_min = 0.5
send_final_after = time.time() + poll_sequence_length_min
# poll bit needs to be set
- self.assertIn("P", p.sprintf("%BFD.flags%"),
- "Poll bit not set in BFD packet")
- self.assert_equal(p[BFD].required_min_rx_interval,
- self.vpp_session.required_min_rx,
- "BFD required min rx interval")
+ self.assertIn("P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet")
+ self.assert_equal(
+ p[BFD].required_min_rx_interval,
+ self.vpp_session.required_min_rx,
+ "BFD required min rx interval",
+ )
self.vpp_session.modify_parameters(
- required_min_rx=2 * self.vpp_session.required_min_rx)
+ required_min_rx=2 * self.vpp_session.required_min_rx
+ )
# 2nd poll sequence should be queued now
# don't send the reply back yet, wait for some time to emulate
# longer round-trip time
@@ -1082,15 +1174,19 @@ class BFD4TestCase(VppTestCase):
while time.time() < send_final_after:
self.test_session.send_packet()
p = wait_for_bfd_packet(self)
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
- self.assert_equal(p[BFD].required_min_rx_interval,
- self.vpp_session.required_min_rx,
- "BFD required min rx interval")
+ self.assert_equal(
+ len(self.vapi.collect_events()), 0, "number of bfd events"
+ )
+ self.assert_equal(
+ p[BFD].required_min_rx_interval,
+ self.vpp_session.required_min_rx,
+ "BFD required min rx interval",
+ )
packet_count += 1
# poll bit must be set
- self.assertIn("P", p.sprintf("%BFD.flags%"),
- "Poll bit not set in BFD packet")
+ self.assertIn(
+ "P", p.sprintf("%BFD.flags%"), "Poll bit not set in BFD packet"
+ )
final = self.test_session.create_packet()
final[BFD].flags = "F"
self.test_session.send_packet(final)
@@ -1100,8 +1196,9 @@ class BFD4TestCase(VppTestCase):
poll_no_2_started = False
for dummy in range(2 * packet_count):
p = wait_for_bfd_packet(self)
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.assert_equal(
+ len(self.vapi.collect_events()), 0, "number of bfd events"
+ )
if "P" in p.sprintf("%BFD.flags%"):
poll_no_2_started = True
if time.time() < poll_sequence_start + poll_sequence_length:
@@ -1119,31 +1216,32 @@ class BFD4TestCase(VppTestCase):
self.test_session.send_packet(final)
p = wait_for_bfd_packet(self)
# poll bit must not be set
- self.assertNotIn("P", p.sprintf("%BFD.flags%"),
- "Poll bit set in BFD packet")
+ self.assertNotIn("P", p.sprintf("%BFD.flags%"), "Poll bit set in BFD packet")
# returning inconsistent results requiring retries in per-patch tests
@unittest.skipUnless(config.extended, "part of extended tests")
def test_poll_response(self):
- """ test correct response to control frame with poll bit set """
+ """test correct response to control frame with poll bit set"""
bfd_session_up(self)
poll = self.test_session.create_packet()
poll[BFD].flags = "P"
self.test_session.send_packet(poll)
final = wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ self, pcap_time_min=time.time() - self.vpp_clock_offset
+ )
self.assertIn("F", final.sprintf("%BFD.flags%"))
def test_no_periodic_if_remote_demand(self):
- """ no periodic frames outside poll sequence if remote demand set """
+ """no periodic frames outside poll sequence if remote demand set"""
bfd_session_up(self)
demand = self.test_session.create_packet()
demand[BFD].flags = "D"
self.test_session.send_packet(demand)
- transmit_time = 0.9 \
- * max(self.vpp_session.required_min_rx,
- self.test_session.desired_min_tx) \
+ transmit_time = (
+ 0.9
+ * max(self.vpp_session.required_min_rx, self.test_session.desired_min_tx)
/ USEC_IN_SEC
+ )
count = 0
for dummy in range(self.test_session.detect_mult * 2):
self.sleep(transmit_time)
@@ -1161,7 +1259,7 @@ class BFD4TestCase(VppTestCase):
self.assert_equal(len(events), 0, "number of events received")
def test_echo_looped_back(self):
- """ echo packets looped back """
+ """echo packets looped back"""
bfd_session_up(self)
stats_before = bfd_grab_stats_snapshot(self)
self.pg0.enable_capture()
@@ -1169,14 +1267,14 @@ class BFD4TestCase(VppTestCase):
# random source port low enough to increment a few times..
udp_sport_tx = randint(1, 50000)
udp_sport_rx = udp_sport_tx
- echo_packet = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg0.remote_ip4) /
- UDP(dport=BFD.udp_dport_echo) /
- Raw("this should be looped back"))
+ echo_packet = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4)
+ / UDP(dport=BFD.udp_dport_echo)
+ / Raw("this should be looped back")
+ )
for dummy in range(echo_packet_count):
- self.sleep(.01, "delay between echo packets")
+ self.sleep(0.01, "delay between echo packets")
echo_packet[UDP].sport = udp_sport_tx
udp_sport_tx += 1
self.logger.debug(ppp("Sending packet:", echo_packet))
@@ -1189,8 +1287,7 @@ class BFD4TestCase(VppTestCase):
p = self.pg0.wait_for_packet(1)
self.logger.debug(ppp("Got packet:", p))
ether = p[Ether]
- self.assert_equal(self.pg0.remote_mac,
- ether.dst, "Destination MAC")
+ self.assert_equal(self.pg0.remote_mac, ether.dst, "Destination MAC")
self.assert_equal(self.pg0.local_mac, ether.src, "Source MAC")
ip = p[IP]
self.assert_equal(self.pg0.remote_ip4, ip.dst, "Destination IP")
@@ -1199,50 +1296,57 @@ class BFD4TestCase(VppTestCase):
bfd_control_packets_rx += 1
continue
self.assert_equal(self.pg0.remote_ip4, ip.src, "Source IP")
- self.assert_equal(udp.dport, BFD.udp_dport_echo,
- "UDP destination port")
+ self.assert_equal(udp.dport, BFD.udp_dport_echo, "UDP destination port")
self.assert_equal(udp.sport, udp_sport_rx, "UDP source port")
udp_sport_rx += 1
# need to compare the hex payload here, otherwise BFD_vpp_echo
# gets in way
- self.assertEqual(scapy.compat.raw(p[UDP].payload),
- scapy.compat.raw(echo_packet[UDP].payload),
- "Received packet is not the echo packet sent")
+ self.assertEqual(
+ scapy.compat.raw(p[UDP].payload),
+ scapy.compat.raw(echo_packet[UDP].payload),
+ "Received packet is not the echo packet sent",
+ )
counter += 1
- self.assert_equal(udp_sport_tx, udp_sport_rx, "UDP source port (== "
- "ECHO packet identifier for test purposes)")
+ self.assert_equal(
+ udp_sport_tx,
+ udp_sport_rx,
+ "UDP source port (== ECHO packet identifier for test purposes)",
+ )
stats_after = bfd_grab_stats_snapshot(self)
diff = bfd_stats_diff(stats_before, stats_after)
+ self.assertEqual(0, diff.rx, "RX counter bumped but no BFD packets sent")
+ self.assertEqual(bfd_control_packets_rx, diff.tx, "TX counter incorrect")
self.assertEqual(
- 0, diff.rx, "RX counter bumped but no BFD packets sent")
+ 0, diff.rx_echo, "RX echo counter bumped but no BFD session exists"
+ )
self.assertEqual(
- bfd_control_packets_rx, diff.tx, "TX counter incorrect")
- self.assertEqual(0, diff.rx_echo,
- "RX echo counter bumped but no BFD session exists")
- self.assertEqual(0, diff.tx_echo,
- "TX echo counter bumped but no BFD session exists")
+ 0, diff.tx_echo, "TX echo counter bumped but no BFD session exists"
+ )
def test_echo(self):
- """ echo function """
+ """echo function"""
stats_before = bfd_grab_stats_snapshot(self)
bfd_session_up(self)
self.test_session.update(required_min_echo_rx=150000)
self.test_session.send_packet()
- detection_time = self.test_session.detect_mult *\
- self.vpp_session.required_min_rx / USEC_IN_SEC
+ detection_time = (
+ self.test_session.detect_mult
+ * self.vpp_session.required_min_rx
+ / USEC_IN_SEC
+ )
# echo shouldn't work without echo source set
for dummy in range(10):
sleep = self.vpp_session.required_min_rx / USEC_IN_SEC
self.sleep(sleep, "delay before sending bfd packet")
self.test_session.send_packet()
- p = wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
- self.assert_equal(p[BFD].required_min_rx_interval,
- self.vpp_session.required_min_rx,
- "BFD required min rx interval")
+ p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ self.assert_equal(
+ p[BFD].required_min_rx_interval,
+ self.vpp_session.required_min_rx,
+ "BFD required min rx interval",
+ )
self.test_session.send_packet()
- self.vapi.bfd_udp_set_echo_source(
- sw_if_index=self.loopback0.sw_if_index)
+ self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index)
echo_seen = False
# should be turned on - loopback echo packets
for dummy in range(3):
@@ -1251,13 +1355,18 @@ class BFD4TestCase(VppTestCase):
p = self.pg0.wait_for_packet(1)
self.logger.debug(ppp("Got packet:", p))
if p[UDP].dport == BFD.udp_dport_echo:
- self.assert_equal(
- p[IP].dst, self.pg0.local_ip4, "BFD ECHO dst IP")
- self.assertNotEqual(p[IP].src, self.loopback0.local_ip4,
- "BFD ECHO src IP equal to loopback IP")
+ self.assert_equal(p[IP].dst, self.pg0.local_ip4, "BFD ECHO dst IP")
+ self.assertNotEqual(
+ p[IP].src,
+ self.loopback0.local_ip4,
+ "BFD ECHO src IP equal to loopback IP",
+ )
self.logger.debug(ppp("Looping back packet:", p))
- self.assert_equal(p[Ether].dst, self.pg0.remote_mac,
- "ECHO packet destination MAC address")
+ self.assert_equal(
+ p[Ether].dst,
+ self.pg0.remote_mac,
+ "ECHO packet destination MAC address",
+ )
p[Ether].dst = self.pg0.local_mac
self.pg0.add_stream(p)
self.test_session.rx_packets_echo += 1
@@ -1268,8 +1377,8 @@ class BFD4TestCase(VppTestCase):
self.test_session.rx_packets += 1
if echo_seen:
self.assertGreaterEqual(
- p[BFD].required_min_rx_interval,
- 1000000)
+ p[BFD].required_min_rx_interval, 1000000
+ )
if "P" in p.sprintf("%BFD.flags%"):
final = self.test_session.create_packet()
final[BFD].flags = "F"
@@ -1277,34 +1386,45 @@ class BFD4TestCase(VppTestCase):
else:
raise Exception(ppp("Received unknown packet:", p))
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.assert_equal(
+ len(self.vapi.collect_events()), 0, "number of bfd events"
+ )
self.test_session.send_packet()
self.assertTrue(echo_seen, "No echo packets received")
stats_after = bfd_grab_stats_snapshot(self)
diff = bfd_stats_diff(stats_before, stats_after)
# our rx is vpp tx and vice versa, also tolerate one packet off
- self.assert_in_range(self.test_session.tx_packets,
- diff.rx - 1, diff.rx + 1, "RX counter")
- self.assert_in_range(self.test_session.rx_packets,
- diff.tx - 1, diff.tx + 1, "TX counter")
- self.assert_in_range(self.test_session.tx_packets_echo,
- diff.rx_echo - 1, diff.rx_echo + 1,
- "RX echo counter")
- self.assert_in_range(self.test_session.rx_packets_echo,
- diff.tx_echo - 1, diff.tx_echo + 1,
- "TX echo counter")
+ self.assert_in_range(
+ self.test_session.tx_packets, diff.rx - 1, diff.rx + 1, "RX counter"
+ )
+ self.assert_in_range(
+ self.test_session.rx_packets, diff.tx - 1, diff.tx + 1, "TX counter"
+ )
+ self.assert_in_range(
+ self.test_session.tx_packets_echo,
+ diff.rx_echo - 1,
+ diff.rx_echo + 1,
+ "RX echo counter",
+ )
+ self.assert_in_range(
+ self.test_session.rx_packets_echo,
+ diff.tx_echo - 1,
+ diff.tx_echo + 1,
+ "TX echo counter",
+ )
def test_echo_fail(self):
- """ session goes down if echo function fails """
+ """session goes down if echo function fails"""
bfd_session_up(self)
self.test_session.update(required_min_echo_rx=150000)
self.test_session.send_packet()
- detection_time = self.test_session.detect_mult *\
- self.vpp_session.required_min_rx / USEC_IN_SEC
- self.vapi.bfd_udp_set_echo_source(
- sw_if_index=self.loopback0.sw_if_index)
+ detection_time = (
+ self.test_session.detect_mult
+ * self.vpp_session.required_min_rx
+ / USEC_IN_SEC
+ )
+ self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index)
# echo function should be used now, but we will drop the echo packets
verified_diag = False
for dummy in range(3):
@@ -1318,15 +1438,15 @@ class BFD4TestCase(VppTestCase):
elif p.haslayer(BFD):
if "P" in p.sprintf("%BFD.flags%"):
self.assertGreaterEqual(
- p[BFD].required_min_rx_interval,
- 1000000)
+ p[BFD].required_min_rx_interval, 1000000
+ )
final = self.test_session.create_packet()
final[BFD].flags = "F"
self.test_session.send_packet(final)
if p[BFD].state == BFDState.down:
- self.assert_equal(p[BFD].diag,
- BFDDiagCode.echo_function_failed,
- BFDDiagCode)
+ self.assert_equal(
+ p[BFD].diag, BFDDiagCode.echo_function_failed, BFDDiagCode
+ )
verified_diag = True
else:
raise Exception(ppp("Received unknown packet:", p))
@@ -1337,12 +1457,11 @@ class BFD4TestCase(VppTestCase):
self.assertTrue(verified_diag, "Incorrect diagnostics code received")
def test_echo_stop(self):
- """ echo function stops if peer sets required min echo rx zero """
+ """echo function stops if peer sets required min echo rx zero"""
bfd_session_up(self)
self.test_session.update(required_min_echo_rx=150000)
self.test_session.send_packet()
- self.vapi.bfd_udp_set_echo_source(
- sw_if_index=self.loopback0.sw_if_index)
+ self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index)
# wait for first echo packet
while True:
p = self.pg0.wait_for_packet(1)
@@ -1362,19 +1481,17 @@ class BFD4TestCase(VppTestCase):
self.test_session.send_packet()
# echo packets shouldn't arrive anymore
for dummy in range(5):
- wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
self.test_session.send_packet()
events = self.vapi.collect_events()
self.assert_equal(len(events), 0, "number of bfd events")
def test_echo_source_removed(self):
- """ echo function stops if echo source is removed """
+ """echo function stops if echo source is removed"""
bfd_session_up(self)
self.test_session.update(required_min_echo_rx=150000)
self.test_session.send_packet()
- self.vapi.bfd_udp_set_echo_source(
- sw_if_index=self.loopback0.sw_if_index)
+ self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index)
# wait for first echo packet
while True:
p = self.pg0.wait_for_packet(1)
@@ -1394,18 +1511,16 @@ class BFD4TestCase(VppTestCase):
self.test_session.send_packet()
# echo packets shouldn't arrive anymore
for dummy in range(5):
- wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
self.test_session.send_packet()
events = self.vapi.collect_events()
self.assert_equal(len(events), 0, "number of bfd events")
def test_stale_echo(self):
- """ stale echo packets don't keep a session up """
+ """stale echo packets don't keep a session up"""
bfd_session_up(self)
self.test_session.update(required_min_echo_rx=150000)
- self.vapi.bfd_udp_set_echo_source(
- sw_if_index=self.loopback0.sw_if_index)
+ self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index)
self.test_session.send_packet()
# should be turned on - loopback echo packets
echo_packet = None
@@ -1417,8 +1532,12 @@ class BFD4TestCase(VppTestCase):
if echo_packet is None:
self.logger.debug(ppp("Got first echo packet:", p))
echo_packet = p
- timeout_at = time.time() + self.vpp_session.detect_mult * \
- self.test_session.required_min_echo_rx / USEC_IN_SEC
+ timeout_at = (
+ time.time()
+ + self.vpp_session.detect_mult
+ * self.test_session.required_min_echo_rx
+ / USEC_IN_SEC
+ )
else:
self.logger.debug(ppp("Got followup echo packet:", p))
self.logger.debug(ppp("Looping back first echo packet:", p))
@@ -1434,15 +1553,18 @@ class BFD4TestCase(VppTestCase):
if p[BFD].state == BFDState.down:
self.assertIsNotNone(
timeout_at,
- "Session went down before first echo packet received")
+ "Session went down before first echo packet received",
+ )
now = time.time()
self.assertGreaterEqual(
- now, timeout_at,
- "Session timeout at %s, but is expected at %s" %
- (now, timeout_at))
- self.assert_equal(p[BFD].diag,
- BFDDiagCode.echo_function_failed,
- BFDDiagCode)
+ now,
+ timeout_at,
+ "Session timeout at %s, but is expected at %s"
+ % (now, timeout_at),
+ )
+ self.assert_equal(
+ p[BFD].diag, BFDDiagCode.echo_function_failed, BFDDiagCode
+ )
events = self.vapi.collect_events()
self.assert_equal(len(events), 1, "number of bfd events")
self.assert_equal(events[0].state, BFDState.down, BFDState)
@@ -1454,11 +1576,10 @@ class BFD4TestCase(VppTestCase):
self.assertTrue(timeout_ok, "Expected timeout event didn't occur")
def test_invalid_echo_checksum(self):
- """ echo packets with invalid checksum don't keep a session up """
+ """echo packets with invalid checksum don't keep a session up"""
bfd_session_up(self)
self.test_session.update(required_min_echo_rx=150000)
- self.vapi.bfd_udp_set_echo_source(
- sw_if_index=self.loopback0.sw_if_index)
+ self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index)
self.test_session.send_packet()
# should be turned on - loopback echo packets
timeout_at = None
@@ -1468,8 +1589,12 @@ class BFD4TestCase(VppTestCase):
if p[UDP].dport == BFD.udp_dport_echo:
self.logger.debug(ppp("Got echo packet:", p))
if timeout_at is None:
- timeout_at = time.time() + self.vpp_session.detect_mult * \
- self.test_session.required_min_echo_rx / USEC_IN_SEC
+ timeout_at = (
+ time.time()
+ + self.vpp_session.detect_mult
+ * self.test_session.required_min_echo_rx
+ / USEC_IN_SEC
+ )
p[BFD_vpp_echo].checksum = getrandbits(64)
p[Ether].dst = self.pg0.local_mac
self.logger.debug(ppp("Looping back modified echo packet:", p))
@@ -1484,15 +1609,18 @@ class BFD4TestCase(VppTestCase):
if p[BFD].state == BFDState.down:
self.assertIsNotNone(
timeout_at,
- "Session went down before first echo packet received")
+ "Session went down before first echo packet received",
+ )
now = time.time()
self.assertGreaterEqual(
- now, timeout_at,
- "Session timeout at %s, but is expected at %s" %
- (now, timeout_at))
- self.assert_equal(p[BFD].diag,
- BFDDiagCode.echo_function_failed,
- BFDDiagCode)
+ now,
+ timeout_at,
+ "Session timeout at %s, but is expected at %s"
+ % (now, timeout_at),
+ )
+ self.assert_equal(
+ p[BFD].diag, BFDDiagCode.echo_function_failed, BFDDiagCode
+ )
events = self.vapi.collect_events()
self.assert_equal(len(events), 1, "number of bfd events")
self.assert_equal(events[0].state, BFDState.down, BFDState)
@@ -1504,7 +1632,7 @@ class BFD4TestCase(VppTestCase):
self.assertTrue(timeout_ok, "Expected timeout event didn't occur")
def test_admin_up_down(self):
- """ put session admin-up and admin-down """
+ """put session admin-up and admin-down"""
bfd_session_up(self)
self.vpp_session.admin_down()
self.pg0.enable_capture()
@@ -1523,33 +1651,30 @@ class BFD4TestCase(VppTestCase):
self.test_session.update(state=BFDState.down)
e = self.vapi.wait_for_event(1, "bfd_udp_session_event")
verify_event(self, e, expected_state=BFDState.down)
- p = wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
self.assert_equal(p[BFD].state, BFDState.down, BFDState)
self.test_session.send_packet()
- p = wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
self.assert_equal(p[BFD].state, BFDState.init, BFDState)
e = self.vapi.wait_for_event(1, "bfd_udp_session_event")
verify_event(self, e, expected_state=BFDState.init)
self.test_session.update(state=BFDState.up)
self.test_session.send_packet()
- p = wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
self.assert_equal(p[BFD].state, BFDState.up, BFDState)
e = self.vapi.wait_for_event(1, "bfd_udp_session_event")
verify_event(self, e, expected_state=BFDState.up)
def test_config_change_remote_demand(self):
- """ configuration change while peer in demand mode """
+ """configuration change while peer in demand mode"""
bfd_session_up(self)
demand = self.test_session.create_packet()
demand[BFD].flags = "D"
self.test_session.send_packet(demand)
self.vpp_session.modify_parameters(
- required_min_rx=2 * self.vpp_session.required_min_rx)
- p = wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ required_min_rx=2 * self.vpp_session.required_min_rx
+ )
+ p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
# poll bit must be set
self.assertIn("P", p.sprintf("%BFD.flags%"), "Poll bit not set")
# terminate poll sequence
@@ -1557,10 +1682,11 @@ class BFD4TestCase(VppTestCase):
final[BFD].flags = "D+F"
self.test_session.send_packet(final)
# vpp should be quiet now again
- transmit_time = 0.9 \
- * max(self.vpp_session.required_min_rx,
- self.test_session.desired_min_tx) \
+ transmit_time = (
+ 0.9
+ * max(self.vpp_session.required_min_rx, self.test_session.desired_min_tx)
/ USEC_IN_SEC
+ )
count = 0
for dummy in range(self.test_session.detect_mult * 2):
self.sleep(transmit_time)
@@ -1578,7 +1704,7 @@ class BFD4TestCase(VppTestCase):
self.assert_equal(len(events), 0, "number of events received")
def test_intf_deleted(self):
- """ interface with bfd session deleted """
+ """interface with bfd session deleted"""
intf = VppLoInterface(self)
intf.config_ip4()
intf.admin_up()
@@ -1595,7 +1721,7 @@ class BFD4TestCase(VppTestCase):
@tag_run_solo
@tag_fixme_vpp_workers
class BFD6TestCase(VppTestCase):
- """Bidirectional Forwarding Detection (BFD) (IPv6) """
+ """Bidirectional Forwarding Detection (BFD) (IPv6)"""
pg0 = None
vpp_clock_offset = None
@@ -1631,11 +1757,11 @@ class BFD6TestCase(VppTestCase):
self.vapi.want_bfd_events()
self.pg0.enable_capture()
try:
- self.bfd_udp4_sessions = self.statistics['/bfd/udp4/sessions']
- self.bfd_udp6_sessions = self.statistics['/bfd/udp6/sessions']
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip6,
- af=AF_INET6)
+ self.bfd_udp4_sessions = self.statistics["/bfd/udp4/sessions"]
+ self.bfd_udp6_sessions = self.statistics["/bfd/udp6/sessions"]
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip6, af=AF_INET6
+ )
self.vpp_session.add_vpp_config()
self.vpp_session.admin_up()
self.test_session = BFDTestSession(self, self.pg0, AF_INET6)
@@ -1651,26 +1777,29 @@ class BFD6TestCase(VppTestCase):
super(BFD6TestCase, self).tearDown()
def test_session_up(self):
- """ bring BFD session up """
+ """bring BFD session up"""
bfd_session_up(self)
- bfd_udp4_sessions = self.statistics['/bfd/udp4/sessions']
- bfd_udp6_sessions = self.statistics['/bfd/udp6/sessions']
+ bfd_udp4_sessions = self.statistics["/bfd/udp4/sessions"]
+ bfd_udp6_sessions = self.statistics["/bfd/udp6/sessions"]
self.assert_equal(bfd_udp4_sessions, self.bfd_udp4_sessions)
self.assert_equal(bfd_udp6_sessions - self.bfd_udp6_sessions, 1)
def test_session_up_by_ip(self):
- """ bring BFD session up - first frame looked up by address pair """
+ """bring BFD session up - first frame looked up by address pair"""
self.logger.info("BFD: Sending Slow control frame")
self.test_session.update(my_discriminator=randint(0, 40000000))
self.test_session.send_packet()
self.pg0.enable_capture()
p = self.pg0.wait_for_packet(1)
- self.assert_equal(p[BFD].your_discriminator,
- self.test_session.my_discriminator,
- "BFD - your discriminator")
+ self.assert_equal(
+ p[BFD].your_discriminator,
+ self.test_session.my_discriminator,
+ "BFD - your discriminator",
+ )
self.assert_equal(p[BFD].state, BFDState.init, BFDState)
- self.test_session.update(your_discriminator=p[BFD].my_discriminator,
- state=BFDState.up)
+ self.test_session.update(
+ your_discriminator=p[BFD].my_discriminator, state=BFDState.up
+ )
self.logger.info("BFD: Waiting for event")
e = self.vapi.wait_for_event(1, "bfd_udp_session_event")
verify_event(self, e, expected_state=BFDState.init)
@@ -1685,17 +1814,16 @@ class BFD6TestCase(VppTestCase):
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
def test_hold_up(self):
- """ hold BFD session up """
+ """hold BFD session up"""
bfd_session_up(self)
for dummy in range(self.test_session.detect_mult * 2):
wait_for_bfd_packet(self)
self.test_session.send_packet()
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events")
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
def test_echo_looped_back(self):
- """ echo packets looped back """
+ """echo packets looped back"""
bfd_session_up(self)
stats_before = bfd_grab_stats_snapshot(self)
self.pg0.enable_capture()
@@ -1703,14 +1831,14 @@ class BFD6TestCase(VppTestCase):
# random source port low enough to increment a few times..
udp_sport_tx = randint(1, 50000)
udp_sport_rx = udp_sport_tx
- echo_packet = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=self.pg0.remote_ip6) /
- UDP(dport=BFD.udp_dport_echo) /
- Raw("this should be looped back"))
+ echo_packet = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6)
+ / UDP(dport=BFD.udp_dport_echo)
+ / Raw("this should be looped back")
+ )
for dummy in range(echo_packet_count):
- self.sleep(.01, "delay between echo packets")
+ self.sleep(0.01, "delay between echo packets")
echo_packet[UDP].sport = udp_sport_tx
udp_sport_tx += 1
self.logger.debug(ppp("Sending packet:", echo_packet))
@@ -1722,8 +1850,7 @@ class BFD6TestCase(VppTestCase):
p = self.pg0.wait_for_packet(1)
self.logger.debug(ppp("Got packet:", p))
ether = p[Ether]
- self.assert_equal(self.pg0.remote_mac,
- ether.dst, "Destination MAC")
+ self.assert_equal(self.pg0.remote_mac, ether.dst, "Destination MAC")
self.assert_equal(self.pg0.local_mac, ether.src, "Source MAC")
ip = p[IPv6]
self.assert_equal(self.pg0.remote_ip6, ip.dst, "Destination IP")
@@ -1732,50 +1859,57 @@ class BFD6TestCase(VppTestCase):
bfd_control_packets_rx += 1
continue
self.assert_equal(self.pg0.remote_ip6, ip.src, "Source IP")
- self.assert_equal(udp.dport, BFD.udp_dport_echo,
- "UDP destination port")
+ self.assert_equal(udp.dport, BFD.udp_dport_echo, "UDP destination port")
self.assert_equal(udp.sport, udp_sport_rx, "UDP source port")
udp_sport_rx += 1
# need to compare the hex payload here, otherwise BFD_vpp_echo
# gets in way
- self.assertEqual(scapy.compat.raw(p[UDP].payload),
- scapy.compat.raw(echo_packet[UDP].payload),
- "Received packet is not the echo packet sent")
+ self.assertEqual(
+ scapy.compat.raw(p[UDP].payload),
+ scapy.compat.raw(echo_packet[UDP].payload),
+ "Received packet is not the echo packet sent",
+ )
counter += 1
- self.assert_equal(udp_sport_tx, udp_sport_rx, "UDP source port (== "
- "ECHO packet identifier for test purposes)")
+ self.assert_equal(
+ udp_sport_tx,
+ udp_sport_rx,
+ "UDP source port (== ECHO packet identifier for test purposes)",
+ )
stats_after = bfd_grab_stats_snapshot(self)
diff = bfd_stats_diff(stats_before, stats_after)
+ self.assertEqual(0, diff.rx, "RX counter bumped but no BFD packets sent")
+ self.assertEqual(bfd_control_packets_rx, diff.tx, "TX counter incorrect")
self.assertEqual(
- 0, diff.rx, "RX counter bumped but no BFD packets sent")
- self.assertEqual(bfd_control_packets_rx,
- diff.tx, "TX counter incorrect")
- self.assertEqual(0, diff.rx_echo,
- "RX echo counter bumped but no BFD session exists")
- self.assertEqual(0, diff.tx_echo,
- "TX echo counter bumped but no BFD session exists")
+ 0, diff.rx_echo, "RX echo counter bumped but no BFD session exists"
+ )
+ self.assertEqual(
+ 0, diff.tx_echo, "TX echo counter bumped but no BFD session exists"
+ )
def test_echo(self):
- """ echo function """
+ """echo function"""
stats_before = bfd_grab_stats_snapshot(self)
bfd_session_up(self)
self.test_session.update(required_min_echo_rx=150000)
self.test_session.send_packet()
- detection_time = self.test_session.detect_mult *\
- self.vpp_session.required_min_rx / USEC_IN_SEC
+ detection_time = (
+ self.test_session.detect_mult
+ * self.vpp_session.required_min_rx
+ / USEC_IN_SEC
+ )
# echo shouldn't work without echo source set
for dummy in range(10):
sleep = self.vpp_session.required_min_rx / USEC_IN_SEC
self.sleep(sleep, "delay before sending bfd packet")
self.test_session.send_packet()
- p = wait_for_bfd_packet(
- self, pcap_time_min=time.time() - self.vpp_clock_offset)
- self.assert_equal(p[BFD].required_min_rx_interval,
- self.vpp_session.required_min_rx,
- "BFD required min rx interval")
+ p = wait_for_bfd_packet(self, pcap_time_min=time.time() - self.vpp_clock_offset)
+ self.assert_equal(
+ p[BFD].required_min_rx_interval,
+ self.vpp_session.required_min_rx,
+ "BFD required min rx interval",
+ )
self.test_session.send_packet()
- self.vapi.bfd_udp_set_echo_source(
- sw_if_index=self.loopback0.sw_if_index)
+ self.vapi.bfd_udp_set_echo_source(sw_if_index=self.loopback0.sw_if_index)
echo_seen = False
# should be turned on - loopback echo packets
for dummy in range(3):
@@ -1785,12 +1919,19 @@ class BFD6TestCase(VppTestCase):
self.logger.debug(ppp("Got packet:", p))
if p[UDP].dport == BFD.udp_dport_echo:
self.assert_equal(
- p[IPv6].dst, self.pg0.local_ip6, "BFD ECHO dst IP")
- self.assertNotEqual(p[IPv6].src, self.loopback0.local_ip6,
- "BFD ECHO src IP equal to loopback IP")
+ p[IPv6].dst, self.pg0.local_ip6, "BFD ECHO dst IP"
+ )
+ self.assertNotEqual(
+ p[IPv6].src,
+ self.loopback0.local_ip6,
+ "BFD ECHO src IP equal to loopback IP",
+ )
self.logger.debug(ppp("Looping back packet:", p))
- self.assert_equal(p[Ether].dst, self.pg0.remote_mac,
- "ECHO packet destination MAC address")
+ self.assert_equal(
+ p[Ether].dst,
+ self.pg0.remote_mac,
+ "ECHO packet destination MAC address",
+ )
self.test_session.rx_packets_echo += 1
self.test_session.tx_packets_echo += 1
p[Ether].dst = self.pg0.local_mac
@@ -1801,8 +1942,8 @@ class BFD6TestCase(VppTestCase):
self.test_session.rx_packets += 1
if echo_seen:
self.assertGreaterEqual(
- p[BFD].required_min_rx_interval,
- 1000000)
+ p[BFD].required_min_rx_interval, 1000000
+ )
if "P" in p.sprintf("%BFD.flags%"):
final = self.test_session.create_packet()
final[BFD].flags = "F"
@@ -1810,33 +1951,41 @@ class BFD6TestCase(VppTestCase):
else:
raise Exception(ppp("Received unknown packet:", p))
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.assert_equal(
+ len(self.vapi.collect_events()), 0, "number of bfd events"
+ )
self.test_session.send_packet()
self.assertTrue(echo_seen, "No echo packets received")
stats_after = bfd_grab_stats_snapshot(self)
diff = bfd_stats_diff(stats_before, stats_after)
# our rx is vpp tx and vice versa, also tolerate one packet off
- self.assert_in_range(self.test_session.tx_packets,
- diff.rx - 1, diff.rx + 1, "RX counter")
- self.assert_in_range(self.test_session.rx_packets,
- diff.tx - 1, diff.tx + 1, "TX counter")
- self.assert_in_range(self.test_session.tx_packets_echo,
- diff.rx_echo - 1, diff.rx_echo + 1,
- "RX echo counter")
- self.assert_in_range(self.test_session.rx_packets_echo,
- diff.tx_echo - 1, diff.tx_echo + 1,
- "TX echo counter")
+ self.assert_in_range(
+ self.test_session.tx_packets, diff.rx - 1, diff.rx + 1, "RX counter"
+ )
+ self.assert_in_range(
+ self.test_session.rx_packets, diff.tx - 1, diff.tx + 1, "TX counter"
+ )
+ self.assert_in_range(
+ self.test_session.tx_packets_echo,
+ diff.rx_echo - 1,
+ diff.rx_echo + 1,
+ "RX echo counter",
+ )
+ self.assert_in_range(
+ self.test_session.rx_packets_echo,
+ diff.tx_echo - 1,
+ diff.tx_echo + 1,
+ "TX echo counter",
+ )
def test_intf_deleted(self):
- """ interface with bfd session deleted """
+ """interface with bfd session deleted"""
intf = VppLoInterface(self)
intf.config_ip6()
intf.admin_up()
sw_if_index = intf.sw_if_index
- vpp_session = VppBFDUDPSession(
- self, intf, intf.remote_ip6, af=AF_INET6)
+ vpp_session = VppBFDUDPSession(self, intf, intf.remote_ip6, af=AF_INET6)
vpp_session.add_vpp_config()
vpp_session.admin_up()
intf.remove_vpp_config()
@@ -1847,7 +1996,7 @@ class BFD6TestCase(VppTestCase):
@tag_run_solo
class BFDFIBTestCase(VppTestCase):
- """ BFD-FIB interactions (IPv6) """
+ """BFD-FIB interactions (IPv6)"""
vpp_session = None
test_session = None
@@ -1880,40 +2029,48 @@ class BFDFIBTestCase(VppTestCase):
@staticmethod
def pkt_is_not_data_traffic(p):
- """ not data traffic implies BFD or the usual IPv6 ND/RA"""
+ """not data traffic implies BFD or the usual IPv6 ND/RA"""
if p.haslayer(BFD) or is_ipv6_misc(p):
return True
return False
def test_session_with_fib(self):
- """ BFD-FIB interactions """
+ """BFD-FIB interactions"""
# packets to match against both of the routes
- p = [(Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src="3001::1", dst="2001::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src="3001::1", dst="2002::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
+ p = [
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src="3001::1", dst="2001::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src="3001::1", dst="2002::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
# A recursive and a non-recursive route via a next-hop that
# will have a BFD session
- ip_2001_s_64 = VppIpRoute(self, "2001::", 64,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index)])
- ip_2002_s_64 = VppIpRoute(self, "2002::", 64,
- [VppRoutePath(self.pg0.remote_ip6,
- 0xffffffff)])
+ ip_2001_s_64 = VppIpRoute(
+ self,
+ "2001::",
+ 64,
+ [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)],
+ )
+ ip_2002_s_64 = VppIpRoute(
+ self, "2002::", 64, [VppRoutePath(self.pg0.remote_ip6, 0xFFFFFFFF)]
+ )
ip_2001_s_64.add_vpp_config()
ip_2002_s_64.add_vpp_config()
# bring the session up now the routes are present
- self.vpp_session = VppBFDUDPSession(self,
- self.pg0,
- self.pg0.remote_ip6,
- af=AF_INET6)
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip6, af=AF_INET6
+ )
self.vpp_session.add_vpp_config()
self.vpp_session.admin_up()
self.test_session = BFDTestSession(self, self.pg0, AF_INET6)
@@ -1925,10 +2082,9 @@ class BFDFIBTestCase(VppTestCase):
self.pg_start()
for packet in p:
captured = self.pg0.wait_for_packet(
- 1,
- filter_out_fn=self.pkt_is_not_data_traffic)
- self.assertEqual(captured[IPv6].dst,
- packet[IPv6].dst)
+ 1, filter_out_fn=self.pkt_is_not_data_traffic
+ )
+ self.assertEqual(captured[IPv6].dst, packet[IPv6].dst)
# session is up - traffic is dropped
bfd_session_down(self)
@@ -1945,15 +2101,14 @@ class BFDFIBTestCase(VppTestCase):
self.pg_start()
for packet in p:
captured = self.pg0.wait_for_packet(
- 1,
- filter_out_fn=self.pkt_is_not_data_traffic)
- self.assertEqual(captured[IPv6].dst,
- packet[IPv6].dst)
+ 1, filter_out_fn=self.pkt_is_not_data_traffic
+ )
+ self.assertEqual(captured[IPv6].dst, packet[IPv6].dst)
@unittest.skipUnless(config.extended, "part of extended tests")
class BFDTunTestCase(VppTestCase):
- """ BFD over GRE tunnel """
+ """BFD over GRE tunnel"""
vpp_session = None
test_session = None
@@ -1986,42 +2141,44 @@ class BFDTunTestCase(VppTestCase):
@staticmethod
def pkt_is_not_data_traffic(p):
- """ not data traffic implies BFD or the usual IPv6 ND/RA"""
+ """not data traffic implies BFD or the usual IPv6 ND/RA"""
if p.haslayer(BFD) or is_ipv6_misc(p):
return True
return False
def test_bfd_o_gre(self):
- """ BFD-o-GRE """
+ """BFD-o-GRE"""
# A GRE interface over which to run a BFD session
- gre_if = VppGreInterface(self,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ gre_if = VppGreInterface(self, self.pg0.local_ip4, self.pg0.remote_ip4)
gre_if.add_vpp_config()
gre_if.admin_up()
gre_if.config_ip4()
# bring the session up now the routes are present
- self.vpp_session = VppBFDUDPSession(self,
- gre_if,
- gre_if.remote_ip4,
- is_tunnel=True)
+ self.vpp_session = VppBFDUDPSession(
+ self, gre_if, gre_if.remote_ip4, is_tunnel=True
+ )
self.vpp_session.add_vpp_config()
self.vpp_session.admin_up()
self.test_session = BFDTestSession(
- self, gre_if, AF_INET,
- tunnel_header=(IP(src=self.pg0.remote_ip4,
- dst=self.pg0.local_ip4) /
- GRE()),
- phy_interface=self.pg0)
+ self,
+ gre_if,
+ AF_INET,
+ tunnel_header=(IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / GRE()),
+ phy_interface=self.pg0,
+ )
# packets to match against both of the routes
- p = [(Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=gre_if.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
+ p = [
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=gre_if.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ ]
# session is up - traffic passes
bfd_session_up(self)
@@ -2034,7 +2191,7 @@ class BFDTunTestCase(VppTestCase):
@tag_run_solo
class BFDSHA1TestCase(VppTestCase):
- """Bidirectional Forwarding Detection (BFD) (SHA1 auth) """
+ """Bidirectional Forwarding Detection (BFD) (SHA1 auth)"""
pg0 = None
vpp_clock_offset = None
@@ -2072,31 +2229,39 @@ class BFDSHA1TestCase(VppTestCase):
super(BFDSHA1TestCase, self).tearDown()
def test_session_up(self):
- """ bring BFD session up """
+ """bring BFD session up"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4,
- sha1_key=key)
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
self.vpp_session.add_vpp_config()
self.vpp_session.admin_up()
self.test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key,
- bfd_key_id=self.vpp_session.bfd_key_id)
+ self,
+ self.pg0,
+ AF_INET,
+ sha1_key=key,
+ bfd_key_id=self.vpp_session.bfd_key_id,
+ )
bfd_session_up(self)
def test_hold_up(self):
- """ hold BFD session up """
+ """hold BFD session up"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4,
- sha1_key=key)
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
self.vpp_session.add_vpp_config()
self.vpp_session.admin_up()
self.test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key,
- bfd_key_id=self.vpp_session.bfd_key_id)
+ self,
+ self.pg0,
+ AF_INET,
+ sha1_key=key,
+ bfd_key_id=self.vpp_session.bfd_key_id,
+ )
bfd_session_up(self)
for dummy in range(self.test_session.detect_mult * 2):
wait_for_bfd_packet(self)
@@ -2104,19 +2269,23 @@ class BFDSHA1TestCase(VppTestCase):
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
def test_hold_up_meticulous(self):
- """ hold BFD session up - meticulous auth """
- key = self.factory.create_random_key(
- self, BFDAuthType.meticulous_keyed_sha1)
+ """hold BFD session up - meticulous auth"""
+ key = self.factory.create_random_key(self, BFDAuthType.meticulous_keyed_sha1)
key.add_vpp_config()
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4, sha1_key=key)
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
self.vpp_session.add_vpp_config()
self.vpp_session.admin_up()
# specify sequence number so that it wraps
self.test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key,
+ self,
+ self.pg0,
+ AF_INET,
+ sha1_key=key,
bfd_key_id=self.vpp_session.bfd_key_id,
- our_seq_number=0xFFFFFFFF - 4)
+ our_seq_number=0xFFFFFFFF - 4,
+ )
bfd_session_up(self)
for dummy in range(30):
wait_for_bfd_packet(self)
@@ -2125,35 +2294,47 @@ class BFDSHA1TestCase(VppTestCase):
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
def test_send_bad_seq_number(self):
- """ session is not kept alive by msgs with bad sequence numbers"""
- key = self.factory.create_random_key(
- self, BFDAuthType.meticulous_keyed_sha1)
+ """session is not kept alive by msgs with bad sequence numbers"""
+ key = self.factory.create_random_key(self, BFDAuthType.meticulous_keyed_sha1)
key.add_vpp_config()
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4, sha1_key=key)
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
self.vpp_session.add_vpp_config()
self.test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key,
- bfd_key_id=self.vpp_session.bfd_key_id)
+ self,
+ self.pg0,
+ AF_INET,
+ sha1_key=key,
+ bfd_key_id=self.vpp_session.bfd_key_id,
+ )
bfd_session_up(self)
- detection_time = self.test_session.detect_mult *\
- self.vpp_session.required_min_rx / USEC_IN_SEC
+ detection_time = (
+ self.test_session.detect_mult
+ * self.vpp_session.required_min_rx
+ / USEC_IN_SEC
+ )
send_until = time.time() + 2 * detection_time
while time.time() < send_until:
self.test_session.send_packet()
- self.sleep(0.7 * self.vpp_session.required_min_rx / USEC_IN_SEC,
- "time between bfd packets")
+ self.sleep(
+ 0.7 * self.vpp_session.required_min_rx / USEC_IN_SEC,
+ "time between bfd packets",
+ )
e = self.vapi.collect_events()
# session should be down now, because the sequence numbers weren't
# updated
self.assert_equal(len(e), 1, "number of bfd events")
verify_event(self, e[0], expected_state=BFDState.down)
- def execute_rogue_session_scenario(self, vpp_bfd_udp_session,
- legitimate_test_session,
- rogue_test_session,
- rogue_bfd_values=None):
- """ execute a rogue session interaction scenario
+ def execute_rogue_session_scenario(
+ self,
+ vpp_bfd_udp_session,
+ legitimate_test_session,
+ rogue_test_session,
+ rogue_bfd_values=None,
+ ):
+ """execute a rogue session interaction scenario
1. create vpp session, add config
2. bring the legitimate session up
@@ -2178,7 +2359,8 @@ class BFDSHA1TestCase(VppTestCase):
detect_mult=self.test_session.detect_mult,
diag=self.test_session.diag,
state=self.test_session.state,
- auth_type=self.test_session.auth_type)
+ auth_type=self.test_session.auth_type,
+ )
if rogue_bfd_values:
rogue_test_session.update(**rogue_bfd_values)
rogue_test_session.update(state=BFDState.down)
@@ -2187,69 +2369,84 @@ class BFDSHA1TestCase(VppTestCase):
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
def test_mismatch_auth(self):
- """ session is not brought down by unauthenticated msg """
+ """session is not brought down by unauthenticated msg"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
vpp_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip4, sha1_key=key)
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
legitimate_test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key,
- bfd_key_id=vpp_session.bfd_key_id)
+ self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=vpp_session.bfd_key_id
+ )
rogue_test_session = BFDTestSession(self, self.pg0, AF_INET)
- self.execute_rogue_session_scenario(vpp_session,
- legitimate_test_session,
- rogue_test_session)
+ self.execute_rogue_session_scenario(
+ vpp_session, legitimate_test_session, rogue_test_session
+ )
def test_mismatch_bfd_key_id(self):
- """ session is not brought down by msg with non-existent key-id """
+ """session is not brought down by msg with non-existent key-id"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
vpp_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip4, sha1_key=key)
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
# pick a different random bfd key id
x = randint(0, 255)
while x == vpp_session.bfd_key_id:
x = randint(0, 255)
legitimate_test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key,
- bfd_key_id=vpp_session.bfd_key_id)
+ self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=vpp_session.bfd_key_id
+ )
rogue_test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=x)
- self.execute_rogue_session_scenario(vpp_session,
- legitimate_test_session,
- rogue_test_session)
+ self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=x
+ )
+ self.execute_rogue_session_scenario(
+ vpp_session, legitimate_test_session, rogue_test_session
+ )
def test_mismatched_auth_type(self):
- """ session is not brought down by msg with wrong auth type """
+ """session is not brought down by msg with wrong auth type"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
vpp_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip4, sha1_key=key)
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
legitimate_test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key,
- bfd_key_id=vpp_session.bfd_key_id)
+ self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=vpp_session.bfd_key_id
+ )
rogue_test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key,
- bfd_key_id=vpp_session.bfd_key_id)
+ self, self.pg0, AF_INET, sha1_key=key, bfd_key_id=vpp_session.bfd_key_id
+ )
self.execute_rogue_session_scenario(
- vpp_session, legitimate_test_session, rogue_test_session,
- {'auth_type': BFDAuthType.keyed_md5})
+ vpp_session,
+ legitimate_test_session,
+ rogue_test_session,
+ {"auth_type": BFDAuthType.keyed_md5},
+ )
def test_restart(self):
- """ simulate remote peer restart and resynchronization """
- key = self.factory.create_random_key(
- self, BFDAuthType.meticulous_keyed_sha1)
+ """simulate remote peer restart and resynchronization"""
+ key = self.factory.create_random_key(self, BFDAuthType.meticulous_keyed_sha1)
key.add_vpp_config()
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4, sha1_key=key)
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
self.vpp_session.add_vpp_config()
self.test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key,
- bfd_key_id=self.vpp_session.bfd_key_id, our_seq_number=0)
+ self,
+ self.pg0,
+ AF_INET,
+ sha1_key=key,
+ bfd_key_id=self.vpp_session.bfd_key_id,
+ our_seq_number=0,
+ )
bfd_session_up(self)
# don't send any packets for 2*detection_time
- detection_time = self.test_session.detect_mult *\
- self.vpp_session.required_min_rx / USEC_IN_SEC
+ detection_time = (
+ self.test_session.detect_mult
+ * self.vpp_session.required_min_rx
+ / USEC_IN_SEC
+ )
self.sleep(2 * detection_time, "simulating peer restart")
events = self.vapi.collect_events()
self.assert_equal(len(events), 1, "number of bfd events")
@@ -2266,7 +2463,7 @@ class BFDSHA1TestCase(VppTestCase):
@tag_run_solo
class BFDAuthOnOffTestCase(VppTestCase):
- """Bidirectional Forwarding Detection (BFD) (changing auth) """
+ """Bidirectional Forwarding Detection (BFD) (changing auth)"""
pg0 = None
vpp_session = None
@@ -2303,11 +2500,10 @@ class BFDAuthOnOffTestCase(VppTestCase):
super(BFDAuthOnOffTestCase, self).tearDown()
def test_auth_on_immediate(self):
- """ turn auth on without disturbing session state (immediate) """
+ """turn auth on without disturbing session state (immediate)"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4)
+ self.vpp_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
self.vpp_session.add_vpp_config()
self.test_session = BFDTestSession(self, self.pg0, AF_INET)
bfd_session_up(self)
@@ -2323,19 +2519,23 @@ class BFDAuthOnOffTestCase(VppTestCase):
self.assert_equal(p[BFD].state, BFDState.up, BFDState)
self.test_session.send_packet()
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events")
def test_auth_off_immediate(self):
- """ turn auth off without disturbing session state (immediate) """
+ """turn auth off without disturbing session state (immediate)"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4, sha1_key=key)
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
self.vpp_session.add_vpp_config()
self.test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key,
- bfd_key_id=self.vpp_session.bfd_key_id)
+ self,
+ self.pg0,
+ AF_INET,
+ sha1_key=key,
+ bfd_key_id=self.vpp_session.bfd_key_id,
+ )
bfd_session_up(self)
# self.vapi.want_bfd_events(enable_disable=0)
for dummy in range(self.test_session.detect_mult * 2):
@@ -2352,21 +2552,25 @@ class BFDAuthOnOffTestCase(VppTestCase):
self.test_session.inc_seq_num()
self.test_session.send_packet()
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events")
def test_auth_change_key_immediate(self):
- """ change auth key without disturbing session state (immediate) """
+ """change auth key without disturbing session state (immediate)"""
key1 = self.factory.create_random_key(self)
key1.add_vpp_config()
key2 = self.factory.create_random_key(self)
key2.add_vpp_config()
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4, sha1_key=key1)
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key1
+ )
self.vpp_session.add_vpp_config()
self.test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key1,
- bfd_key_id=self.vpp_session.bfd_key_id)
+ self,
+ self.pg0,
+ AF_INET,
+ sha1_key=key1,
+ bfd_key_id=self.vpp_session.bfd_key_id,
+ )
bfd_session_up(self)
for dummy in range(self.test_session.detect_mult * 2):
p = wait_for_bfd_packet(self)
@@ -2380,15 +2584,13 @@ class BFDAuthOnOffTestCase(VppTestCase):
self.assert_equal(p[BFD].state, BFDState.up, BFDState)
self.test_session.send_packet()
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events")
def test_auth_on_delayed(self):
- """ turn auth on without disturbing session state (delayed) """
+ """turn auth on without disturbing session state (delayed)"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4)
+ self.vpp_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
self.vpp_session.add_vpp_config()
self.test_session = BFDTestSession(self, self.pg0, AF_INET)
bfd_session_up(self)
@@ -2408,19 +2610,23 @@ class BFDAuthOnOffTestCase(VppTestCase):
self.assert_equal(p[BFD].state, BFDState.up, BFDState)
self.test_session.send_packet()
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events")
def test_auth_off_delayed(self):
- """ turn auth off without disturbing session state (delayed) """
+ """turn auth off without disturbing session state (delayed)"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4, sha1_key=key)
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
self.vpp_session.add_vpp_config()
self.test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key,
- bfd_key_id=self.vpp_session.bfd_key_id)
+ self,
+ self.pg0,
+ AF_INET,
+ sha1_key=key,
+ bfd_key_id=self.vpp_session.bfd_key_id,
+ )
bfd_session_up(self)
for dummy in range(self.test_session.detect_mult * 2):
p = wait_for_bfd_packet(self)
@@ -2439,22 +2645,26 @@ class BFDAuthOnOffTestCase(VppTestCase):
self.assert_equal(p[BFD].state, BFDState.up, BFDState)
self.test_session.send_packet()
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events")
def test_auth_change_key_delayed(self):
- """ change auth key without disturbing session state (delayed) """
+ """change auth key without disturbing session state (delayed)"""
key1 = self.factory.create_random_key(self)
key1.add_vpp_config()
key2 = self.factory.create_random_key(self)
key2.add_vpp_config()
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip4, sha1_key=key1)
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key1
+ )
self.vpp_session.add_vpp_config()
self.vpp_session.admin_up()
self.test_session = BFDTestSession(
- self, self.pg0, AF_INET, sha1_key=key1,
- bfd_key_id=self.vpp_session.bfd_key_id)
+ self,
+ self.pg0,
+ AF_INET,
+ sha1_key=key1,
+ bfd_key_id=self.vpp_session.bfd_key_id,
+ )
bfd_session_up(self)
for dummy in range(self.test_session.detect_mult * 2):
p = wait_for_bfd_packet(self)
@@ -2473,13 +2683,13 @@ class BFDAuthOnOffTestCase(VppTestCase):
self.assert_equal(p[BFD].state, BFDState.up, BFDState)
self.test_session.send_packet()
self.assert_equal(self.vpp_session.state, BFDState.up, BFDState)
- self.assert_equal(len(self.vapi.collect_events()), 0,
- "number of bfd events")
+ self.assert_equal(len(self.vapi.collect_events()), 0, "number of bfd events")
@tag_run_solo
class BFDCLITestCase(VppTestCase):
- """Bidirectional Forwarding Detection (BFD) (CLI) """
+ """Bidirectional Forwarding Detection (BFD) (CLI)"""
+
pg0 = None
@classmethod
@@ -2516,52 +2726,54 @@ class BFDCLITestCase(VppTestCase):
super(BFDCLITestCase, self).tearDown()
def cli_verify_no_response(self, cli):
- """ execute a CLI, asserting that the response is empty """
- self.assert_equal(self.vapi.cli(cli),
- "",
- "CLI command response")
+ """execute a CLI, asserting that the response is empty"""
+ self.assert_equal(self.vapi.cli(cli), "", "CLI command response")
def cli_verify_response(self, cli, expected):
- """ execute a CLI, asserting that the response matches expectation """
+ """execute a CLI, asserting that the response matches expectation"""
try:
reply = self.vapi.cli(cli)
except CliFailedCommandError as cli_error:
reply = str(cli_error)
- self.assert_equal(reply.strip(),
- expected,
- "CLI command response")
+ self.assert_equal(reply.strip(), expected, "CLI command response")
def test_show(self):
- """ show commands """
+ """show commands"""
k1 = self.factory.create_random_key(self)
k1.add_vpp_config()
k2 = self.factory.create_random_key(
- self, auth_type=BFDAuthType.meticulous_keyed_sha1)
+ self, auth_type=BFDAuthType.meticulous_keyed_sha1
+ )
k2.add_vpp_config()
s1 = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
s1.add_vpp_config()
- s2 = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip6, af=AF_INET6,
- sha1_key=k2)
+ s2 = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, sha1_key=k2
+ )
s2.add_vpp_config()
self.logger.info(self.vapi.ppcli("show bfd keys"))
self.logger.info(self.vapi.ppcli("show bfd sessions"))
self.logger.info(self.vapi.ppcli("show bfd"))
def test_set_del_sha1_key(self):
- """ set/delete SHA1 auth key """
+ """set/delete SHA1 auth key"""
k = self.factory.create_random_key(self)
self.registry.register(k, self.logger)
self.cli_verify_no_response(
- "bfd key set conf-key-id %s type keyed-sha1 secret %s" %
- (k.conf_key_id,
- "".join("{:02x}".format(scapy.compat.orb(c)) for c in k.key)))
+ "bfd key set conf-key-id %s type keyed-sha1 secret %s"
+ % (
+ k.conf_key_id,
+ "".join("{:02x}".format(scapy.compat.orb(c)) for c in k.key),
+ )
+ )
self.assertTrue(k.query_vpp_config())
self.vpp_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip4, sha1_key=k)
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=k
+ )
self.vpp_session.add_vpp_config()
- self.test_session = \
- BFDTestSession(self, self.pg0, AF_INET, sha1_key=k,
- bfd_key_id=self.vpp_session.bfd_key_id)
+ self.test_session = BFDTestSession(
+ self, self.pg0, AF_INET, sha1_key=k, bfd_key_id=self.vpp_session.bfd_key_id
+ )
self.vapi.want_bfd_events()
bfd_session_up(self)
bfd_session_down(self)
@@ -2569,37 +2781,43 @@ class BFDCLITestCase(VppTestCase):
# is in-use
k2 = self.factory.create_random_key(self)
self.cli_verify_response(
- "bfd key set conf-key-id %s type keyed-sha1 secret %s" %
- (k.conf_key_id,
- "".join("{:02x}".format(scapy.compat.orb(c)) for c in k2.key)),
+ "bfd key set conf-key-id %s type keyed-sha1 secret %s"
+ % (
+ k.conf_key_id,
+ "".join("{:02x}".format(scapy.compat.orb(c)) for c in k2.key),
+ ),
"bfd key set: `bfd_auth_set_key' API call failed, "
- "rv=-103:BFD object in use")
+ "rv=-103:BFD object in use",
+ )
# manipulating the session using old secret should still work
bfd_session_up(self)
bfd_session_down(self)
self.vpp_session.remove_vpp_config()
- self.cli_verify_no_response(
- "bfd key del conf-key-id %s" % k.conf_key_id)
+ self.cli_verify_no_response("bfd key del conf-key-id %s" % k.conf_key_id)
self.assertFalse(k.query_vpp_config())
def test_set_del_meticulous_sha1_key(self):
- """ set/delete meticulous SHA1 auth key """
+ """set/delete meticulous SHA1 auth key"""
k = self.factory.create_random_key(
- self, auth_type=BFDAuthType.meticulous_keyed_sha1)
+ self, auth_type=BFDAuthType.meticulous_keyed_sha1
+ )
self.registry.register(k, self.logger)
self.cli_verify_no_response(
- "bfd key set conf-key-id %s type meticulous-keyed-sha1 secret %s" %
- (k.conf_key_id,
- "".join("{:02x}".format(scapy.compat.orb(c)) for c in k.key)))
+ "bfd key set conf-key-id %s type meticulous-keyed-sha1 secret %s"
+ % (
+ k.conf_key_id,
+ "".join("{:02x}".format(scapy.compat.orb(c)) for c in k.key),
+ )
+ )
self.assertTrue(k.query_vpp_config())
- self.vpp_session = VppBFDUDPSession(self, self.pg0,
- self.pg0.remote_ip6, af=AF_INET6,
- sha1_key=k)
+ self.vpp_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, sha1_key=k
+ )
self.vpp_session.add_vpp_config()
self.vpp_session.admin_up()
- self.test_session = \
- BFDTestSession(self, self.pg0, AF_INET6, sha1_key=k,
- bfd_key_id=self.vpp_session.bfd_key_id)
+ self.test_session = BFDTestSession(
+ self, self.pg0, AF_INET6, sha1_key=k, bfd_key_id=self.vpp_session.bfd_key_id
+ )
self.vapi.want_bfd_events()
bfd_session_up(self)
bfd_session_down(self)
@@ -2607,299 +2825,409 @@ class BFDCLITestCase(VppTestCase):
# is in-use
k2 = self.factory.create_random_key(self)
self.cli_verify_response(
- "bfd key set conf-key-id %s type keyed-sha1 secret %s" %
- (k.conf_key_id,
- "".join("{:02x}".format(scapy.compat.orb(c)) for c in k2.key)),
+ "bfd key set conf-key-id %s type keyed-sha1 secret %s"
+ % (
+ k.conf_key_id,
+ "".join("{:02x}".format(scapy.compat.orb(c)) for c in k2.key),
+ ),
"bfd key set: `bfd_auth_set_key' API call failed, "
- "rv=-103:BFD object in use")
+ "rv=-103:BFD object in use",
+ )
# manipulating the session using old secret should still work
bfd_session_up(self)
bfd_session_down(self)
self.vpp_session.remove_vpp_config()
- self.cli_verify_no_response(
- "bfd key del conf-key-id %s" % k.conf_key_id)
+ self.cli_verify_no_response("bfd key del conf-key-id %s" % k.conf_key_id)
self.assertFalse(k.query_vpp_config())
def test_add_mod_del_bfd_udp(self):
- """ create/modify/delete IPv4 BFD UDP session """
- vpp_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip4)
+ """create/modify/delete IPv4 BFD UDP session"""
+ vpp_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
self.registry.register(vpp_session, self.logger)
- cli_add_cmd = "bfd udp session add interface %s local-addr %s " \
- "peer-addr %s desired-min-tx %s required-min-rx %s "\
- "detect-mult %s" % (self.pg0.name, self.pg0.local_ip4,
- self.pg0.remote_ip4,
- vpp_session.desired_min_tx,
- vpp_session.required_min_rx,
- vpp_session.detect_mult)
+ cli_add_cmd = (
+ "bfd udp session add interface %s local-addr %s "
+ "peer-addr %s desired-min-tx %s required-min-rx %s "
+ "detect-mult %s"
+ % (
+ self.pg0.name,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ vpp_session.desired_min_tx,
+ vpp_session.required_min_rx,
+ vpp_session.detect_mult,
+ )
+ )
self.cli_verify_no_response(cli_add_cmd)
# 2nd add should fail
self.cli_verify_response(
cli_add_cmd,
"bfd udp session add: `bfd_add_add_session' API call"
- " failed, rv=-101:Duplicate BFD object")
+ " failed, rv=-101:Duplicate BFD object",
+ )
verify_bfd_session_config(self, vpp_session)
mod_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip4,
+ self,
+ self.pg0,
+ self.pg0.remote_ip4,
required_min_rx=2 * vpp_session.required_min_rx,
desired_min_tx=3 * vpp_session.desired_min_tx,
- detect_mult=4 * vpp_session.detect_mult)
+ detect_mult=4 * vpp_session.detect_mult,
+ )
self.cli_verify_no_response(
"bfd udp session mod interface %s local-addr %s peer-addr %s "
- "desired-min-tx %s required-min-rx %s detect-mult %s" %
- (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4,
- mod_session.desired_min_tx, mod_session.required_min_rx,
- mod_session.detect_mult))
+ "desired-min-tx %s required-min-rx %s detect-mult %s"
+ % (
+ self.pg0.name,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ mod_session.desired_min_tx,
+ mod_session.required_min_rx,
+ mod_session.detect_mult,
+ )
+ )
verify_bfd_session_config(self, mod_session)
- cli_del_cmd = "bfd udp session del interface %s local-addr %s "\
- "peer-addr %s" % (self.pg0.name,
- self.pg0.local_ip4, self.pg0.remote_ip4)
+ cli_del_cmd = (
+ "bfd udp session del interface %s local-addr %s "
+ "peer-addr %s" % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4)
+ )
self.cli_verify_no_response(cli_del_cmd)
# 2nd del is expected to fail
self.cli_verify_response(
- cli_del_cmd, "bfd udp session del: `bfd_udp_del_session' API call"
- " failed, rv=-102:No such BFD object")
+ cli_del_cmd,
+ "bfd udp session del: `bfd_udp_del_session' API call"
+ " failed, rv=-102:No such BFD object",
+ )
self.assertFalse(vpp_session.query_vpp_config())
def test_add_mod_del_bfd_udp6(self):
- """ create/modify/delete IPv6 BFD UDP session """
- vpp_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip6, af=AF_INET6)
+ """create/modify/delete IPv6 BFD UDP session"""
+ vpp_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip6, af=AF_INET6)
self.registry.register(vpp_session, self.logger)
- cli_add_cmd = "bfd udp session add interface %s local-addr %s " \
- "peer-addr %s desired-min-tx %s required-min-rx %s "\
- "detect-mult %s" % (self.pg0.name, self.pg0.local_ip6,
- self.pg0.remote_ip6,
- vpp_session.desired_min_tx,
- vpp_session.required_min_rx,
- vpp_session.detect_mult)
+ cli_add_cmd = (
+ "bfd udp session add interface %s local-addr %s "
+ "peer-addr %s desired-min-tx %s required-min-rx %s "
+ "detect-mult %s"
+ % (
+ self.pg0.name,
+ self.pg0.local_ip6,
+ self.pg0.remote_ip6,
+ vpp_session.desired_min_tx,
+ vpp_session.required_min_rx,
+ vpp_session.detect_mult,
+ )
+ )
self.cli_verify_no_response(cli_add_cmd)
# 2nd add should fail
self.cli_verify_response(
cli_add_cmd,
"bfd udp session add: `bfd_add_add_session' API call"
- " failed, rv=-101:Duplicate BFD object")
+ " failed, rv=-101:Duplicate BFD object",
+ )
verify_bfd_session_config(self, vpp_session)
mod_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip6, af=AF_INET6,
+ self,
+ self.pg0,
+ self.pg0.remote_ip6,
+ af=AF_INET6,
required_min_rx=2 * vpp_session.required_min_rx,
desired_min_tx=3 * vpp_session.desired_min_tx,
- detect_mult=4 * vpp_session.detect_mult)
+ detect_mult=4 * vpp_session.detect_mult,
+ )
self.cli_verify_no_response(
"bfd udp session mod interface %s local-addr %s peer-addr %s "
- "desired-min-tx %s required-min-rx %s detect-mult %s" %
- (self.pg0.name, self.pg0.local_ip6, self.pg0.remote_ip6,
- mod_session.desired_min_tx,
- mod_session.required_min_rx, mod_session.detect_mult))
+ "desired-min-tx %s required-min-rx %s detect-mult %s"
+ % (
+ self.pg0.name,
+ self.pg0.local_ip6,
+ self.pg0.remote_ip6,
+ mod_session.desired_min_tx,
+ mod_session.required_min_rx,
+ mod_session.detect_mult,
+ )
+ )
verify_bfd_session_config(self, mod_session)
- cli_del_cmd = "bfd udp session del interface %s local-addr %s "\
- "peer-addr %s" % (self.pg0.name,
- self.pg0.local_ip6, self.pg0.remote_ip6)
+ cli_del_cmd = (
+ "bfd udp session del interface %s local-addr %s "
+ "peer-addr %s" % (self.pg0.name, self.pg0.local_ip6, self.pg0.remote_ip6)
+ )
self.cli_verify_no_response(cli_del_cmd)
# 2nd del is expected to fail
self.cli_verify_response(
cli_del_cmd,
"bfd udp session del: `bfd_udp_del_session' API call"
- " failed, rv=-102:No such BFD object")
+ " failed, rv=-102:No such BFD object",
+ )
self.assertFalse(vpp_session.query_vpp_config())
def test_add_mod_del_bfd_udp_auth(self):
- """ create/modify/delete IPv4 BFD UDP session (authenticated) """
+ """create/modify/delete IPv4 BFD UDP session (authenticated)"""
key = self.factory.create_random_key(self)
key.add_vpp_config()
vpp_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip4, sha1_key=key)
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
self.registry.register(vpp_session, self.logger)
- cli_add_cmd = "bfd udp session add interface %s local-addr %s " \
- "peer-addr %s desired-min-tx %s required-min-rx %s "\
- "detect-mult %s conf-key-id %s bfd-key-id %s"\
- % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4,
- vpp_session.desired_min_tx, vpp_session.required_min_rx,
- vpp_session.detect_mult, key.conf_key_id,
- vpp_session.bfd_key_id)
+ cli_add_cmd = (
+ "bfd udp session add interface %s local-addr %s "
+ "peer-addr %s desired-min-tx %s required-min-rx %s "
+ "detect-mult %s conf-key-id %s bfd-key-id %s"
+ % (
+ self.pg0.name,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ vpp_session.desired_min_tx,
+ vpp_session.required_min_rx,
+ vpp_session.detect_mult,
+ key.conf_key_id,
+ vpp_session.bfd_key_id,
+ )
+ )
self.cli_verify_no_response(cli_add_cmd)
# 2nd add should fail
self.cli_verify_response(
cli_add_cmd,
"bfd udp session add: `bfd_add_add_session' API call"
- " failed, rv=-101:Duplicate BFD object")
+ " failed, rv=-101:Duplicate BFD object",
+ )
verify_bfd_session_config(self, vpp_session)
mod_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip4, sha1_key=key,
+ self,
+ self.pg0,
+ self.pg0.remote_ip4,
+ sha1_key=key,
bfd_key_id=vpp_session.bfd_key_id,
required_min_rx=2 * vpp_session.required_min_rx,
desired_min_tx=3 * vpp_session.desired_min_tx,
- detect_mult=4 * vpp_session.detect_mult)
+ detect_mult=4 * vpp_session.detect_mult,
+ )
self.cli_verify_no_response(
"bfd udp session mod interface %s local-addr %s peer-addr %s "
- "desired-min-tx %s required-min-rx %s detect-mult %s" %
- (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4,
- mod_session.desired_min_tx,
- mod_session.required_min_rx, mod_session.detect_mult))
+ "desired-min-tx %s required-min-rx %s detect-mult %s"
+ % (
+ self.pg0.name,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ mod_session.desired_min_tx,
+ mod_session.required_min_rx,
+ mod_session.detect_mult,
+ )
+ )
verify_bfd_session_config(self, mod_session)
- cli_del_cmd = "bfd udp session del interface %s local-addr %s "\
- "peer-addr %s" % (self.pg0.name,
- self.pg0.local_ip4, self.pg0.remote_ip4)
+ cli_del_cmd = (
+ "bfd udp session del interface %s local-addr %s "
+ "peer-addr %s" % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4)
+ )
self.cli_verify_no_response(cli_del_cmd)
# 2nd del is expected to fail
self.cli_verify_response(
cli_del_cmd,
"bfd udp session del: `bfd_udp_del_session' API call"
- " failed, rv=-102:No such BFD object")
+ " failed, rv=-102:No such BFD object",
+ )
self.assertFalse(vpp_session.query_vpp_config())
def test_add_mod_del_bfd_udp6_auth(self):
- """ create/modify/delete IPv6 BFD UDP session (authenticated) """
+ """create/modify/delete IPv6 BFD UDP session (authenticated)"""
key = self.factory.create_random_key(
- self, auth_type=BFDAuthType.meticulous_keyed_sha1)
+ self, auth_type=BFDAuthType.meticulous_keyed_sha1
+ )
key.add_vpp_config()
vpp_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, sha1_key=key)
+ self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, sha1_key=key
+ )
self.registry.register(vpp_session, self.logger)
- cli_add_cmd = "bfd udp session add interface %s local-addr %s " \
- "peer-addr %s desired-min-tx %s required-min-rx %s "\
- "detect-mult %s conf-key-id %s bfd-key-id %s" \
- % (self.pg0.name, self.pg0.local_ip6, self.pg0.remote_ip6,
- vpp_session.desired_min_tx, vpp_session.required_min_rx,
- vpp_session.detect_mult, key.conf_key_id,
- vpp_session.bfd_key_id)
+ cli_add_cmd = (
+ "bfd udp session add interface %s local-addr %s "
+ "peer-addr %s desired-min-tx %s required-min-rx %s "
+ "detect-mult %s conf-key-id %s bfd-key-id %s"
+ % (
+ self.pg0.name,
+ self.pg0.local_ip6,
+ self.pg0.remote_ip6,
+ vpp_session.desired_min_tx,
+ vpp_session.required_min_rx,
+ vpp_session.detect_mult,
+ key.conf_key_id,
+ vpp_session.bfd_key_id,
+ )
+ )
self.cli_verify_no_response(cli_add_cmd)
# 2nd add should fail
self.cli_verify_response(
cli_add_cmd,
"bfd udp session add: `bfd_add_add_session' API call"
- " failed, rv=-101:Duplicate BFD object")
+ " failed, rv=-101:Duplicate BFD object",
+ )
verify_bfd_session_config(self, vpp_session)
mod_session = VppBFDUDPSession(
- self, self.pg0, self.pg0.remote_ip6, af=AF_INET6, sha1_key=key,
+ self,
+ self.pg0,
+ self.pg0.remote_ip6,
+ af=AF_INET6,
+ sha1_key=key,
bfd_key_id=vpp_session.bfd_key_id,
required_min_rx=2 * vpp_session.required_min_rx,
desired_min_tx=3 * vpp_session.desired_min_tx,
- detect_mult=4 * vpp_session.detect_mult)
+ detect_mult=4 * vpp_session.detect_mult,
+ )
self.cli_verify_no_response(
"bfd udp session mod interface %s local-addr %s peer-addr %s "
- "desired-min-tx %s required-min-rx %s detect-mult %s" %
- (self.pg0.name, self.pg0.local_ip6, self.pg0.remote_ip6,
- mod_session.desired_min_tx,
- mod_session.required_min_rx, mod_session.detect_mult))
+ "desired-min-tx %s required-min-rx %s detect-mult %s"
+ % (
+ self.pg0.name,
+ self.pg0.local_ip6,
+ self.pg0.remote_ip6,
+ mod_session.desired_min_tx,
+ mod_session.required_min_rx,
+ mod_session.detect_mult,
+ )
+ )
verify_bfd_session_config(self, mod_session)
- cli_del_cmd = "bfd udp session del interface %s local-addr %s "\
- "peer-addr %s" % (self.pg0.name,
- self.pg0.local_ip6, self.pg0.remote_ip6)
+ cli_del_cmd = (
+ "bfd udp session del interface %s local-addr %s "
+ "peer-addr %s" % (self.pg0.name, self.pg0.local_ip6, self.pg0.remote_ip6)
+ )
self.cli_verify_no_response(cli_del_cmd)
# 2nd del is expected to fail
self.cli_verify_response(
cli_del_cmd,
"bfd udp session del: `bfd_udp_del_session' API call"
- " failed, rv=-102:No such BFD object")
+ " failed, rv=-102:No such BFD object",
+ )
self.assertFalse(vpp_session.query_vpp_config())
def test_auth_on_off(self):
- """ turn authentication on and off """
+ """turn authentication on and off"""
key = self.factory.create_random_key(
- self, auth_type=BFDAuthType.meticulous_keyed_sha1)
+ self, auth_type=BFDAuthType.meticulous_keyed_sha1
+ )
key.add_vpp_config()
session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
- auth_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4,
- sha1_key=key)
+ auth_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
session.add_vpp_config()
- cli_activate = \
- "bfd udp session auth activate interface %s local-addr %s "\
- "peer-addr %s conf-key-id %s bfd-key-id %s"\
- % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4,
- key.conf_key_id, auth_session.bfd_key_id)
+ cli_activate = (
+ "bfd udp session auth activate interface %s local-addr %s "
+ "peer-addr %s conf-key-id %s bfd-key-id %s"
+ % (
+ self.pg0.name,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ key.conf_key_id,
+ auth_session.bfd_key_id,
+ )
+ )
self.cli_verify_no_response(cli_activate)
verify_bfd_session_config(self, auth_session)
self.cli_verify_no_response(cli_activate)
verify_bfd_session_config(self, auth_session)
- cli_deactivate = \
- "bfd udp session auth deactivate interface %s local-addr %s "\
- "peer-addr %s "\
- % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4)
+ cli_deactivate = (
+ "bfd udp session auth deactivate interface %s local-addr %s "
+ "peer-addr %s " % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4)
+ )
self.cli_verify_no_response(cli_deactivate)
verify_bfd_session_config(self, session)
self.cli_verify_no_response(cli_deactivate)
verify_bfd_session_config(self, session)
def test_auth_on_off_delayed(self):
- """ turn authentication on and off (delayed) """
+ """turn authentication on and off (delayed)"""
key = self.factory.create_random_key(
- self, auth_type=BFDAuthType.meticulous_keyed_sha1)
+ self, auth_type=BFDAuthType.meticulous_keyed_sha1
+ )
key.add_vpp_config()
session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
- auth_session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4,
- sha1_key=key)
+ auth_session = VppBFDUDPSession(
+ self, self.pg0, self.pg0.remote_ip4, sha1_key=key
+ )
session.add_vpp_config()
- cli_activate = \
- "bfd udp session auth activate interface %s local-addr %s "\
- "peer-addr %s conf-key-id %s bfd-key-id %s delayed yes"\
- % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4,
- key.conf_key_id, auth_session.bfd_key_id)
+ cli_activate = (
+ "bfd udp session auth activate interface %s local-addr %s "
+ "peer-addr %s conf-key-id %s bfd-key-id %s delayed yes"
+ % (
+ self.pg0.name,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ key.conf_key_id,
+ auth_session.bfd_key_id,
+ )
+ )
self.cli_verify_no_response(cli_activate)
verify_bfd_session_config(self, auth_session)
self.cli_verify_no_response(cli_activate)
verify_bfd_session_config(self, auth_session)
- cli_deactivate = \
- "bfd udp session auth deactivate interface %s local-addr %s "\
- "peer-addr %s delayed yes"\
+ cli_deactivate = (
+ "bfd udp session auth deactivate interface %s local-addr %s "
+ "peer-addr %s delayed yes"
% (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4)
+ )
self.cli_verify_no_response(cli_deactivate)
verify_bfd_session_config(self, session)
self.cli_verify_no_response(cli_deactivate)
verify_bfd_session_config(self, session)
def test_admin_up_down(self):
- """ put session admin-up and admin-down """
+ """put session admin-up and admin-down"""
session = VppBFDUDPSession(self, self.pg0, self.pg0.remote_ip4)
session.add_vpp_config()
- cli_down = \
- "bfd udp session set-flags admin down interface %s local-addr %s "\
- "peer-addr %s "\
- % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4)
- cli_up = \
- "bfd udp session set-flags admin up interface %s local-addr %s "\
- "peer-addr %s "\
- % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4)
+ cli_down = (
+ "bfd udp session set-flags admin down interface %s local-addr %s "
+ "peer-addr %s " % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4)
+ )
+ cli_up = (
+ "bfd udp session set-flags admin up interface %s local-addr %s "
+ "peer-addr %s " % (self.pg0.name, self.pg0.local_ip4, self.pg0.remote_ip4)
+ )
self.cli_verify_no_response(cli_down)
verify_bfd_session_config(self, session, state=BFDState.admin_down)
self.cli_verify_no_response(cli_up)
verify_bfd_session_config(self, session, state=BFDState.down)
def test_set_del_udp_echo_source(self):
- """ set/del udp echo source """
+ """set/del udp echo source"""
self.create_loopback_interfaces(1)
self.loopback0 = self.lo_interfaces[0]
self.loopback0.admin_up()
- self.cli_verify_response("show bfd echo-source",
- "UDP echo source is not set.")
+ self.cli_verify_response("show bfd echo-source", "UDP echo source is not set.")
cli_set = "bfd udp echo-source set interface %s" % self.loopback0.name
self.cli_verify_no_response(cli_set)
- self.cli_verify_response("show bfd echo-source",
- "UDP echo source is: %s\n"
- "IPv4 address usable as echo source: none\n"
- "IPv6 address usable as echo source: none" %
- self.loopback0.name)
+ self.cli_verify_response(
+ "show bfd echo-source",
+ "UDP echo source is: %s\n"
+ "IPv4 address usable as echo source: none\n"
+ "IPv6 address usable as echo source: none" % self.loopback0.name,
+ )
self.loopback0.config_ip4()
- echo_ip4 = str(ipaddress.IPv4Address(int(ipaddress.IPv4Address(
- self.loopback0.local_ip4)) ^ 1))
- self.cli_verify_response("show bfd echo-source",
- "UDP echo source is: %s\n"
- "IPv4 address usable as echo source: %s\n"
- "IPv6 address usable as echo source: none" %
- (self.loopback0.name, echo_ip4))
- echo_ip6 = str(ipaddress.IPv6Address(int(ipaddress.IPv6Address(
- self.loopback0.local_ip6)) ^ 1))
+ echo_ip4 = str(
+ ipaddress.IPv4Address(
+ int(ipaddress.IPv4Address(self.loopback0.local_ip4)) ^ 1
+ )
+ )
+ self.cli_verify_response(
+ "show bfd echo-source",
+ "UDP echo source is: %s\n"
+ "IPv4 address usable as echo source: %s\n"
+ "IPv6 address usable as echo source: none"
+ % (self.loopback0.name, echo_ip4),
+ )
+ echo_ip6 = str(
+ ipaddress.IPv6Address(
+ int(ipaddress.IPv6Address(self.loopback0.local_ip6)) ^ 1
+ )
+ )
self.loopback0.config_ip6()
- self.cli_verify_response("show bfd echo-source",
- "UDP echo source is: %s\n"
- "IPv4 address usable as echo source: %s\n"
- "IPv6 address usable as echo source: %s" %
- (self.loopback0.name, echo_ip4, echo_ip6))
+ self.cli_verify_response(
+ "show bfd echo-source",
+ "UDP echo source is: %s\n"
+ "IPv4 address usable as echo source: %s\n"
+ "IPv6 address usable as echo source: %s"
+ % (self.loopback0.name, echo_ip4, echo_ip6),
+ )
cli_del = "bfd udp echo-source del"
self.cli_verify_no_response(cli_del)
- self.cli_verify_response("show bfd echo-source",
- "UDP echo source is not set.")
+ self.cli_verify_response("show bfd echo-source", "UDP echo source is not set.")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_bier.py b/test/test_bier.py
index 7dd6a30f34b..f58449ef4c3 100644
--- a/test/test_bier.py
+++ b/test/test_bier.py
@@ -5,12 +5,27 @@ import unittest
from config import config
from framework import VppTestCase, VppTestRunner
from vpp_ip import DpoProto
-from vpp_ip_route import VppIpRoute, VppRoutePath, \
- VppMplsTable, VppIpMRoute, VppMRoutePath, VppIpTable, \
- MPLS_LABEL_INVALID, \
- VppMplsLabel, FibPathProto, FibPathType
-from vpp_bier import BIER_HDR_PAYLOAD, VppBierImp, VppBierDispEntry, \
- VppBierDispTable, VppBierTable, VppBierTableID, VppBierRoute
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ VppMplsTable,
+ VppIpMRoute,
+ VppMRoutePath,
+ VppIpTable,
+ MPLS_LABEL_INVALID,
+ VppMplsLabel,
+ FibPathProto,
+ FibPathType,
+)
+from vpp_bier import (
+ BIER_HDR_PAYLOAD,
+ VppBierImp,
+ VppBierDispEntry,
+ VppBierDispTable,
+ VppBierTable,
+ VppBierTableID,
+ VppBierRoute,
+)
from vpp_udp_encap import VppUdpEncap
from vpp_papi import VppEnum
@@ -26,10 +41,10 @@ NUM_PKTS = 67
class TestBFIB(VppTestCase):
- """ BIER FIB Test Case """
+ """BIER FIB Test Case"""
def test_bfib(self):
- """ BFIB Unit Tests """
+ """BFIB Unit Tests"""
error = self.vapi.cli("test bier")
if error:
@@ -38,7 +53,7 @@ class TestBFIB(VppTestCase):
class TestBier(VppTestCase):
- """ BIER Test Case """
+ """BIER Test Case"""
def setUp(self):
super(TestBier, self).setUp()
@@ -86,16 +101,17 @@ class TestBier(VppTestCase):
#
# A packet with no bits set gets dropped
#
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- MPLS(label=77, ttl=255) /
- BIER(length=hdr_len_id) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / MPLS(label=77, ttl=255)
+ / BIER(length=hdr_len_id)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
pkts = [p]
- self.send_and_assert_no_replies(self.pg0, pkts,
- "Empty Bit-String")
+ self.send_and_assert_no_replies(self.pg0, pkts, "Empty Bit-String")
#
# Add a BIER route for each bit-position in the table via a different
@@ -104,19 +120,32 @@ class TestBier(VppTestCase):
#
nh_routes = []
bier_routes = []
- for i in range(1, max_bp+1):
+ for i in range(1, max_bp + 1):
nh = "10.0.%d.%d" % (i / 255, i % 255)
nh_routes.append(
- VppIpRoute(self, nh, 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index,
- labels=[VppMplsLabel(2000+i)])]))
+ VppIpRoute(
+ self,
+ nh,
+ 32,
+ [
+ VppRoutePath(
+ self.pg1.remote_ip4,
+ self.pg1.sw_if_index,
+ labels=[VppMplsLabel(2000 + i)],
+ )
+ ],
+ )
+ )
nh_routes[-1].add_vpp_config()
bier_routes.append(
- VppBierRoute(self, bti, i,
- [VppRoutePath(nh, 0xffffffff,
- labels=[VppMplsLabel(100+i)])]))
+ VppBierRoute(
+ self,
+ bti,
+ i,
+ [VppRoutePath(nh, 0xFFFFFFFF, labels=[VppMplsLabel(100 + i)])],
+ )
+ )
bier_routes[-1].add_vpp_config()
#
@@ -125,13 +154,14 @@ class TestBier(VppTestCase):
pkt_sizes = [64, 1400]
for pkt_size in pkt_sizes:
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- MPLS(label=77, ttl=255) /
- BIER(length=hdr_len_id,
- BitString=scapy.compat.chb(255)*n_bytes) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(5) * pkt_size))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / MPLS(label=77, ttl=255)
+ / BIER(length=hdr_len_id, BitString=scapy.compat.chb(255) * n_bytes)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(5) * pkt_size)
+ )
pkts = p
self.pg0.add_stream(pkts)
@@ -150,7 +180,7 @@ class TestBier(VppTestCase):
bp = olabel.label - 2000
blabel = olabel[MPLS].payload
- self.assertEqual(blabel.label, 100+bp)
+ self.assertEqual(blabel.label, 100 + bp)
self.assertEqual(blabel.ttl, 254)
bier_hdr = blabel[MPLS].payload
@@ -165,11 +195,11 @@ class TestBier(VppTestCase):
self.assertEqual(bier_hdr.Proto, 5)
# The bit-string should consist only of the BP given by i.
- byte_array = [b'\0'] * (n_bytes)
+ byte_array = [b"\0"] * (n_bytes)
byte_val = scapy.compat.chb(1 << (bp - 1) % 8)
byte_pos = n_bytes - (((bp - 1) // 8) + 1)
byte_array[byte_pos] = byte_val
- bitstring = b''.join(byte_array)
+ bitstring = b"".join(byte_array)
self.assertEqual(len(bitstring), len(bier_hdr.BitString))
self.assertEqual(bitstring, bier_hdr.BitString)
@@ -223,39 +253,55 @@ class TestBier(VppTestCase):
#
pkts = []
for ii in range(257):
- pkts.append((Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- MPLS(label=77, ttl=255) /
- BIER(length=BIERLength.BIER_LEN_64,
- entropy=ii,
- BitString=scapy.compat.chb(255)*16) /
- IPv6(src=self.pg0.remote_ip6,
- dst=self.pg0.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw()))
+ pkts.append(
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / MPLS(label=77, ttl=255)
+ / BIER(
+ length=BIERLength.BIER_LEN_64,
+ entropy=ii,
+ BitString=scapy.compat.chb(255) * 16,
+ )
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
+ )
#
# 4 next hops
#
- nhs = [{'ip': "10.0.0.1", 'label': 201},
- {'ip': "10.0.0.2", 'label': 202},
- {'ip': "10.0.0.3", 'label': 203},
- {'ip': "10.0.0.4", 'label': 204}]
+ nhs = [
+ {"ip": "10.0.0.1", "label": 201},
+ {"ip": "10.0.0.2", "label": 202},
+ {"ip": "10.0.0.3", "label": 203},
+ {"ip": "10.0.0.4", "label": 204},
+ ]
for nh in nhs:
ipr = VppIpRoute(
- self, nh['ip'], 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index,
- labels=[VppMplsLabel(nh['label'])])])
+ self,
+ nh["ip"],
+ 32,
+ [
+ VppRoutePath(
+ self.pg1.remote_ip4,
+ self.pg1.sw_if_index,
+ labels=[VppMplsLabel(nh["label"])],
+ )
+ ],
+ )
ipr.add_vpp_config()
bier_route = VppBierRoute(
- self, bti, 1,
- [VppRoutePath(nhs[0]['ip'], 0xffffffff,
- labels=[VppMplsLabel(101)]),
- VppRoutePath(nhs[1]['ip'], 0xffffffff,
- labels=[VppMplsLabel(101)])])
+ self,
+ bti,
+ 1,
+ [
+ VppRoutePath(nhs[0]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]),
+ VppRoutePath(nhs[1]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]),
+ ],
+ )
bier_route.add_vpp_config()
rx = self.send_and_expect(self.pg0, pkts, self.pg1)
@@ -264,37 +310,38 @@ class TestBier(VppTestCase):
# we should have recieved a packet from each neighbor
#
for nh in nhs[:2]:
- self.assertTrue(sum(p[MPLS].label == nh['label'] for p in rx))
+ self.assertTrue(sum(p[MPLS].label == nh["label"] for p in rx))
#
# add the other paths
#
bier_route.update_paths(
- [VppRoutePath(nhs[0]['ip'], 0xffffffff,
- labels=[VppMplsLabel(101)]),
- VppRoutePath(nhs[1]['ip'], 0xffffffff,
- labels=[VppMplsLabel(101)]),
- VppRoutePath(nhs[2]['ip'], 0xffffffff,
- labels=[VppMplsLabel(101)]),
- VppRoutePath(nhs[3]['ip'], 0xffffffff,
- labels=[VppMplsLabel(101)])])
+ [
+ VppRoutePath(nhs[0]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]),
+ VppRoutePath(nhs[1]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]),
+ VppRoutePath(nhs[2]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]),
+ VppRoutePath(nhs[3]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)]),
+ ]
+ )
rx = self.send_and_expect(self.pg0, pkts, self.pg1)
for nh in nhs:
- self.assertTrue(sum(p[MPLS].label == nh['label'] for p in rx))
+ self.assertTrue(sum(p[MPLS].label == nh["label"] for p in rx))
#
# remove first two paths
#
- bier_route.remove_path(VppRoutePath(nhs[0]['ip'], 0xffffffff,
- labels=[VppMplsLabel(101)]))
- bier_route.remove_path(VppRoutePath(nhs[1]['ip'], 0xffffffff,
- labels=[VppMplsLabel(101)]))
+ bier_route.remove_path(
+ VppRoutePath(nhs[0]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)])
+ )
+ bier_route.remove_path(
+ VppRoutePath(nhs[1]["ip"], 0xFFFFFFFF, labels=[VppMplsLabel(101)])
+ )
rx = self.send_and_expect(self.pg0, pkts, self.pg1)
for nh in nhs[2:]:
- self.assertTrue(sum(p[MPLS].label == nh['label'] for p in rx))
+ self.assertTrue(sum(p[MPLS].label == nh["label"] for p in rx))
#
# remove the last of the paths, deleteing the entry
@@ -321,23 +368,39 @@ class TestBier(VppTestCase):
#
nh1 = "10.0.0.1"
nh2 = "10.0.0.2"
- ip_route_1 = VppIpRoute(self, nh1, 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index,
- labels=[VppMplsLabel(2001)])])
- ip_route_2 = VppIpRoute(self, nh2, 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index,
- labels=[VppMplsLabel(2002)])])
+ ip_route_1 = VppIpRoute(
+ self,
+ nh1,
+ 32,
+ [
+ VppRoutePath(
+ self.pg1.remote_ip4,
+ self.pg1.sw_if_index,
+ labels=[VppMplsLabel(2001)],
+ )
+ ],
+ )
+ ip_route_2 = VppIpRoute(
+ self,
+ nh2,
+ 32,
+ [
+ VppRoutePath(
+ self.pg1.remote_ip4,
+ self.pg1.sw_if_index,
+ labels=[VppMplsLabel(2002)],
+ )
+ ],
+ )
ip_route_1.add_vpp_config()
ip_route_2.add_vpp_config()
- bier_route_1 = VppBierRoute(self, bti, 1,
- [VppRoutePath(nh1, 0xffffffff,
- labels=[VppMplsLabel(101)])])
- bier_route_2 = VppBierRoute(self, bti, 2,
- [VppRoutePath(nh2, 0xffffffff,
- labels=[VppMplsLabel(102)])])
+ bier_route_1 = VppBierRoute(
+ self, bti, 1, [VppRoutePath(nh1, 0xFFFFFFFF, labels=[VppMplsLabel(101)])]
+ )
+ bier_route_2 = VppBierRoute(
+ self, bti, 2, [VppRoutePath(nh2, 0xFFFFFFFF, labels=[VppMplsLabel(102)])]
+ )
bier_route_1.add_vpp_config()
bier_route_2.add_vpp_config()
@@ -353,25 +416,33 @@ class TestBier(VppTestCase):
route_ing_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- paths=[VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(0xffffffff,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
- type=FibPathType.FIB_PATH_TYPE_BIER_IMP,
- bier_imp=bi.bi_index)])
+ paths=[
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ 0xFFFFFFFF,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ type=FibPathType.FIB_PATH_TYPE_BIER_IMP,
+ bier_imp=bi.bi_index,
+ ),
+ ],
+ )
route_ing_232_1_1_1.add_vpp_config()
#
# inject an IP packet. We expect it to be BIER encapped and
# replicated.
#
- p = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src="1.1.1.1", dst="232.1.1.1") /
- UDP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src="1.1.1.1", dst="232.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ )
self.pg0.add_stream([p])
self.pg_enable_capture(self.pg_interfaces)
@@ -425,20 +496,33 @@ class TestBier(VppTestCase):
# BIER route in table that's for-us
#
bier_route_1 = VppBierRoute(
- self, bti, 1,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
- nh_table_id=8)])
+ self,
+ bti,
+ 1,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ nh_table_id=8,
+ )
+ ],
+ )
bier_route_1.add_vpp_config()
#
# An entry in the disposition table
#
- bier_de_1 = VppBierDispEntry(self, bdt.id, 99,
- BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
- FibPathProto.FIB_PATH_NH_PROTO_BIER,
- "0.0.0.0", 0, rpf_id=8192)
+ bier_de_1 = VppBierDispEntry(
+ self,
+ bdt.id,
+ 99,
+ BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
+ FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ "0.0.0.0",
+ 0,
+ rpf_id=8192,
+ )
bier_de_1.add_vpp_config()
#
@@ -447,48 +531,68 @@ class TestBier(VppTestCase):
route_eg_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- paths=[VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ paths=[
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ )
+ ],
+ )
route_eg_232_1_1_1.add_vpp_config()
route_eg_232_1_1_1.update_rpf_id(8192)
#
# A packet with all bits set gets spat out to BP:1
#
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- MPLS(label=77, ttl=255) /
- BIER(length=BIERLength.BIER_LEN_256,
- BitString=scapy.compat.chb(255)*32,
- BFRID=99) /
- IP(src="1.1.1.1", dst="232.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / MPLS(label=77, ttl=255)
+ / BIER(
+ length=BIERLength.BIER_LEN_256,
+ BitString=scapy.compat.chb(255) * 32,
+ BFRID=99,
+ )
+ / IP(src="1.1.1.1", dst="232.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
self.send_and_expect(self.pg0, [p], self.pg1)
#
# A packet that does not match the Disposition entry gets dropped
#
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- MPLS(label=77, ttl=255) /
- BIER(length=BIERLength.BIER_LEN_256,
- BitString=scapy.compat.chb(255)*32,
- BFRID=77) /
- IP(src="1.1.1.1", dst="232.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw())
- self.send_and_assert_no_replies(self.pg0, p*2,
- "no matching disposition entry")
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / MPLS(label=77, ttl=255)
+ / BIER(
+ length=BIERLength.BIER_LEN_256,
+ BitString=scapy.compat.chb(255) * 32,
+ BFRID=77,
+ )
+ / IP(src="1.1.1.1", dst="232.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
+ self.send_and_assert_no_replies(
+ self.pg0, p * 2, "no matching disposition entry"
+ )
#
# Add the default route to the disposition table
#
- bier_de_2 = VppBierDispEntry(self, bdt.id, 0,
- BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
- FibPathProto.FIB_PATH_NH_PROTO_BIER,
- "0.0.0.0", 0, rpf_id=8192)
+ bier_de_2 = VppBierDispEntry(
+ self,
+ bdt.id,
+ 0,
+ BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
+ FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ "0.0.0.0",
+ 0,
+ rpf_id=8192,
+ )
bier_de_2.add_vpp_config()
#
@@ -506,30 +610,41 @@ class TestBier(VppTestCase):
route_eg_232_1_1_2 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.2", 32,
+ "232.1.1.2",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- paths=[VppMRoutePath(0xffffffff,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=DpoProto.DPO_PROTO_BIER,
- type=FibPathType.FIB_PATH_TYPE_BIER_IMP,
- bier_imp=bi.bi_index),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ paths=[
+ VppMRoutePath(
+ 0xFFFFFFFF,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=DpoProto.DPO_PROTO_BIER,
+ type=FibPathType.FIB_PATH_TYPE_BIER_IMP,
+ bier_imp=bi.bi_index,
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_eg_232_1_1_2.add_vpp_config()
route_eg_232_1_1_2.update_rpf_id(8192)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- MPLS(label=77, ttl=255) /
- BIER(length=BIERLength.BIER_LEN_256,
- BitString=scapy.compat.chb(255)*32,
- BFRID=77) /
- IP(src="1.1.1.1", dst="232.1.1.2") /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / MPLS(label=77, ttl=255)
+ / BIER(
+ length=BIERLength.BIER_LEN_256,
+ BitString=scapy.compat.chb(255) * 32,
+ BFRID=77,
+ )
+ / IP(src="1.1.1.1", dst="232.1.1.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
self.send_and_expect(self.pg0, [p], self.pg1)
def bier_e2e(self, hdr_len_id, n_bytes, max_bp):
- """ BIER end-to-end"""
+ """BIER end-to-end"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -541,9 +656,9 @@ class TestBier(VppTestCase):
bt = VppBierTable(self, bti, 77)
bt.add_vpp_config()
- lowest = [b'\0'] * (n_bytes)
+ lowest = [b"\0"] * (n_bytes)
lowest[-1] = scapy.compat.chb(1)
- highest = [b'\0'] * (n_bytes)
+ highest = [b"\0"] * (n_bytes)
highest[0] = scapy.compat.chb(128)
#
@@ -560,28 +675,42 @@ class TestBier(VppTestCase):
route_ing_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- paths=[VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(0xffffffff,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
- type=FibPathType.FIB_PATH_TYPE_BIER_IMP,
- bier_imp=bi_low.bi_index)])
+ paths=[
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ 0xFFFFFFFF,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ type=FibPathType.FIB_PATH_TYPE_BIER_IMP,
+ bier_imp=bi_low.bi_index,
+ ),
+ ],
+ )
route_ing_232_1_1_1.add_vpp_config()
route_ing_232_1_1_2 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.2", 32,
+ "232.1.1.2",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- paths=[VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(0xffffffff,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
- type=FibPathType.FIB_PATH_TYPE_BIER_IMP,
- bier_imp=bi_high.bi_index)])
+ paths=[
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ 0xFFFFFFFF,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ type=FibPathType.FIB_PATH_TYPE_BIER_IMP,
+ bier_imp=bi_high.bi_index,
+ ),
+ ],
+ )
route_ing_232_1_1_2.add_vpp_config()
#
@@ -595,33 +724,59 @@ class TestBier(VppTestCase):
# disp table 8.
#
bier_route_1 = VppBierRoute(
- self, bti, 1,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
- nh_table_id=8)])
+ self,
+ bti,
+ 1,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ nh_table_id=8,
+ )
+ ],
+ )
bier_route_1.add_vpp_config()
bier_route_max = VppBierRoute(
- self, bti, max_bp,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
- nh_table_id=8)])
+ self,
+ bti,
+ max_bp,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ nh_table_id=8,
+ )
+ ],
+ )
bier_route_max.add_vpp_config()
#
# An entry in the disposition table for sender 333
# lookup in VRF 10
#
- bier_de_1 = VppBierDispEntry(self, bdt.id, 333,
- BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
- FibPathProto.FIB_PATH_NH_PROTO_BIER,
- "0.0.0.0", 10, rpf_id=8192)
+ bier_de_1 = VppBierDispEntry(
+ self,
+ bdt.id,
+ 333,
+ BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
+ FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ "0.0.0.0",
+ 10,
+ rpf_id=8192,
+ )
bier_de_1.add_vpp_config()
- bier_de_1 = VppBierDispEntry(self, bdt.id, 334,
- BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
- FibPathProto.FIB_PATH_NH_PROTO_BIER,
- "0.0.0.0", 10, rpf_id=8193)
+ bier_de_1 = VppBierDispEntry(
+ self,
+ bdt.id,
+ 334,
+ BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
+ FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ "0.0.0.0",
+ 10,
+ rpf_id=8193,
+ )
bier_de_1.add_vpp_config()
#
@@ -631,21 +786,31 @@ class TestBier(VppTestCase):
route_eg_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
table_id=10,
- paths=[VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ paths=[
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ )
+ ],
+ )
route_eg_232_1_1_1.add_vpp_config()
route_eg_232_1_1_1.update_rpf_id(8192)
route_eg_232_1_1_2 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.2", 32,
+ "232.1.1.2",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
table_id=10,
- paths=[VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ paths=[
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ )
+ ],
+ )
route_eg_232_1_1_2.add_vpp_config()
route_eg_232_1_1_2.update_rpf_id(8193)
@@ -654,49 +819,51 @@ class TestBier(VppTestCase):
# replicated, then hit the disposition and be forwarded
# out of VRF 10, i.e. on pg1
#
- p = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src="1.1.1.1", dst="232.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(5) * 32))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src="1.1.1.1", dst="232.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(5) * 32)
+ )
- rx = self.send_and_expect(self.pg0, p*NUM_PKTS, self.pg1)
+ rx = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1)
self.assertEqual(rx[0][IP].src, "1.1.1.1")
self.assertEqual(rx[0][IP].dst, "232.1.1.1")
- p = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src="1.1.1.1", dst="232.1.1.2") /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(5) * 512))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src="1.1.1.1", dst="232.1.1.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(5) * 512)
+ )
- rx = self.send_and_expect(self.pg0, p*NUM_PKTS, self.pg1)
+ rx = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1)
self.assertEqual(rx[0][IP].src, "1.1.1.1")
self.assertEqual(rx[0][IP].dst, "232.1.1.2")
@unittest.skipUnless(config.extended, "part of extended tests")
def test_bier_e2e_1024(self):
- """ BIER end-to-end BSL:1024"""
+ """BIER end-to-end BSL:1024"""
self.bier_e2e(BIERLength.BIER_LEN_1024, 128, 1024)
@unittest.skipUnless(config.extended, "part of extended tests")
def test_bier_e2e_512(self):
- """ BIER end-to-end BSL:512"""
+ """BIER end-to-end BSL:512"""
self.bier_e2e(BIERLength.BIER_LEN_512, 64, 512)
@unittest.skipUnless(config.extended, "part of extended tests")
def test_bier_e2e_256(self):
- """ BIER end-to-end BSL:256"""
+ """BIER end-to-end BSL:256"""
self.bier_e2e(BIERLength.BIER_LEN_256, 32, 256)
@unittest.skipUnless(config.extended, "part of extended tests")
def test_bier_e2e_128(self):
- """ BIER end-to-end BSL:128"""
+ """BIER end-to-end BSL:128"""
self.bier_e2e(BIERLength.BIER_LEN_128, 16, 128)
def test_bier_e2e_64(self):
- """ BIER end-to-end BSL:64"""
+ """BIER end-to-end BSL:64"""
self.bier_e2e(BIERLength.BIER_LEN_64, 8, 64)
def test_bier_head_o_udp(self):
@@ -716,24 +883,36 @@ class TestBier(VppTestCase):
# 1 bit positions via 1 next hops
#
nh1 = "10.0.0.1"
- ip_route = VppIpRoute(self, nh1, 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index,
- labels=[VppMplsLabel(2001)])])
+ ip_route = VppIpRoute(
+ self,
+ nh1,
+ 32,
+ [
+ VppRoutePath(
+ self.pg1.remote_ip4,
+ self.pg1.sw_if_index,
+ labels=[VppMplsLabel(2001)],
+ )
+ ],
+ )
ip_route.add_vpp_config()
- udp_encap = VppUdpEncap(self,
- self.pg0.local_ip4,
- nh1,
- 330, 8138)
+ udp_encap = VppUdpEncap(self, self.pg0.local_ip4, nh1, 330, 8138)
udp_encap.add_vpp_config()
bier_route = VppBierRoute(
- self, bti, 1,
- [VppRoutePath("0.0.0.0",
- 0xFFFFFFFF,
- type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
- next_hop_id=udp_encap.id)])
+ self,
+ bti,
+ 1,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
+ next_hop_id=udp_encap.id,
+ )
+ ],
+ )
bier_route.add_vpp_config()
#
@@ -741,9 +920,9 @@ class TestBier(VppTestCase):
# only use the second, but creating 2 tests with a non-zero
# value index in the route add
#
- bi = VppBierImp(self, bti, 333, scapy.compat.chb(0xff) * 32)
+ bi = VppBierImp(self, bti, 333, scapy.compat.chb(0xFF) * 32)
bi.add_vpp_config()
- bi2 = VppBierImp(self, bti, 334, scapy.compat.chb(0xff) * 32)
+ bi2 = VppBierImp(self, bti, 334, scapy.compat.chb(0xFF) * 32)
bi2.add_vpp_config()
#
@@ -752,24 +931,32 @@ class TestBier(VppTestCase):
route_ing_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- paths=[VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(0xffffffff,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
- type=FibPathType.FIB_PATH_TYPE_BIER_IMP,
- bier_imp=bi2.bi_index)])
+ paths=[
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ 0xFFFFFFFF,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ type=FibPathType.FIB_PATH_TYPE_BIER_IMP,
+ bier_imp=bi2.bi_index,
+ ),
+ ],
+ )
route_ing_232_1_1_1.add_vpp_config()
#
# inject a packet an IP. We expect it to be BIER and UDP encapped,
#
- p = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src="1.1.1.1", dst="232.1.1.1") /
- UDP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src="1.1.1.1", dst="232.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ )
self.pg0.add_stream([p])
self.pg_enable_capture(self.pg_interfaces)
@@ -813,20 +1000,33 @@ class TestBier(VppTestCase):
# BIER route in table that's for-us
#
bier_route_1 = VppBierRoute(
- self, bti, 1,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
- nh_table_id=8)])
+ self,
+ bti,
+ 1,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ nh_table_id=8,
+ )
+ ],
+ )
bier_route_1.add_vpp_config()
#
# An entry in the disposition table
#
- bier_de_1 = VppBierDispEntry(self, bdt.id, 99,
- BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
- FibPathProto.FIB_PATH_NH_PROTO_BIER,
- "0.0.0.0", 0, rpf_id=8192)
+ bier_de_1 = VppBierDispEntry(
+ self,
+ bdt.id,
+ 99,
+ BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
+ FibPathProto.FIB_PATH_NH_PROTO_BIER,
+ "0.0.0.0",
+ 0,
+ rpf_id=8192,
+ )
bier_de_1.add_vpp_config()
#
@@ -835,29 +1035,38 @@ class TestBier(VppTestCase):
route_eg_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- paths=[VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ paths=[
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ )
+ ],
+ )
route_eg_232_1_1_1.add_vpp_config()
route_eg_232_1_1_1.update_rpf_id(8192)
#
# A packet with all bits set gets spat out to BP:1
#
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=333, dport=8138) /
- BIFT(sd=1, set=0, bsl=2, ttl=255) /
- BIER(length=BIERLength.BIER_LEN_256,
- BitString=scapy.compat.chb(255)*32,
- BFRID=99) /
- IP(src="1.1.1.1", dst="232.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=333, dport=8138)
+ / BIFT(sd=1, set=0, bsl=2, ttl=255)
+ / BIER(
+ length=BIERLength.BIER_LEN_256,
+ BitString=scapy.compat.chb(255) * 32,
+ BFRID=99,
+ )
+ / IP(src="1.1.1.1", dst="232.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
rx = self.send_and_expect(self.pg0, [p], self.pg1)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_bihash.py b/test/test_bihash.py
index 32eb4ff3a21..b57485a3e9a 100644
--- a/test/test_bihash.py
+++ b/test/test_bihash.py
@@ -8,7 +8,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
class TestBihash(VppTestCase):
- """ Bihash Test Cases """
+ """Bihash Test Cases"""
@classmethod
def setUpClass(cls):
@@ -28,48 +28,54 @@ class TestBihash(VppTestCase):
super(TestBihash, self).tearDown()
def test_bihash_unittest(self):
- """ Bihash Add/Del Test """
+ """Bihash Add/Del Test"""
error = self.vapi.cli("test bihash careful 0 verbose 0")
if error:
self.logger.critical(error)
- self.assertNotIn('failed', error)
+ self.assertNotIn("failed", error)
def test_bihash_thread(self):
- """ Bihash Thread Test """
+ """Bihash Thread Test"""
- error = self.vapi.cli("test bihash threads 2 nbuckets" +
- " 64000 careful 0 verbose 0")
+ error = self.vapi.cli(
+ "test bihash threads 2 nbuckets" + " 64000 careful 0 verbose 0"
+ )
if error:
self.logger.critical(error)
- self.assertNotIn('failed', error)
+ self.assertNotIn("failed", error)
def test_bihash_vec64(self):
- """ Bihash vec64 Test """
+ """Bihash vec64 Test"""
error = self.vapi.cli("test bihash vec64")
if error:
self.logger.critical(error)
- self.assertNotIn('failed', error)
+ self.assertNotIn("failed", error)
@unittest.skipUnless(config.gcov, "part of code coverage tests")
def test_bihash_coverage(self):
- """ Improve Code Coverage """
+ """Improve Code Coverage"""
- error = self.vapi.cli("test bihash nitems 10 ncycles 3" +
- "search 2 careful 1 verbose 2 non-random-keys")
+ error = self.vapi.cli(
+ "test bihash nitems 10 ncycles 3"
+ + "search 2 careful 1 verbose 2 non-random-keys"
+ )
if error:
self.logger.critical(error)
- self.assertNotIn('failed', error)
+ self.assertNotIn("failed", error)
- error = self.vapi.cli("test bihash nitems 10 nbuckets 1 ncycles 3" +
- "search 2 careful 1 verbose 2 non-random-keys")
+ error = self.vapi.cli(
+ "test bihash nitems 10 nbuckets 1 ncycles 3"
+ + "search 2 careful 1 verbose 2 non-random-keys"
+ )
if error:
self.logger.critical(error)
- self.assertNotIn('failed', error)
+ self.assertNotIn("failed", error)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_bond.py b/test/test_bond.py
index 5df86ae5b0f..159bae5fea0 100644
--- a/test/test_bond.py
+++ b/test/test_bond.py
@@ -13,15 +13,13 @@ from vpp_papi import MACAddress, VppEnum
class TestBondInterface(VppTestCase):
- """Bond Test Case
-
- """
+ """Bond Test Case"""
@classmethod
def setUpClass(cls):
super(TestBondInterface, cls).setUpClass()
# Test variables
- cls.pkts_per_burst = 257 # Number of packets per burst
+ cls.pkts_per_burst = 257 # Number of packets per burst
# create 3 pg interfaces
cls.create_pg_interfaces(range(4))
@@ -46,7 +44,7 @@ class TestBondInterface(VppTestCase):
self.logger.info(self.vapi.ppcli("show interface"))
def test_bond_traffic(self):
- """ Bond traffic test """
+ """Bond traffic test"""
# topology
#
@@ -69,12 +67,13 @@ class TestBondInterface(VppTestCase):
lb=VppEnum.vl_api_bond_lb_algo_t.BOND_API_LB_ALGO_L34,
numa_only=0,
use_custom_mac=1,
- mac_address=mac)
+ mac_address=mac,
+ )
bond0.add_vpp_config()
bond0.admin_up()
self.vapi.sw_interface_add_del_address(
- sw_if_index=bond0.sw_if_index,
- prefix="10.10.10.1/24")
+ sw_if_index=bond0.sw_if_index, prefix="10.10.10.1/24"
+ )
self.pg2.config_ip4()
self.pg2.resolve_arp()
@@ -98,29 +97,39 @@ class TestBondInterface(VppTestCase):
# generate a packet from pg2 -> BondEthernet0 -> pg1
# BondEthernet0 TX hashes this packet to pg1
- p2 = (Ether(src=bond0_mac, dst=self.pg2.local_mac) /
- IP(src=self.pg2.local_ip4, dst="10.10.10.12") /
- UDP(sport=1235, dport=1235) /
- Raw(b'\xa5' * 100))
+ p2 = (
+ Ether(src=bond0_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.local_ip4, dst="10.10.10.12")
+ / UDP(sport=1235, dport=1235)
+ / Raw(b"\xa5" * 100)
+ )
self.pg2.add_stream(p2)
# generate a packet from pg3 -> BondEthernet0 -> pg0
# BondEthernet0 TX hashes this packet to pg0
# notice the ip address and ports are different than p2 packet
- p3 = (Ether(src=bond0_mac, dst=self.pg3.local_mac) /
- IP(src=self.pg3.local_ip4, dst="10.10.10.11") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p3 = (
+ Ether(src=bond0_mac, dst=self.pg3.local_mac)
+ / IP(src=self.pg3.local_ip4, dst="10.10.10.11")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.pg3.add_stream(p3)
self.pg_enable_capture(self.pg_interfaces)
# set up the static arp entries pointing to the BondEthernet0 interface
# so that it does not try to resolve the ip address
- self.logger.info(self.vapi.cli(
- "set ip neighbor static BondEthernet0 10.10.10.12 abcd.abcd.0002"))
- self.logger.info(self.vapi.cli(
- "set ip neighbor static BondEthernet0 10.10.10.11 abcd.abcd.0004"))
+ self.logger.info(
+ self.vapi.cli(
+ "set ip neighbor static BondEthernet0 10.10.10.12 abcd.abcd.0002"
+ )
+ )
+ self.logger.info(
+ self.vapi.cli(
+ "set ip neighbor static BondEthernet0 10.10.10.11 abcd.abcd.0004"
+ )
+ )
# clear the interface counters
self.logger.info(self.vapi.cli("clear interfaces"))
@@ -166,14 +175,13 @@ class TestBondInterface(VppTestCase):
bond0.remove_vpp_config()
def test_bond_add_member(self):
- """ Bond add_member/detach member test """
+ """Bond add_member/detach member test"""
# create interface (BondEthernet0) and set bond mode to LACP
self.logger.info("create bond")
bond0 = VppBondInterface(
- self,
- mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP,
- enable_gso=0)
+ self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP, enable_gso=0
+ )
bond0.add_vpp_config()
bond0.admin_up()
@@ -187,15 +195,13 @@ class TestBondInterface(VppTestCase):
# add_member pg0 and pg1 to BondEthernet0
self.logger.info("bond add_member interface pg0 to BondEthernet0")
bond0.add_member_vpp_bond_interface(
- sw_if_index=self.pg0.sw_if_index,
- is_passive=0,
- is_long_timeout=0)
+ sw_if_index=self.pg0.sw_if_index, is_passive=0, is_long_timeout=0
+ )
self.logger.info("bond add_member interface pg1 to BondEthernet0")
bond0.add_member_vpp_bond_interface(
- sw_if_index=self.pg1.sw_if_index,
- is_passive=0,
- is_long_timeout=0)
+ sw_if_index=self.pg1.sw_if_index, is_passive=0, is_long_timeout=0
+ )
# verify both members in BondEthernet0
if_dump = self.vapi.sw_member_interface_dump(bond0.sw_if_index)
self.assertTrue(self.pg0.is_interface_config_in_dump(if_dump))
@@ -222,25 +228,27 @@ class TestBondInterface(VppTestCase):
bond0.remove_vpp_config()
def test_bond(self):
- """ Bond add/delete interface test """
+ """Bond add/delete interface test"""
self.logger.info("Bond add interfaces")
# create interface 1 (BondEthernet0)
bond0 = VppBondInterface(
- self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP)
+ self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP
+ )
bond0.add_vpp_config()
bond0.admin_up()
# create interface 2 (BondEthernet1)
bond1 = VppBondInterface(
- self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_XOR)
+ self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_XOR
+ )
bond1.add_vpp_config()
bond1.admin_up()
# verify both interfaces in the show
ifs = self.vapi.cli("show interface")
- self.assertIn('BondEthernet0', ifs)
- self.assertIn('BondEthernet1', ifs)
+ self.assertIn("BondEthernet0", ifs)
+ self.assertIn("BondEthernet1", ifs)
# verify they are in the dump also
if_dump = self.vapi.sw_bond_interface_dump(sw_if_index=0xFFFFFFFF)
@@ -255,10 +263,10 @@ class TestBondInterface(VppTestCase):
ifs = self.vapi.cli("show interface")
# verify BondEthernet0 still in the show
- self.assertIn('BondEthernet0', ifs)
+ self.assertIn("BondEthernet0", ifs)
# verify BondEthernet1 not in the show
- self.assertNotIn('BondEthernet1', ifs)
+ self.assertNotIn("BondEthernet1", ifs)
# verify BondEthernet1 is not in the dump
if_dump = self.vapi.sw_bond_interface_dump(sw_if_index=0xFFFFFFFF)
@@ -275,15 +283,14 @@ class TestBondInterface(VppTestCase):
# verify BondEthernet0 not in the show
ifs = self.vapi.cli("show interface")
- self.assertNotIn('BondEthernet0', ifs)
+ self.assertNotIn("BondEthernet0", ifs)
# verify BondEthernet0 is not in the dump
- if_dump = self.vapi.sw_bond_interface_dump(
- sw_if_index=bond0.sw_if_index)
+ if_dump = self.vapi.sw_bond_interface_dump(sw_if_index=bond0.sw_if_index)
self.assertFalse(bond0.is_interface_config_in_dump(if_dump))
def test_bond_link(self):
- """ Bond hw interface link state test """
+ """Bond hw interface link state test"""
# for convenience
bond_modes = VppEnum.vl_api_bond_mode_t
@@ -292,16 +299,17 @@ class TestBondInterface(VppTestCase):
# create interface 1 (BondEthernet0)
self.logger.info("Create bond interface")
# use round-robin mode to avoid negotiation required by LACP
- bond0 = VppBondInterface(self,
- mode=bond_modes.BOND_API_MODE_ROUND_ROBIN)
+ bond0 = VppBondInterface(self, mode=bond_modes.BOND_API_MODE_ROUND_ROBIN)
bond0.add_vpp_config()
# set bond admin up.
self.logger.info("set interface BondEthernet0 admin up")
bond0.admin_up()
# confirm link up
- bond0.assert_interface_state(intf_flags.IF_STATUS_API_FLAG_ADMIN_UP,
- intf_flags.IF_STATUS_API_FLAG_LINK_UP)
+ bond0.assert_interface_state(
+ intf_flags.IF_STATUS_API_FLAG_ADMIN_UP,
+ intf_flags.IF_STATUS_API_FLAG_LINK_UP,
+ )
# toggle bond admin state
self.logger.info("toggle interface BondEthernet0")
@@ -309,13 +317,15 @@ class TestBondInterface(VppTestCase):
bond0.admin_up()
# confirm link is still up
- bond0.assert_interface_state(intf_flags.IF_STATUS_API_FLAG_ADMIN_UP,
- intf_flags.IF_STATUS_API_FLAG_LINK_UP)
+ bond0.assert_interface_state(
+ intf_flags.IF_STATUS_API_FLAG_ADMIN_UP,
+ intf_flags.IF_STATUS_API_FLAG_LINK_UP,
+ )
# delete BondEthernet0
self.logger.info("Deleting BondEthernet0")
bond0.remove_vpp_config()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_buffers.py b/test/test_buffers.py
index f50f05c609a..01875526812 100644
--- a/test/test_buffers.py
+++ b/test/test_buffers.py
@@ -4,7 +4,7 @@ from framework import VppTestCase
class TestBuffers(VppTestCase):
- """ Buffer C Unit Tests """
+ """Buffer C Unit Tests"""
@classmethod
def setUpClass(cls):
@@ -21,9 +21,9 @@ class TestBuffers(VppTestCase):
super(TestBuffers, self).tearDown()
def test_linearize(self):
- """ Chained Buffer Linearization """
+ """Chained Buffer Linearization"""
error = self.vapi.cli("test chained-buffer-linearization")
if error:
self.logger.critical(error)
- self.assertNotIn('failed', error)
+ self.assertNotIn("failed", error)
diff --git a/test/test_cdp.py b/test/test_cdp.py
index 46751e81d86..da378dbebe3 100644
--- a/test/test_cdp.py
+++ b/test/test_cdp.py
@@ -4,8 +4,13 @@
from scapy.packet import Packet
from scapy.all import ShortField, StrField
from scapy.layers.l2 import Dot3, LLC, SNAP
-from scapy.contrib.cdp import CDPMsgDeviceID, CDPMsgSoftwareVersion, \
- CDPMsgPlatform, CDPMsgPortID, CDPv2_HDR
+from scapy.contrib.cdp import (
+ CDPMsgDeviceID,
+ CDPMsgSoftwareVersion,
+ CDPMsgPlatform,
+ CDPMsgPortID,
+ CDPv2_HDR,
+)
from framework import VppTestCase
from scapy.all import raw
@@ -25,18 +30,17 @@ CDP test.
class CustomTLV(Packet):
- """ Custom TLV protocol layer for scapy """
+ """Custom TLV protocol layer for scapy"""
fields_desc = [
ShortField("type", 0),
ShortField("length", 4),
- StrField("value", "")
-
+ StrField("value", ""),
]
class TestCDP(VppTestCase):
- """ CDP Test Case """
+ """CDP Test Case"""
nen_ptr = compile(r"not enabled")
cdp_ptr = compile(r"^([-\.\w]+)\s+([-\.\w]+)\s+([-\.\w]+)\s+([-\.\w]+)$")
@@ -95,8 +99,9 @@ class TestCDP(VppTestCase):
length = min(len(system), len(self.device_id))
self.assert_equal(port, self.port_id, "CDP received invalid port id")
- self.assert_equal(system[:length], self.device_id[:length],
- "CDP received invalid device id")
+ self.assert_equal(
+ system[:length], self.device_id[:length], "CDP received invalid device id"
+ )
def test_cdp_underflow_tlv(self):
self.send_bad_packet(3, ".")
@@ -109,7 +114,8 @@ class TestCDP(VppTestCase):
self.send_packet(self.create_bad_packet(l, v))
err = self.statistics.get_err_counter(
- '/err/cdp-input/cdp packets with bad TLVs')
+ "/err/cdp-input/cdp packets with bad TLVs"
+ )
self.assertTrue(err >= 1, "CDP didn't drop bad packet")
def send_packet(self, packet):
@@ -118,29 +124,30 @@ class TestCDP(VppTestCase):
self.pg_start()
def create_base_packet(self):
- packet = (Dot3(src=self.interface.remote_mac,
- dst="01:00:0c:cc:cc:cc") /
- LLC(dsap=0xaa, ssap=0xaa, ctrl=0x03) /
- SNAP()/CDPv2_HDR())
+ packet = (
+ Dot3(src=self.interface.remote_mac, dst="01:00:0c:cc:cc:cc")
+ / LLC(dsap=0xAA, ssap=0xAA, ctrl=0x03)
+ / SNAP()
+ / CDPv2_HDR()
+ )
return packet
def create_packet(self):
- packet = (self.create_base_packet() /
- CDPMsgDeviceID(val=self.device_id) /
- CDPMsgSoftwareVersion(val=self.version) /
- CDPMsgPortID(iface=self.port_id) /
- CDPMsgPlatform(val=self.platform))
+ packet = (
+ self.create_base_packet()
+ / CDPMsgDeviceID(val=self.device_id)
+ / CDPMsgSoftwareVersion(val=self.version)
+ / CDPMsgPortID(iface=self.port_id)
+ / CDPMsgPlatform(val=self.platform)
+ )
return packet
def create_bad_packet(self, tl=4, tv=""):
- packet = (self.create_base_packet() /
- CustomTLV(type=1,
- length=tl,
- value=tv))
+ packet = self.create_base_packet() / CustomTLV(type=1, length=tl, value=tv)
return packet
def process_cli(self, exp, ptr):
- for line in self.vapi.cli(exp).split('\n')[1:]:
+ for line in self.vapi.cli(exp).split("\n")[1:]:
m = ptr.match(line.strip())
if m:
yield m.groups()
diff --git a/test/test_classifier.py b/test/test_classifier.py
index 9f0fdbf587a..068561230ea 100644
--- a/test/test_classifier.py
+++ b/test/test_classifier.py
@@ -19,7 +19,7 @@ from vpp_papi import VppEnum
# Tests split to different test case classes because of issue reported in
# ticket VPP-1336
class TestClassifierIP(TestClassifier):
- """ Classifier IP Test Case """
+ """Classifier IP Test Case"""
@classmethod
def setUpClass(cls):
@@ -30,7 +30,7 @@ class TestClassifierIP(TestClassifier):
super(TestClassifierIP, cls).tearDownClass()
def test_iacl_src_ip(self):
- """ Source IP iACL test
+ """Source IP iACL test
Test scenario for basic IP ACL with source IP
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -42,11 +42,11 @@ class TestClassifierIP(TestClassifier):
pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes)
self.pg0.add_stream(pkts)
- key = 'ip_src'
- self.create_classify_table(key, self.build_ip_mask(src_ip='ffffffff'))
+ key = "ip_src"
+ self.create_classify_table(key, self.build_ip_mask(src_ip="ffffffff"))
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_ip_match(src_ip=self.pg0.remote_ip4))
+ self.acl_tbl_idx.get(key), self.build_ip_match(src_ip=self.pg0.remote_ip4)
+ )
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -60,7 +60,7 @@ class TestClassifierIP(TestClassifier):
self.pg3.assert_nothing_captured(remark="packets forwarded")
def test_iacl_dst_ip(self):
- """ Destination IP iACL test
+ """Destination IP iACL test
Test scenario for basic IP ACL with destination IP
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -72,11 +72,11 @@ class TestClassifierIP(TestClassifier):
pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes)
self.pg0.add_stream(pkts)
- key = 'ip_dst'
- self.create_classify_table(key, self.build_ip_mask(dst_ip='ffffffff'))
+ key = "ip_dst"
+ self.create_classify_table(key, self.build_ip_mask(dst_ip="ffffffff"))
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_ip_match(dst_ip=self.pg1.remote_ip4))
+ self.acl_tbl_idx.get(key), self.build_ip_match(dst_ip=self.pg1.remote_ip4)
+ )
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -90,7 +90,7 @@ class TestClassifierIP(TestClassifier):
self.pg3.assert_nothing_captured(remark="packets forwarded")
def test_iacl_src_dst_ip(self):
- """ Source and destination IP iACL test
+ """Source and destination IP iACL test
Test scenario for basic IP ACL with source and destination IP
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -102,13 +102,14 @@ class TestClassifierIP(TestClassifier):
pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes)
self.pg0.add_stream(pkts)
- key = 'ip'
+ key = "ip"
self.create_classify_table(
- key, self.build_ip_mask(src_ip='ffffffff', dst_ip='ffffffff'))
+ key, self.build_ip_mask(src_ip="ffffffff", dst_ip="ffffffff")
+ )
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip_match(src_ip=self.pg0.remote_ip4,
- dst_ip=self.pg1.remote_ip4))
+ self.build_ip_match(src_ip=self.pg0.remote_ip4, dst_ip=self.pg1.remote_ip4),
+ )
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -123,7 +124,7 @@ class TestClassifierIP(TestClassifier):
class TestClassifierUDP(TestClassifier):
- """ Classifier UDP proto Test Case """
+ """Classifier UDP proto Test Case"""
@classmethod
def setUpClass(cls):
@@ -134,7 +135,7 @@ class TestClassifierUDP(TestClassifier):
super(TestClassifierUDP, cls).tearDownClass()
def test_iacl_proto_udp(self):
- """ UDP protocol iACL test
+ """UDP protocol iACL test
Test scenario for basic protocol ACL with UDP protocol
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -146,13 +147,12 @@ class TestClassifierUDP(TestClassifier):
pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes)
self.pg0.add_stream(pkts)
- key = 'proto_udp'
- self.create_classify_table(key, self.build_ip_mask(proto='ff'))
+ key = "proto_udp"
+ self.create_classify_table(key, self.build_ip_mask(proto="ff"))
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_ip_match(proto=socket.IPPROTO_UDP))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.acl_tbl_idx.get(key), self.build_ip_match(proto=socket.IPPROTO_UDP)
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -165,7 +165,7 @@ class TestClassifierUDP(TestClassifier):
self.pg3.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_udp_sport(self):
- """ UDP source port iACL test
+ """UDP source port iACL test
Test scenario for basic protocol ACL with UDP and sport
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -175,18 +175,18 @@ class TestClassifierUDP(TestClassifier):
# Basic iACL testing with UDP and sport
sport = 38
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- UDP(sport=sport, dport=5678))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=sport, dport=5678)
+ )
self.pg0.add_stream(pkts)
- key = 'proto_udp_sport'
- self.create_classify_table(
- key, self.build_ip_mask(proto='ff', src_port='ffff'))
+ key = "proto_udp_sport"
+ self.create_classify_table(key, self.build_ip_mask(proto="ff", src_port="ffff"))
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip_match(proto=socket.IPPROTO_UDP, src_port=sport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip_match(proto=socket.IPPROTO_UDP, src_port=sport),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -199,7 +199,7 @@ class TestClassifierUDP(TestClassifier):
self.pg3.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_udp_dport(self):
- """ UDP destination port iACL test
+ """UDP destination port iACL test
Test scenario for basic protocol ACL with UDP and dport
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -209,18 +209,18 @@ class TestClassifierUDP(TestClassifier):
# Basic iACL testing with UDP and dport
dport = 427
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- UDP(sport=1234, dport=dport))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=1234, dport=dport)
+ )
self.pg0.add_stream(pkts)
- key = 'proto_udp_dport'
- self.create_classify_table(
- key, self.build_ip_mask(proto='ff', dst_port='ffff'))
+ key = "proto_udp_dport"
+ self.create_classify_table(key, self.build_ip_mask(proto="ff", dst_port="ffff"))
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip_match(proto=socket.IPPROTO_UDP, dst_port=dport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip_match(proto=socket.IPPROTO_UDP, dst_port=dport),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -233,7 +233,7 @@ class TestClassifierUDP(TestClassifier):
self.pg3.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_udp_sport_dport(self):
- """ UDP source and destination ports iACL test
+ """UDP source and destination ports iACL test
Test scenario for basic protocol ACL with UDP and sport and dport
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -244,20 +244,22 @@ class TestClassifierUDP(TestClassifier):
# Basic iACL testing with UDP and sport and dport
sport = 13720
dport = 9080
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- UDP(sport=sport, dport=dport))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=sport, dport=dport)
+ )
self.pg0.add_stream(pkts)
- key = 'proto_udp_ports'
+ key = "proto_udp_ports"
self.create_classify_table(
- key,
- self.build_ip_mask(proto='ff', src_port='ffff', dst_port='ffff'))
+ key, self.build_ip_mask(proto="ff", src_port="ffff", dst_port="ffff")
+ )
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip_match(proto=socket.IPPROTO_UDP, src_port=sport,
- dst_port=dport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip_match(
+ proto=socket.IPPROTO_UDP, src_port=sport, dst_port=dport
+ ),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -271,7 +273,7 @@ class TestClassifierUDP(TestClassifier):
class TestClassifierTCP(TestClassifier):
- """ Classifier TCP proto Test Case """
+ """Classifier TCP proto Test Case"""
@classmethod
def setUpClass(cls):
@@ -282,7 +284,7 @@ class TestClassifierTCP(TestClassifier):
super(TestClassifierTCP, cls).tearDownClass()
def test_iacl_proto_tcp(self):
- """ TCP protocol iACL test
+ """TCP protocol iACL test
Test scenario for basic protocol ACL with TCP protocol
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -291,17 +293,17 @@ class TestClassifierTCP(TestClassifier):
"""
# Basic iACL testing with TCP protocol
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- TCP(sport=1234, dport=5678))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=1234, dport=5678)
+ )
self.pg0.add_stream(pkts)
- key = 'proto_tcp'
- self.create_classify_table(key, self.build_ip_mask(proto='ff'))
+ key = "proto_tcp"
+ self.create_classify_table(key, self.build_ip_mask(proto="ff"))
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_ip_match(proto=socket.IPPROTO_TCP))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.acl_tbl_idx.get(key), self.build_ip_match(proto=socket.IPPROTO_TCP)
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -314,7 +316,7 @@ class TestClassifierTCP(TestClassifier):
self.pg3.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_tcp_sport(self):
- """ TCP source port iACL test
+ """TCP source port iACL test
Test scenario for basic protocol ACL with TCP and sport
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -324,18 +326,18 @@ class TestClassifierTCP(TestClassifier):
# Basic iACL testing with TCP and sport
sport = 38
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- TCP(sport=sport, dport=5678))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=sport, dport=5678)
+ )
self.pg0.add_stream(pkts)
- key = 'proto_tcp_sport'
- self.create_classify_table(
- key, self.build_ip_mask(proto='ff', src_port='ffff'))
+ key = "proto_tcp_sport"
+ self.create_classify_table(key, self.build_ip_mask(proto="ff", src_port="ffff"))
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip_match(proto=socket.IPPROTO_TCP, src_port=sport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip_match(proto=socket.IPPROTO_TCP, src_port=sport),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -348,7 +350,7 @@ class TestClassifierTCP(TestClassifier):
self.pg3.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_tcp_dport(self):
- """ TCP destination port iACL test
+ """TCP destination port iACL test
Test scenario for basic protocol ACL with TCP and dport
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -358,18 +360,18 @@ class TestClassifierTCP(TestClassifier):
# Basic iACL testing with TCP and dport
dport = 427
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- TCP(sport=1234, dport=dport))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=1234, dport=dport)
+ )
self.pg0.add_stream(pkts)
- key = 'proto_tcp_sport'
- self.create_classify_table(
- key, self.build_ip_mask(proto='ff', dst_port='ffff'))
+ key = "proto_tcp_sport"
+ self.create_classify_table(key, self.build_ip_mask(proto="ff", dst_port="ffff"))
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip_match(proto=socket.IPPROTO_TCP, dst_port=dport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip_match(proto=socket.IPPROTO_TCP, dst_port=dport),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -382,7 +384,7 @@ class TestClassifierTCP(TestClassifier):
self.pg3.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_tcp_sport_dport(self):
- """ TCP source and destination ports iACL test
+ """TCP source and destination ports iACL test
Test scenario for basic protocol ACL with TCP and sport and dport
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -393,20 +395,22 @@ class TestClassifierTCP(TestClassifier):
# Basic iACL testing with TCP and sport and dport
sport = 13720
dport = 9080
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- TCP(sport=sport, dport=dport))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=sport, dport=dport)
+ )
self.pg0.add_stream(pkts)
- key = 'proto_tcp_ports'
+ key = "proto_tcp_ports"
self.create_classify_table(
- key,
- self.build_ip_mask(proto='ff', src_port='ffff', dst_port='ffff'))
+ key, self.build_ip_mask(proto="ff", src_port="ffff", dst_port="ffff")
+ )
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip_match(proto=socket.IPPROTO_TCP, src_port=sport,
- dst_port=dport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip_match(
+ proto=socket.IPPROTO_TCP, src_port=sport, dst_port=dport
+ ),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -420,7 +424,7 @@ class TestClassifierTCP(TestClassifier):
class TestClassifierIPOut(TestClassifier):
- """ Classifier output IP Test Case """
+ """Classifier output IP Test Case"""
@classmethod
def setUpClass(cls):
@@ -431,7 +435,7 @@ class TestClassifierIPOut(TestClassifier):
super(TestClassifierIPOut, cls).tearDownClass()
def test_acl_ip_out(self):
- """ Output IP ACL test
+ """Output IP ACL test
Test scenario for basic IP ACL with source IP
- Create IPv4 stream for pg1 -> pg0 interface.
@@ -443,12 +447,13 @@ class TestClassifierIPOut(TestClassifier):
pkts = self.create_stream(self.pg1, self.pg0, self.pg_if_packet_sizes)
self.pg1.add_stream(pkts)
- key = 'ip_out'
+ key = "ip_out"
self.create_classify_table(
- key, self.build_ip_mask(src_ip='ffffffff'), data_offset=0)
+ key, self.build_ip_mask(src_ip="ffffffff"), data_offset=0
+ )
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_ip_match(src_ip=self.pg1.remote_ip4))
+ self.acl_tbl_idx.get(key), self.build_ip_match(src_ip=self.pg1.remote_ip4)
+ )
self.output_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -463,7 +468,7 @@ class TestClassifierIPOut(TestClassifier):
class TestClassifierMAC(TestClassifier):
- """ Classifier MAC Test Case """
+ """Classifier MAC Test Case"""
@classmethod
def setUpClass(cls):
@@ -474,7 +479,7 @@ class TestClassifierMAC(TestClassifier):
super(TestClassifierMAC, cls).tearDownClass()
def test_acl_mac(self):
- """ MAC ACL test
+ """MAC ACL test
Test scenario for basic MAC ACL with source MAC
- Create IPv4 stream for pg0 -> pg2 interface.
@@ -486,12 +491,13 @@ class TestClassifierMAC(TestClassifier):
pkts = self.create_stream(self.pg0, self.pg2, self.pg_if_packet_sizes)
self.pg0.add_stream(pkts)
- key = 'mac'
+ key = "mac"
self.create_classify_table(
- key, self.build_mac_mask(src_mac='ffffffffffff'), data_offset=-14)
+ key, self.build_mac_mask(src_mac="ffffffffffff"), data_offset=-14
+ )
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_mac_match(src_mac=self.pg0.remote_mac))
+ self.acl_tbl_idx.get(key), self.build_mac_match(src_mac=self.pg0.remote_mac)
+ )
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -506,7 +512,7 @@ class TestClassifierMAC(TestClassifier):
class TestClassifierComplex(TestClassifier):
- """ Large & Nested Classifiers Test Cases """
+ """Large & Nested Classifiers Test Cases"""
@classmethod
def setUpClass(cls):
@@ -517,7 +523,7 @@ class TestClassifierComplex(TestClassifier):
super(TestClassifierComplex, cls).tearDownClass()
def test_iacl_large(self):
- """ Large input ACL test
+ """Large input ACL test
Test scenario for Large ACL matching on ethernet+ip+udp headers
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -527,7 +533,7 @@ class TestClassifierComplex(TestClassifier):
# 40b offset = 80bytes - (sizeof(UDP/IP/ETH) + 4b)
# + 4b as build_ip_ma*() func, do not match against UDP Len & Chksum
- msk = VarMask(offset=40, spec='ffff')
+ msk = VarMask(offset=40, spec="ffff")
mth = VarMatch(offset=40, value=0x1234, length=2)
payload_msk = self.build_payload_mask([msk])
@@ -537,38 +543,49 @@ class TestClassifierComplex(TestClassifier):
dport = 9080
# 36b offset = 80bytes - (sizeof(UDP/IP/ETH))
- packet_ex = bytes.fromhex(('0' * 36) + '1234')
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- UDP(sport=sport, dport=dport),
- packet_ex)
+ packet_ex = bytes.fromhex(("0" * 36) + "1234")
+ pkts = self.create_stream(
+ self.pg0,
+ self.pg1,
+ self.pg_if_packet_sizes,
+ UDP(sport=sport, dport=dport),
+ packet_ex,
+ )
self.pg0.add_stream(pkts)
- key = 'large_in'
+ key = "large_in"
self.create_classify_table(
key,
- self.build_mac_mask(src_mac='ffffffffffff',
- dst_mac='ffffffffffff',
- ether_type='ffff') +
- self.build_ip_mask(proto='ff',
- src_ip='ffffffff',
- dst_ip='ffffffff',
- src_port='ffff',
- dst_port='ffff') +
- payload_msk,
- data_offset=-14)
+ self.build_mac_mask(
+ src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff"
+ )
+ + self.build_ip_mask(
+ proto="ff",
+ src_ip="ffffffff",
+ dst_ip="ffffffff",
+ src_port="ffff",
+ dst_port="ffff",
+ )
+ + payload_msk,
+ data_offset=-14,
+ )
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_mac_match(src_mac=self.pg0.remote_mac,
- dst_mac=self.pg0.local_mac,
- # ipv4 next header
- ether_type='0800') +
- self.build_ip_match(proto=socket.IPPROTO_UDP,
- src_ip=self.pg0.remote_ip4,
- dst_ip=self.pg1.remote_ip4,
- src_port=sport,
- dst_port=dport) +
- payload_match
+ self.build_mac_match(
+ src_mac=self.pg0.remote_mac,
+ dst_mac=self.pg0.local_mac,
+ # ipv4 next header
+ ether_type="0800",
+ )
+ + self.build_ip_match(
+ proto=socket.IPPROTO_UDP,
+ src_ip=self.pg0.remote_ip4,
+ dst_ip=self.pg1.remote_ip4,
+ src_port=sport,
+ dst_port=dport,
+ )
+ + payload_match,
)
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
@@ -584,7 +601,7 @@ class TestClassifierComplex(TestClassifier):
self.pg3.assert_nothing_captured(remark="packets forwarded")
def test_oacl_large(self):
- """ Large output ACL test
+ """Large output ACL test
Test scenario for Large ACL matching on ethernet+ip+udp headers
- Create IPv4 stream for pg1 -> pg0 interface.
- Create large acl matching on ethernet+ip+udp header fields
@@ -593,7 +610,7 @@ class TestClassifierComplex(TestClassifier):
# 40b offset = 80bytes - (sizeof(UDP/IP/ETH) + 4b)
# + 4b as build_ip_ma*() func, do not match against UDP Len & Chksum
- msk = VarMask(offset=40, spec='ffff')
+ msk = VarMask(offset=40, spec="ffff")
mth = VarMatch(offset=40, value=0x1234, length=2)
payload_msk = self.build_payload_mask([msk])
@@ -603,38 +620,50 @@ class TestClassifierComplex(TestClassifier):
dport = 9080
# 36b offset = 80bytes - (sizeof(UDP/IP/ETH))
- packet_ex = bytes.fromhex(('0' * 36) + '1234')
- pkts = self.create_stream(self.pg1, self.pg0, self.pg_if_packet_sizes,
- UDP(sport=sport, dport=dport),
- packet_ex)
+ packet_ex = bytes.fromhex(("0" * 36) + "1234")
+ pkts = self.create_stream(
+ self.pg1,
+ self.pg0,
+ self.pg_if_packet_sizes,
+ UDP(sport=sport, dport=dport),
+ packet_ex,
+ )
self.pg1.add_stream(pkts)
- key = 'large_out'
+ key = "large_out"
self.create_classify_table(
key,
- self.build_mac_mask(src_mac='ffffffffffff',
- dst_mac='ffffffffffff',
- ether_type='ffff') +
- self.build_ip_mask(proto='ff',
- src_ip='ffffffff',
- dst_ip='ffffffff',
- src_port='ffff',
- dst_port='ffff') +
- payload_msk,
- data_offset=-14)
+ self.build_mac_mask(
+ src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff"
+ )
+ + self.build_ip_mask(
+ proto="ff",
+ src_ip="ffffffff",
+ dst_ip="ffffffff",
+ src_port="ffff",
+ dst_port="ffff",
+ )
+ + payload_msk,
+ data_offset=-14,
+ )
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_mac_match(src_mac=self.pg0.local_mac,
- dst_mac=self.pg0.remote_mac,
- # ipv4 next header
- ether_type='0800') +
- self.build_ip_match(proto=socket.IPPROTO_UDP,
- src_ip=self.pg1.remote_ip4,
- dst_ip=self.pg0.remote_ip4,
- src_port=sport,
- dst_port=dport) +
- payload_match)
+ self.build_mac_match(
+ src_mac=self.pg0.local_mac,
+ dst_mac=self.pg0.remote_mac,
+ # ipv4 next header
+ ether_type="0800",
+ )
+ + self.build_ip_match(
+ proto=socket.IPPROTO_UDP,
+ src_ip=self.pg1.remote_ip4,
+ dst_ip=self.pg0.remote_ip4,
+ src_port=sport,
+ dst_port=dport,
+ )
+ + payload_match,
+ )
self.output_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -649,7 +678,7 @@ class TestClassifierComplex(TestClassifier):
self.pg3.assert_nothing_captured(remark="packets forwarded")
def test_iacl_nested(self):
- """ Nested input ACL test
+ """Nested input ACL test
Test scenario for Large ACL matching on ethernet+ip+udp headers
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -660,48 +689,60 @@ class TestClassifierComplex(TestClassifier):
sport = 13720
dport = 9080
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- UDP(sport=sport, dport=dport))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=sport, dport=dport)
+ )
self.pg0.add_stream(pkts)
- subtable_key = 'subtable_in'
+ subtable_key = "subtable_in"
self.create_classify_table(
subtable_key,
- self.build_mac_mask(src_mac='ffffffffffff',
- dst_mac='ffffffffffff',
- ether_type='ffff') +
- self.build_ip_mask(proto='ff',
- src_ip='ffffffff',
- dst_ip='ffffffff',
- src_port='ffff',
- dst_port='ffff'),
- data_offset=-14)
-
- key = 'nested_in'
+ self.build_mac_mask(
+ src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff"
+ )
+ + self.build_ip_mask(
+ proto="ff",
+ src_ip="ffffffff",
+ dst_ip="ffffffff",
+ src_port="ffff",
+ dst_port="ffff",
+ ),
+ data_offset=-14,
+ )
+
+ key = "nested_in"
self.create_classify_table(
key,
- self.build_mac_mask(src_mac='ffffffffffff',
- dst_mac='ffffffffffff',
- ether_type='ffff') +
- self.build_ip_mask(proto='ff',
- src_ip='ffffffff',
- dst_ip='ffffffff',
- src_port='ffff',
- dst_port='ffff'),
- next_table_index=self.acl_tbl_idx.get(subtable_key))
+ self.build_mac_mask(
+ src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff"
+ )
+ + self.build_ip_mask(
+ proto="ff",
+ src_ip="ffffffff",
+ dst_ip="ffffffff",
+ src_port="ffff",
+ dst_port="ffff",
+ ),
+ next_table_index=self.acl_tbl_idx.get(subtable_key),
+ )
self.create_classify_session(
self.acl_tbl_idx.get(subtable_key),
- self.build_mac_match(src_mac=self.pg0.remote_mac,
- dst_mac=self.pg0.local_mac,
- # ipv4 next header
- ether_type='0800') +
- self.build_ip_match(proto=socket.IPPROTO_UDP,
- src_ip=self.pg0.remote_ip4,
- dst_ip=self.pg1.remote_ip4,
- src_port=sport,
- dst_port=dport))
+ self.build_mac_match(
+ src_mac=self.pg0.remote_mac,
+ dst_mac=self.pg0.local_mac,
+ # ipv4 next header
+ ether_type="0800",
+ )
+ + self.build_ip_match(
+ proto=socket.IPPROTO_UDP,
+ src_ip=self.pg0.remote_ip4,
+ dst_ip=self.pg1.remote_ip4,
+ src_port=sport,
+ dst_port=dport,
+ ),
+ )
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -716,7 +757,7 @@ class TestClassifierComplex(TestClassifier):
self.pg3.assert_nothing_captured(remark="packets forwarded")
def test_oacl_nested(self):
- """ Nested output ACL test
+ """Nested output ACL test
Test scenario for Large ACL matching on ethernet+ip+udp headers
- Create IPv4 stream for pg1 -> pg0 interface.
@@ -727,48 +768,60 @@ class TestClassifierComplex(TestClassifier):
sport = 13720
dport = 9080
- pkts = self.create_stream(self.pg1, self.pg0, self.pg_if_packet_sizes,
- UDP(sport=sport, dport=dport))
+ pkts = self.create_stream(
+ self.pg1, self.pg0, self.pg_if_packet_sizes, UDP(sport=sport, dport=dport)
+ )
self.pg1.add_stream(pkts)
- subtable_key = 'subtable_out'
+ subtable_key = "subtable_out"
self.create_classify_table(
subtable_key,
- self.build_mac_mask(src_mac='ffffffffffff',
- dst_mac='ffffffffffff',
- ether_type='ffff') +
- self.build_ip_mask(proto='ff',
- src_ip='ffffffff',
- dst_ip='ffffffff',
- src_port='ffff',
- dst_port='ffff'),
- data_offset=-14)
-
- key = 'nested_out'
+ self.build_mac_mask(
+ src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff"
+ )
+ + self.build_ip_mask(
+ proto="ff",
+ src_ip="ffffffff",
+ dst_ip="ffffffff",
+ src_port="ffff",
+ dst_port="ffff",
+ ),
+ data_offset=-14,
+ )
+
+ key = "nested_out"
self.create_classify_table(
key,
- self.build_mac_mask(src_mac='ffffffffffff',
- dst_mac='ffffffffffff',
- ether_type='ffff') +
- self.build_ip_mask(proto='ff',
- src_ip='ffffffff',
- dst_ip='ffffffff',
- src_port='ffff',
- dst_port='ffff'),
+ self.build_mac_mask(
+ src_mac="ffffffffffff", dst_mac="ffffffffffff", ether_type="ffff"
+ )
+ + self.build_ip_mask(
+ proto="ff",
+ src_ip="ffffffff",
+ dst_ip="ffffffff",
+ src_port="ffff",
+ dst_port="ffff",
+ ),
next_table_index=self.acl_tbl_idx.get(subtable_key),
- data_offset=-14)
+ data_offset=-14,
+ )
self.create_classify_session(
self.acl_tbl_idx.get(subtable_key),
- self.build_mac_match(src_mac=self.pg0.local_mac,
- dst_mac=self.pg0.remote_mac,
- # ipv4 next header
- ether_type='0800') +
- self.build_ip_match(proto=socket.IPPROTO_UDP,
- src_ip=self.pg1.remote_ip4,
- dst_ip=self.pg0.remote_ip4,
- src_port=sport,
- dst_port=dport))
+ self.build_mac_match(
+ src_mac=self.pg0.local_mac,
+ dst_mac=self.pg0.remote_mac,
+ # ipv4 next header
+ ether_type="0800",
+ )
+ + self.build_ip_match(
+ proto=socket.IPPROTO_UDP,
+ src_ip=self.pg1.remote_ip4,
+ dst_ip=self.pg0.remote_ip4,
+ src_port=sport,
+ dst_port=dport,
+ ),
+ )
self.output_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -784,7 +837,7 @@ class TestClassifierComplex(TestClassifier):
class TestClassifierPBR(TestClassifier):
- """ Classifier PBR Test Case """
+ """Classifier PBR Test Case"""
@classmethod
def setUpClass(cls):
@@ -795,7 +848,7 @@ class TestClassifierPBR(TestClassifier):
super(TestClassifierPBR, cls).tearDownClass()
def test_acl_pbr(self):
- """ IP PBR test
+ """IP PBR test
Test scenario for PBR with source IP
- Create IPv4 stream for pg0 -> pg3 interface.
@@ -807,19 +860,24 @@ class TestClassifierPBR(TestClassifier):
pkts = self.create_stream(self.pg0, self.pg3, self.pg_if_packet_sizes)
self.pg0.add_stream(pkts)
- key = 'pbr'
- self.create_classify_table(key, self.build_ip_mask(src_ip='ffffffff'))
+ key = "pbr"
+ self.create_classify_table(key, self.build_ip_mask(src_ip="ffffffff"))
pbr_option = 1
# this will create the VRF/table in which we will insert the route
self.create_classify_session(
self.acl_tbl_idx.get(key),
self.build_ip_match(src_ip=self.pg0.remote_ip4),
- pbr_option, self.pbr_vrfid)
+ pbr_option,
+ self.pbr_vrfid,
+ )
self.assertTrue(self.verify_vrf(self.pbr_vrfid))
- r = VppIpRoute(self, self.pg3.local_ip4, 24,
- [VppRoutePath(self.pg3.remote_ip4,
- INVALID_INDEX)],
- table_id=self.pbr_vrfid)
+ r = VppIpRoute(
+ self,
+ self.pg3.local_ip4,
+ 24,
+ [VppRoutePath(self.pg3.remote_ip4, INVALID_INDEX)],
+ table_id=self.pbr_vrfid,
+ )
r.add_vpp_config()
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
@@ -839,14 +897,17 @@ class TestClassifierPBR(TestClassifier):
self.create_classify_session(
self.acl_tbl_idx.get(key),
self.build_ip_match(src_ip=self.pg0.remote_ip4),
- pbr_option, self.pbr_vrfid, is_add=0)
+ pbr_option,
+ self.pbr_vrfid,
+ is_add=0,
+ )
# and the table should be gone.
self.assertFalse(self.verify_vrf(self.pbr_vrfid))
class TestClassifierPunt(TestClassifier):
- """ Classifier punt Test Case """
+ """Classifier punt Test Case"""
@classmethod
def setUpClass(cls):
@@ -857,7 +918,7 @@ class TestClassifierPunt(TestClassifier):
super(TestClassifierPunt, cls).tearDownClass()
def test_punt_udp(self):
- """ IPv4/UDP protocol punt ACL test
+ """IPv4/UDP protocol punt ACL test
Test scenario for basic punt ACL with UDP protocol
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -868,13 +929,10 @@ class TestClassifierPunt(TestClassifier):
sport = 6754
dport = 17923
- key = 'ip4_udp_punt'
+ key = "ip4_udp_punt"
self.create_classify_table(
- key,
- self.build_ip_mask(
- src_ip='ffffffff',
- proto='ff',
- src_port='ffff'))
+ key, self.build_ip_mask(src_ip="ffffffff", proto="ff", src_port="ffff")
+ )
table_index = self.acl_tbl_idx.get(key)
self.vapi.punt_acl_add_del(ip4_table_index=table_index)
self.acl_active_table = key
@@ -883,52 +941,67 @@ class TestClassifierPunt(TestClassifier):
self.vapi.set_punt(
is_add=1,
punt={
- 'type': VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4,
- 'punt': {
- 'l4': {
- 'af': VppEnum.vl_api_address_family_t.ADDRESS_IP4,
- 'protocol': VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP,
- 'port': dport,
- }}})
- self.vapi.ip_punt_redirect(punt={
- 'rx_sw_if_index': self.pg0.sw_if_index,
- 'tx_sw_if_index': self.pg1.sw_if_index,
- 'nh': self.pg1.remote_ip4,
- })
-
- pkts = [(Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=sport, dport=dport) /
- Raw('\x17' * 100))] * 2
+ "type": VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4,
+ "punt": {
+ "l4": {
+ "af": VppEnum.vl_api_address_family_t.ADDRESS_IP4,
+ "protocol": VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP,
+ "port": dport,
+ }
+ },
+ },
+ )
+ self.vapi.ip_punt_redirect(
+ punt={
+ "rx_sw_if_index": self.pg0.sw_if_index,
+ "tx_sw_if_index": self.pg1.sw_if_index,
+ "nh": self.pg1.remote_ip4,
+ }
+ )
+
+ pkts = [
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=sport, dport=dport)
+ / Raw("\x17" * 100)
+ )
+ ] * 2
# allow a session but not matching the stream: expect to drop
self.create_classify_session(
table_index,
- self.build_ip_match(src_ip=self.pg0.remote_ip4,
- proto=socket.IPPROTO_UDP, src_port=sport + 10))
+ self.build_ip_match(
+ src_ip=self.pg0.remote_ip4,
+ proto=socket.IPPROTO_UDP,
+ src_port=sport + 10,
+ ),
+ )
self.send_and_assert_no_replies(self.pg0, pkts)
# allow a session matching the stream: expect to pass
self.create_classify_session(
table_index,
- self.build_ip_match(src_ip=self.pg0.remote_ip4,
- proto=socket.IPPROTO_UDP, src_port=sport))
+ self.build_ip_match(
+ src_ip=self.pg0.remote_ip4, proto=socket.IPPROTO_UDP, src_port=sport
+ ),
+ )
self.send_and_expect_only(self.pg0, pkts, self.pg1)
# test dump api: ip4 is set, ip6 is not
r = self.vapi.punt_acl_get()
self.assertEqual(r.ip4_table_index, table_index)
- self.assertEqual(r.ip6_table_index, 0xffffffff)
+ self.assertEqual(r.ip6_table_index, 0xFFFFFFFF)
# cleanup
- self.acl_active_table = ''
+ self.acl_active_table = ""
self.vapi.punt_acl_add_del(ip4_table_index=table_index, is_add=0)
# test dump api: nothing set
r = self.vapi.punt_acl_get()
- self.assertEqual(r.ip4_table_index, 0xffffffff)
- self.assertEqual(r.ip6_table_index, 0xffffffff)
+ self.assertEqual(r.ip4_table_index, 0xFFFFFFFF)
+ self.assertEqual(r.ip6_table_index, 0xFFFFFFFF)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_classifier_ip6.py b/test/test_classifier_ip6.py
index 211374b5ec6..7b5d41c3eef 100644
--- a/test/test_classifier_ip6.py
+++ b/test/test_classifier_ip6.py
@@ -14,7 +14,7 @@ from template_classifier import TestClassifier
class TestClassifierIP6(TestClassifier):
- """ Classifier IP6 Test Case """
+ """Classifier IP6 Test Case"""
@classmethod
def setUpClass(cls):
@@ -26,7 +26,7 @@ class TestClassifierIP6(TestClassifier):
super(TestClassifierIP6, cls).tearDownClass()
def test_iacl_src_ip(self):
- """ Source IP6 iACL test
+ """Source IP6 iACL test
Test scenario for basic IP ACL with source IP
- Create IPv6 stream for pg0 -> pg1 interface.
@@ -38,13 +38,13 @@ class TestClassifierIP6(TestClassifier):
pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes)
self.pg0.add_stream(pkts)
- key = 'ip6_src'
+ key = "ip6_src"
self.create_classify_table(
- key,
- self.build_ip6_mask(src_ip='ffffffffffffffffffffffffffffffff'))
+ key, self.build_ip6_mask(src_ip="ffffffffffffffffffffffffffffffff")
+ )
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_ip6_match(src_ip=self.pg0.remote_ip6))
+ self.acl_tbl_idx.get(key), self.build_ip6_match(src_ip=self.pg0.remote_ip6)
+ )
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -57,7 +57,7 @@ class TestClassifierIP6(TestClassifier):
self.pg2.assert_nothing_captured(remark="packets forwarded")
def test_iacl_dst_ip(self):
- """ Destination IP6 iACL test
+ """Destination IP6 iACL test
Test scenario for basic IP ACL with destination IP
- Create IPv6 stream for pg0 -> pg1 interface.
@@ -69,13 +69,13 @@ class TestClassifierIP6(TestClassifier):
pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes)
self.pg0.add_stream(pkts)
- key = 'ip6_dst'
+ key = "ip6_dst"
self.create_classify_table(
- key,
- self.build_ip6_mask(dst_ip='ffffffffffffffffffffffffffffffff'))
+ key, self.build_ip6_mask(dst_ip="ffffffffffffffffffffffffffffffff")
+ )
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_ip6_match(dst_ip=self.pg1.remote_ip6))
+ self.acl_tbl_idx.get(key), self.build_ip6_match(dst_ip=self.pg1.remote_ip6)
+ )
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -88,7 +88,7 @@ class TestClassifierIP6(TestClassifier):
self.pg2.assert_nothing_captured(remark="packets forwarded")
def test_iacl_src_dst_ip(self):
- """ Source and destination IP6 iACL test
+ """Source and destination IP6 iACL test
Test scenario for basic IP ACL with source and destination IP
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -100,15 +100,20 @@ class TestClassifierIP6(TestClassifier):
pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes)
self.pg0.add_stream(pkts)
- key = 'ip6'
+ key = "ip6"
self.create_classify_table(
key,
- self.build_ip6_mask(src_ip='ffffffffffffffffffffffffffffffff',
- dst_ip='ffffffffffffffffffffffffffffffff'))
+ self.build_ip6_mask(
+ src_ip="ffffffffffffffffffffffffffffffff",
+ dst_ip="ffffffffffffffffffffffffffffffff",
+ ),
+ )
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip6_match(src_ip=self.pg0.remote_ip6,
- dst_ip=self.pg1.remote_ip6))
+ self.build_ip6_match(
+ src_ip=self.pg0.remote_ip6, dst_ip=self.pg1.remote_ip6
+ ),
+ )
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -124,7 +129,7 @@ class TestClassifierIP6(TestClassifier):
# Tests split to different test case classes because of issue reported in
# ticket VPP-1336
class TestClassifierIP6UDP(TestClassifier):
- """ Classifier IP6 UDP proto Test Case """
+ """Classifier IP6 UDP proto Test Case"""
@classmethod
def setUpClass(cls):
@@ -132,7 +137,7 @@ class TestClassifierIP6UDP(TestClassifier):
cls.af = socket.AF_INET6
def test_iacl_proto_udp(self):
- """ IP6 UDP protocol iACL test
+ """IP6 UDP protocol iACL test
Test scenario for basic protocol ACL with UDP protocol
- Create IPv6 stream for pg0 -> pg1 interface.
@@ -144,11 +149,11 @@ class TestClassifierIP6UDP(TestClassifier):
pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes)
self.pg0.add_stream(pkts)
- key = 'nh_udp'
- self.create_classify_table(key, self.build_ip6_mask(nh='ff'))
+ key = "nh_udp"
+ self.create_classify_table(key, self.build_ip6_mask(nh="ff"))
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_ip6_match(nh=socket.IPPROTO_UDP))
+ self.acl_tbl_idx.get(key), self.build_ip6_match(nh=socket.IPPROTO_UDP)
+ )
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -161,7 +166,7 @@ class TestClassifierIP6UDP(TestClassifier):
self.pg2.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_udp_sport(self):
- """ IP6 UDP source port iACL test
+ """IP6 UDP source port iACL test
Test scenario for basic protocol ACL with UDP and sport
- Create IPv6 stream for pg0 -> pg1 interface.
@@ -171,18 +176,18 @@ class TestClassifierIP6UDP(TestClassifier):
# Basic iACL testing with UDP and sport
sport = 38
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- UDP(sport=sport, dport=5678))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=sport, dport=5678)
+ )
self.pg0.add_stream(pkts)
- key = 'nh_udp_sport'
- self.create_classify_table(
- key, self.build_ip6_mask(nh='ff', src_port='ffff'))
+ key = "nh_udp_sport"
+ self.create_classify_table(key, self.build_ip6_mask(nh="ff", src_port="ffff"))
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip6_match(nh=socket.IPPROTO_UDP, src_port=sport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip6_match(nh=socket.IPPROTO_UDP, src_port=sport),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -194,7 +199,7 @@ class TestClassifierIP6UDP(TestClassifier):
self.pg2.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_udp_dport(self):
- """ IP6 UDP destination port iACL test
+ """IP6 UDP destination port iACL test
Test scenario for basic protocol ACL with UDP and dport
- Create IPv6 stream for pg0 -> pg1 interface.
@@ -204,18 +209,18 @@ class TestClassifierIP6UDP(TestClassifier):
# Basic iACL testing with UDP and dport
dport = 427
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- UDP(sport=1234, dport=dport))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=1234, dport=dport)
+ )
self.pg0.add_stream(pkts)
- key = 'nh_udp_dport'
- self.create_classify_table(
- key, self.build_ip6_mask(nh='ff', dst_port='ffff'))
+ key = "nh_udp_dport"
+ self.create_classify_table(key, self.build_ip6_mask(nh="ff", dst_port="ffff"))
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip6_match(nh=socket.IPPROTO_UDP, dst_port=dport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip6_match(nh=socket.IPPROTO_UDP, dst_port=dport),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -227,7 +232,7 @@ class TestClassifierIP6UDP(TestClassifier):
self.pg2.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_udp_sport_dport(self):
- """ IP6 UDP source and destination ports iACL test
+ """IP6 UDP source and destination ports iACL test
Test scenario for basic protocol ACL with UDP and sport and dport
- Create IPv6 stream for pg0 -> pg1 interface.
@@ -238,20 +243,20 @@ class TestClassifierIP6UDP(TestClassifier):
# Basic iACL testing with UDP and sport and dport
sport = 13720
dport = 9080
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- UDP(sport=sport, dport=dport))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, UDP(sport=sport, dport=dport)
+ )
self.pg0.add_stream(pkts)
- key = 'nh_udp_ports'
+ key = "nh_udp_ports"
self.create_classify_table(
- key,
- self.build_ip6_mask(nh='ff', src_port='ffff', dst_port='ffff'))
+ key, self.build_ip6_mask(nh="ff", src_port="ffff", dst_port="ffff")
+ )
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip6_match(nh=socket.IPPROTO_UDP, src_port=sport,
- dst_port=dport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip6_match(nh=socket.IPPROTO_UDP, src_port=sport, dst_port=dport),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -264,7 +269,7 @@ class TestClassifierIP6UDP(TestClassifier):
class TestClassifierIP6TCP(TestClassifier):
- """ Classifier IP6 TCP proto Test Case """
+ """Classifier IP6 TCP proto Test Case"""
@classmethod
def setUpClass(cls):
@@ -272,7 +277,7 @@ class TestClassifierIP6TCP(TestClassifier):
cls.af = socket.AF_INET6
def test_iacl_proto_tcp(self):
- """ IP6 TCP protocol iACL test
+ """IP6 TCP protocol iACL test
Test scenario for basic protocol ACL with TCP protocol
- Create IPv6 stream for pg0 -> pg1 interface.
@@ -281,17 +286,17 @@ class TestClassifierIP6TCP(TestClassifier):
"""
# Basic iACL testing with TCP protocol
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- TCP(sport=1234, dport=5678))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=1234, dport=5678)
+ )
self.pg0.add_stream(pkts)
- key = 'nh_tcp'
- self.create_classify_table(key, self.build_ip6_mask(nh='ff'))
+ key = "nh_tcp"
+ self.create_classify_table(key, self.build_ip6_mask(nh="ff"))
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_ip6_match(nh=socket.IPPROTO_TCP))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.acl_tbl_idx.get(key), self.build_ip6_match(nh=socket.IPPROTO_TCP)
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -303,7 +308,7 @@ class TestClassifierIP6TCP(TestClassifier):
self.pg2.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_tcp_sport(self):
- """ IP6 TCP source port iACL test
+ """IP6 TCP source port iACL test
Test scenario for basic protocol ACL with TCP and sport
- Create IPv6 stream for pg0 -> pg1 interface.
@@ -313,18 +318,18 @@ class TestClassifierIP6TCP(TestClassifier):
# Basic iACL testing with TCP and sport
sport = 38
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- TCP(sport=sport, dport=5678))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=sport, dport=5678)
+ )
self.pg0.add_stream(pkts)
- key = 'nh_tcp_sport'
- self.create_classify_table(
- key, self.build_ip6_mask(nh='ff', src_port='ffff'))
+ key = "nh_tcp_sport"
+ self.create_classify_table(key, self.build_ip6_mask(nh="ff", src_port="ffff"))
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip6_match(nh=socket.IPPROTO_TCP, src_port=sport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip6_match(nh=socket.IPPROTO_TCP, src_port=sport),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -336,7 +341,7 @@ class TestClassifierIP6TCP(TestClassifier):
self.pg2.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_tcp_dport(self):
- """ IP6 TCP destination port iACL test
+ """IP6 TCP destination port iACL test
Test scenario for basic protocol ACL with TCP and dport
- Create IPv6 stream for pg0 -> pg1 interface.
@@ -346,18 +351,18 @@ class TestClassifierIP6TCP(TestClassifier):
# Basic iACL testing with TCP and dport
dport = 427
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- TCP(sport=1234, dport=dport))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=1234, dport=dport)
+ )
self.pg0.add_stream(pkts)
- key = 'nh_tcp_dport'
- self.create_classify_table(
- key, self.build_ip6_mask(nh='ff', dst_port='ffff'))
+ key = "nh_tcp_dport"
+ self.create_classify_table(key, self.build_ip6_mask(nh="ff", dst_port="ffff"))
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip6_match(nh=socket.IPPROTO_TCP, dst_port=dport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip6_match(nh=socket.IPPROTO_TCP, dst_port=dport),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -369,7 +374,7 @@ class TestClassifierIP6TCP(TestClassifier):
self.pg2.assert_nothing_captured(remark="packets forwarded")
def test_iacl_proto_tcp_sport_dport(self):
- """ IP6 TCP source and destination ports iACL test
+ """IP6 TCP source and destination ports iACL test
Test scenario for basic protocol ACL with TCP and sport and dport
- Create IPv6 stream for pg0 -> pg1 interface.
@@ -380,20 +385,20 @@ class TestClassifierIP6TCP(TestClassifier):
# Basic iACL testing with TCP and sport and dport
sport = 13720
dport = 9080
- pkts = self.create_stream(self.pg0, self.pg1, self.pg_if_packet_sizes,
- TCP(sport=sport, dport=dport))
+ pkts = self.create_stream(
+ self.pg0, self.pg1, self.pg_if_packet_sizes, TCP(sport=sport, dport=dport)
+ )
self.pg0.add_stream(pkts)
- key = 'nh_tcp_ports'
+ key = "nh_tcp_ports"
self.create_classify_table(
- key,
- self.build_ip6_mask(nh='ff', src_port='ffff', dst_port='ffff'))
+ key, self.build_ip6_mask(nh="ff", src_port="ffff", dst_port="ffff")
+ )
self.create_classify_session(
self.acl_tbl_idx.get(key),
- self.build_ip6_match(nh=socket.IPPROTO_TCP, src_port=sport,
- dst_port=dport))
- self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.build_ip6_match(nh=socket.IPPROTO_TCP, src_port=sport, dst_port=dport),
+ )
+ self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -406,7 +411,7 @@ class TestClassifierIP6TCP(TestClassifier):
class TestClassifierIP6Out(TestClassifier):
- """ Classifier output IP6 Test Case """
+ """Classifier output IP6 Test Case"""
@classmethod
def setUpClass(cls):
@@ -414,7 +419,7 @@ class TestClassifierIP6Out(TestClassifier):
cls.af = socket.AF_INET6
def test_acl_ip_out(self):
- """ Output IP6 ACL test
+ """Output IP6 ACL test
Test scenario for basic IP ACL with source IP
- Create IPv6 stream for pg1 -> pg0 interface.
@@ -426,16 +431,16 @@ class TestClassifierIP6Out(TestClassifier):
pkts = self.create_stream(self.pg1, self.pg0, self.pg_if_packet_sizes)
self.pg1.add_stream(pkts)
- key = 'ip6_out'
+ key = "ip6_out"
self.create_classify_table(
key,
- self.build_ip6_mask(src_ip='ffffffffffffffffffffffffffffffff'),
- data_offset=0)
+ self.build_ip6_mask(src_ip="ffffffffffffffffffffffffffffffff"),
+ data_offset=0,
+ )
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_ip6_match(src_ip=self.pg1.remote_ip6))
- self.output_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(key))
+ self.acl_tbl_idx.get(key), self.build_ip6_match(src_ip=self.pg1.remote_ip6)
+ )
+ self.output_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.pg_enable_capture(self.pg_interfaces)
@@ -448,7 +453,7 @@ class TestClassifierIP6Out(TestClassifier):
class TestClassifierIP6MAC(TestClassifier):
- """ Classifier IP6 MAC Test Case """
+ """Classifier IP6 MAC Test Case"""
@classmethod
def setUpClass(cls):
@@ -456,7 +461,7 @@ class TestClassifierIP6MAC(TestClassifier):
cls.af = socket.AF_INET6
def test_acl_mac(self):
- """ IP6 MAC iACL test
+ """IP6 MAC iACL test
Test scenario for basic MAC ACL with source MAC
- Create IPv6 stream for pg0 -> pg2 interface.
@@ -468,12 +473,13 @@ class TestClassifierIP6MAC(TestClassifier):
pkts = self.create_stream(self.pg0, self.pg2, self.pg_if_packet_sizes)
self.pg0.add_stream(pkts)
- key = 'mac'
+ key = "mac"
self.create_classify_table(
- key, self.build_mac_mask(src_mac='ffffffffffff'), data_offset=-14)
+ key, self.build_mac_mask(src_mac="ffffffffffff"), data_offset=-14
+ )
self.create_classify_session(
- self.acl_tbl_idx.get(key),
- self.build_mac_match(src_mac=self.pg0.remote_mac))
+ self.acl_tbl_idx.get(key), self.build_mac_match(src_mac=self.pg0.remote_mac)
+ )
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
@@ -486,5 +492,5 @@ class TestClassifierIP6MAC(TestClassifier):
self.pg1.assert_nothing_captured(remark="packets forwarded")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_classify_l2_acl.py b/test/test_classify_l2_acl.py
index b1309881e58..d94af3f718e 100644
--- a/test/test_classify_l2_acl.py
+++ b/test/test_classify_l2_acl.py
@@ -20,7 +20,7 @@ from template_classifier import TestClassifier
class TestClassifyAcl(TestClassifier):
- """ Classifier-based L2 input and output ACL Test Case """
+ """Classifier-based L2 input and output ACL Test Case"""
# traffic types
IP = 0
@@ -37,7 +37,7 @@ class TestClassifyAcl(TestClassifier):
# supported protocols
proto = [[6, 17], [1, 58]]
- proto_map = {1: 'ICMP', 58: 'ICMPv6EchoRequest', 6: 'TCP', 17: 'UDP'}
+ proto_map = {1: "ICMP", 58: "ICMPv6EchoRequest", 6: "TCP", 17: "UDP"}
ICMPv4 = 0
ICMPv6 = 1
TCP = 0
@@ -104,11 +104,11 @@ class TestClassifyAcl(TestClassifier):
# Create BD with MAC learning and unknown unicast flooding disabled
# and put interfaces to this BD
- cls.vapi.bridge_domain_add_del(bd_id=cls.bd_id, uu_flood=1,
- learn=1)
+ cls.vapi.bridge_domain_add_del(bd_id=cls.bd_id, uu_flood=1, learn=1)
for pg_if in cls.pg_interfaces:
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=pg_if.sw_if_index, bd_id=cls.bd_id)
+ rx_sw_if_index=pg_if.sw_if_index, bd_id=cls.bd_id
+ )
# Set up all interfaces
for i in cls.pg_interfaces:
@@ -128,7 +128,7 @@ class TestClassifyAcl(TestClassifier):
# self.warmup_test()
# Holder of the active classify table key
- cls.acl_active_table = ''
+ cls.acl_active_table = ""
except Exception:
super(TestClassifyAcl, cls).tearDownClass()
@@ -147,25 +147,30 @@ class TestClassifyAcl(TestClassifier):
Show various debug prints after each test.
"""
if not self.vpp_dead:
- if self.acl_active_table == 'mac_inout':
+ if self.acl_active_table == "mac_inout":
self.output_acl_set_interface(
- self.pg1, self.acl_tbl_idx.get(self.acl_active_table), 0)
+ self.pg1, self.acl_tbl_idx.get(self.acl_active_table), 0
+ )
self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0)
- self.acl_active_table = ''
- elif self.acl_active_table == 'mac_out':
+ self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0
+ )
+ self.acl_active_table = ""
+ elif self.acl_active_table == "mac_out":
self.output_acl_set_interface(
- self.pg1, self.acl_tbl_idx.get(self.acl_active_table), 0)
- self.acl_active_table = ''
- elif self.acl_active_table == 'mac_in':
+ self.pg1, self.acl_tbl_idx.get(self.acl_active_table), 0
+ )
+ self.acl_active_table = ""
+ elif self.acl_active_table == "mac_in":
self.input_acl_set_interface(
- self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0)
- self.acl_active_table = ''
+ self.pg0, self.acl_tbl_idx.get(self.acl_active_table), 0
+ )
+ self.acl_active_table = ""
super(TestClassifyAcl, self).tearDown()
- def create_classify_session(self, intf, table_index, match,
- hit_next_index=0xffffffff, is_add=1):
+ def create_classify_session(
+ self, intf, table_index, match, hit_next_index=0xFFFFFFFF, is_add=1
+ ):
"""Create Classify Session
:param VppInterface intf: Interface to apply classify session.
@@ -180,8 +185,9 @@ class TestClassifyAcl(TestClassifier):
table_index=table_index,
match=mask_match,
match_len=mask_match_len,
- hit_next_index=hit_next_index)
- self.assertIsNotNone(r, 'No response msg for add_del_session')
+ hit_next_index=hit_next_index,
+ )
+ self.assertIsNotNone(r, "No response msg for add_del_session")
def create_hosts(self, count, start=0):
"""
@@ -197,39 +203,50 @@ class TestClassifyAcl(TestClassifier):
for pg_if in self.pg_interfaces:
i += 1
start_nr = macs_per_if * i + start
- end_nr = count + start if i == (n_int - 1) \
- else macs_per_if * (i + 1) + start
+ end_nr = (
+ count + start if i == (n_int - 1) else macs_per_if * (i + 1) + start
+ )
hosts = self.hosts_by_pg_idx[pg_if.sw_if_index]
for j in range(start_nr, end_nr):
host = Host(
"00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j),
"172.17.1%02x.%u" % (pg_if.sw_if_index, j),
- "2017:dead:%02x::%u" % (pg_if.sw_if_index, j))
+ "2017:dead:%02x::%u" % (pg_if.sw_if_index, j),
+ )
hosts.append(host)
def create_upper_layer(self, packet_index, proto, ports=0):
p = self.proto_map[proto]
- if p == 'UDP':
+ if p == "UDP":
if ports == 0:
- return UDP(sport=random.randint(self.udp_sport_from,
- self.udp_sport_to),
- dport=random.randint(self.udp_dport_from,
- self.udp_dport_to))
+ return UDP(
+ sport=random.randint(self.udp_sport_from, self.udp_sport_to),
+ dport=random.randint(self.udp_dport_from, self.udp_dport_to),
+ )
else:
return UDP(sport=ports, dport=ports)
- elif p == 'TCP':
+ elif p == "TCP":
if ports == 0:
- return TCP(sport=random.randint(self.tcp_sport_from,
- self.tcp_sport_to),
- dport=random.randint(self.tcp_dport_from,
- self.tcp_dport_to))
+ return TCP(
+ sport=random.randint(self.tcp_sport_from, self.tcp_sport_to),
+ dport=random.randint(self.tcp_dport_from, self.tcp_dport_to),
+ )
else:
return TCP(sport=ports, dport=ports)
- return ''
-
- def create_stream(self, src_if, packet_sizes, traffic_type=0, ipv6=0,
- proto=-1, ports=0, fragments=False,
- pkt_raw=True, etype=-1):
+ return ""
+
+ def create_stream(
+ self,
+ src_if,
+ packet_sizes,
+ traffic_type=0,
+ ipv6=0,
+ proto=-1,
+ ports=0,
+ fragments=False,
+ pkt_raw=True,
+ etype=-1,
+ ):
"""
Create input packet stream for defined interface using hosts or
deleted_hosts list.
@@ -262,26 +279,25 @@ class TestClassifyAcl(TestClassifier):
payload = self.info_to_payload(pkt_info)
p = Ether(dst=dst_host.mac, src=src_host.mac)
if etype > 0:
- p = Ether(dst=dst_host.mac,
- src=src_host.mac,
- type=etype)
+ p = Ether(dst=dst_host.mac, src=src_host.mac, type=etype)
if pkt_info.ip:
p /= IPv6(dst=dst_host.ip6, src=src_host.ip6)
if fragments:
p /= IPv6ExtHdrFragment(offset=64, m=1)
else:
if fragments:
- p /= IP(src=src_host.ip4, dst=dst_host.ip4,
- flags=1, frag=64)
+ p /= IP(
+ src=src_host.ip4, dst=dst_host.ip4, flags=1, frag=64
+ )
else:
p /= IP(src=src_host.ip4, dst=dst_host.ip4)
if traffic_type == self.ICMP:
if pkt_info.ip:
- p /= ICMPv6EchoRequest(type=self.icmp6_type,
- code=self.icmp6_code)
+ p /= ICMPv6EchoRequest(
+ type=self.icmp6_type, code=self.icmp6_code
+ )
else:
- p /= ICMP(type=self.icmp4_type,
- code=self.icmp4_code)
+ p /= ICMP(type=self.icmp4_type, code=self.icmp4_code)
else:
p /= self.create_upper_layer(i, pkt_info.proto, ports)
if pkt_raw:
@@ -293,8 +309,7 @@ class TestClassifyAcl(TestClassifier):
pkts.append(p)
return pkts
- def verify_capture(self, pg_if, capture,
- traffic_type=0, ip_type=0, etype=-1):
+ def verify_capture(self, pg_if, capture, traffic_type=0, ip_type=0, etype=-1):
"""
Verify captured input packet stream for defined interface.
@@ -309,22 +324,21 @@ class TestClassifyAcl(TestClassifier):
for packet in capture:
if etype > 0:
if packet[Ether].type != etype:
- self.logger.error(ppp("Unexpected ethertype in packet:",
- packet))
+ self.logger.error(ppp("Unexpected ethertype in packet:", packet))
else:
continue
try:
# Raw data for ICMPv6 are stored in ICMPv6EchoRequest.data
if traffic_type == self.ICMP and ip_type == self.IPV6:
- payload_info = self.payload_to_info(
- packet[ICMPv6EchoRequest].data)
+ payload_info = self.payload_to_info(packet[ICMPv6EchoRequest].data)
payload = packet[ICMPv6EchoRequest]
else:
payload_info = self.payload_to_info(packet[Raw])
payload = packet[self.proto_map[payload_info.proto]]
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(outside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (outside network):", packet)
+ )
raise
if ip_type != 0:
@@ -338,8 +352,9 @@ class TestClassifyAcl(TestClassifier):
self.assertEqual(payload.type, self.icmp6_type)
self.assertEqual(payload.code, self.icmp6_code)
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(outside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (outside network):", packet)
+ )
raise
else:
try:
@@ -349,12 +364,13 @@ class TestClassifyAcl(TestClassifier):
packet_index = payload_info.index
self.assertEqual(payload_info.dst, dst_sw_if_index)
- self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
- (pg_if.name, payload_info.src,
- packet_index))
+ self.logger.debug(
+ "Got packet on port %s: src=%u (id=%u)"
+ % (pg_if.name, payload_info.src, packet_index)
+ )
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
self.assertEqual(packet_index, next_info.index)
@@ -363,29 +379,26 @@ class TestClassifyAcl(TestClassifier):
self.assertEqual(ip.src, saved_packet[ip_version].src)
self.assertEqual(ip.dst, saved_packet[ip_version].dst)
p = self.proto_map[payload_info.proto]
- if p == 'TCP':
+ if p == "TCP":
tcp = packet[TCP]
- self.assertEqual(tcp.sport, saved_packet[
- TCP].sport)
- self.assertEqual(tcp.dport, saved_packet[
- TCP].dport)
- elif p == 'UDP':
+ self.assertEqual(tcp.sport, saved_packet[TCP].sport)
+ self.assertEqual(tcp.dport, saved_packet[TCP].dport)
+ elif p == "UDP":
udp = packet[UDP]
- self.assertEqual(udp.sport, saved_packet[
- UDP].sport)
- self.assertEqual(udp.dport, saved_packet[
- UDP].dport)
+ self.assertEqual(udp.sport, saved_packet[UDP].sport)
+ self.assertEqual(udp.dport, saved_packet[UDP].dport)
except:
- self.logger.error(ppp("Unexpected or invalid packet:",
- packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
for i in self.pg_interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i, dst_sw_if_index, last_info[i.sw_if_index])
+ i, dst_sw_if_index, last_info[i.sw_if_index]
+ )
self.assertTrue(
remaining_packet is None,
- "Port %u: Packet expected from source %u didn't arrive" %
- (dst_sw_if_index, i.sw_if_index))
+ "Port %u: Packet expected from source %u didn't arrive"
+ % (dst_sw_if_index, i.sw_if_index),
+ )
def run_traffic_no_check(self):
# Test
@@ -400,16 +413,32 @@ class TestClassifyAcl(TestClassifier):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- def run_verify_test(self, traffic_type=0, ip_type=0, proto=-1, ports=0,
- frags=False, pkt_raw=True, etype=-1):
+ def run_verify_test(
+ self,
+ traffic_type=0,
+ ip_type=0,
+ proto=-1,
+ ports=0,
+ frags=False,
+ pkt_raw=True,
+ etype=-1,
+ ):
# Test
# Create incoming packet streams for packet-generator interfaces
pkts_cnt = 0
for i in self.pg_interfaces:
if self.flows.__contains__(i):
- pkts = self.create_stream(i, self.pg_if_packet_sizes,
- traffic_type, ip_type, proto, ports,
- frags, pkt_raw, etype)
+ pkts = self.create_stream(
+ i,
+ self.pg_if_packet_sizes,
+ traffic_type,
+ ip_type,
+ proto,
+ ports,
+ frags,
+ pkt_raw,
+ etype,
+ )
if len(pkts) > 0:
i.add_stream(pkts)
pkts_cnt += len(pkts)
@@ -424,20 +453,27 @@ class TestClassifyAcl(TestClassifier):
if self.flows.__contains__(src_if):
for dst_if in self.flows[src_if]:
capture = dst_if.get_capture(pkts_cnt)
- self.logger.info("Verifying capture on interface %s" %
- dst_if.name)
- self.verify_capture(dst_if, capture,
- traffic_type, ip_type, etype)
+ self.logger.info("Verifying capture on interface %s" % dst_if.name)
+ self.verify_capture(dst_if, capture, traffic_type, ip_type, etype)
- def run_verify_negat_test(self, traffic_type=0, ip_type=0, proto=-1,
- ports=0, frags=False, etype=-1):
+ def run_verify_negat_test(
+ self, traffic_type=0, ip_type=0, proto=-1, ports=0, frags=False, etype=-1
+ ):
# Test
self.reset_packet_infos()
for i in self.pg_interfaces:
if self.flows.__contains__(i):
- pkts = self.create_stream(i, self.pg_if_packet_sizes,
- traffic_type, ip_type, proto, ports,
- frags, True, etype)
+ pkts = self.create_stream(
+ i,
+ self.pg_if_packet_sizes,
+ traffic_type,
+ ip_type,
+ proto,
+ ports,
+ frags,
+ True,
+ etype,
+ )
if len(pkts) > 0:
i.add_stream(pkts)
@@ -450,101 +486,110 @@ class TestClassifyAcl(TestClassifier):
for src_if in self.pg_interfaces:
if self.flows.__contains__(src_if):
for dst_if in self.flows[src_if]:
- self.logger.info("Verifying capture on interface %s" %
- dst_if.name)
+ self.logger.info("Verifying capture on interface %s" % dst_if.name)
capture = dst_if.get_capture(0)
self.assertEqual(len(capture), 0)
- def build_classify_table(self, src_mac='', dst_mac='', ether_type='',
- etype='', key='mac', hit_next_index=0xffffffff):
+ def build_classify_table(
+ self,
+ src_mac="",
+ dst_mac="",
+ ether_type="",
+ etype="",
+ key="mac",
+ hit_next_index=0xFFFFFFFF,
+ ):
# Basic ACL testing
- a_mask = self.build_mac_mask(src_mac=src_mac, dst_mac=dst_mac,
- ether_type=ether_type)
+ a_mask = self.build_mac_mask(
+ src_mac=src_mac, dst_mac=dst_mac, ether_type=ether_type
+ )
self.create_classify_table(key, a_mask)
for host in self.hosts_by_pg_idx[self.pg0.sw_if_index]:
- s_mac = host.mac if src_mac else ''
+ s_mac = host.mac if src_mac else ""
if dst_mac:
for dst_if in self.flows[self.pg0]:
for dst_host in self.hosts_by_pg_idx[dst_if.sw_if_index]:
self.create_classify_session(
- self.pg0, self.acl_tbl_idx.get(key),
- self.build_mac_match(src_mac=s_mac,
- dst_mac=dst_host.mac,
- ether_type=etype),
- hit_next_index=hit_next_index)
+ self.pg0,
+ self.acl_tbl_idx.get(key),
+ self.build_mac_match(
+ src_mac=s_mac, dst_mac=dst_host.mac, ether_type=etype
+ ),
+ hit_next_index=hit_next_index,
+ )
else:
self.create_classify_session(
- self.pg0, self.acl_tbl_idx.get(key),
- self.build_mac_match(src_mac=s_mac, dst_mac='',
- ether_type=etype),
- hit_next_index=hit_next_index)
+ self.pg0,
+ self.acl_tbl_idx.get(key),
+ self.build_mac_match(src_mac=s_mac, dst_mac="", ether_type=etype),
+ hit_next_index=hit_next_index,
+ )
def test_0000_warmup_test(self):
- """ Learn the MAC addresses
- """
+ """Learn the MAC addresses"""
self.create_hosts(2)
self.run_traffic_no_check()
def test_0010_inacl_permit_src_mac(self):
- """ Input L2 ACL test - permit source MAC
+ """Input L2 ACL test - permit source MAC
Test scenario for basic IP ACL with source IP
- Create IPv4 stream for pg0 -> pg1 interface.
- Create ACL with source MAC address.
- Send and verify received packets on pg1 interface.
"""
- key = 'mac_in'
- self.build_classify_table(src_mac='ffffffffffff', key=key)
+ key = "mac_in"
+ self.build_classify_table(src_mac="ffffffffffff", key=key)
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.run_verify_test(self.IP, self.IPV4, -1)
def test_0011_inacl_permit_dst_mac(self):
- """ Input L2 ACL test - permit destination MAC
+ """Input L2 ACL test - permit destination MAC
Test scenario for basic IP ACL with source IP
- Create IPv4 stream for pg0 -> pg1 interface.
- Create ACL with destination MAC address.
- Send and verify received packets on pg1 interface.
"""
- key = 'mac_in'
- self.build_classify_table(dst_mac='ffffffffffff', key=key)
+ key = "mac_in"
+ self.build_classify_table(dst_mac="ffffffffffff", key=key)
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.run_verify_test(self.IP, self.IPV4, -1)
def test_0012_inacl_permit_src_dst_mac(self):
- """ Input L2 ACL test - permit source and destination MAC
+ """Input L2 ACL test - permit source and destination MAC
Test scenario for basic IP ACL with source IP
- Create IPv4 stream for pg0 -> pg1 interface.
- Create ACL with source and destination MAC addresses.
- Send and verify received packets on pg1 interface.
"""
- key = 'mac_in'
+ key = "mac_in"
self.build_classify_table(
- src_mac='ffffffffffff', dst_mac='ffffffffffff', key=key)
+ src_mac="ffffffffffff", dst_mac="ffffffffffff", key=key
+ )
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.run_verify_test(self.IP, self.IPV4, -1)
def test_0013_inacl_permit_ether_type(self):
- """ Input L2 ACL test - permit ether_type
+ """Input L2 ACL test - permit ether_type
Test scenario for basic IP ACL with source IP
- Create IPv4 stream for pg0 -> pg1 interface.
- Create ACL with destination MAC address.
- Send and verify received packets on pg1 interface.
"""
- key = 'mac_in'
- self.build_classify_table(
- ether_type='ffff', etype=hex(ETH_P_IP)[2:], key=key)
+ key = "mac_in"
+ self.build_classify_table(ether_type="ffff", etype=hex(ETH_P_IP)[2:], key=key)
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.run_verify_test(self.IP, self.IPV4, -1)
def test_0015_inacl_deny(self):
- """ Input L2 ACL test - deny
+ """Input L2 ACL test - deny
Test scenario for basic IP ACL with source IP
- Create IPv4 stream for pg0 -> pg1 interface.
@@ -552,57 +597,55 @@ class TestClassifyAcl(TestClassifier):
- Create ACL with source MAC address.
- Send and verify no received packets on pg1 interface.
"""
- key = 'mac_in'
- self.build_classify_table(
- src_mac='ffffffffffff', hit_next_index=0, key=key)
+ key = "mac_in"
+ self.build_classify_table(src_mac="ffffffffffff", hit_next_index=0, key=key)
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.run_verify_negat_test(self.IP, self.IPV4, -1)
def test_0020_outacl_permit(self):
- """ Output L2 ACL test - permit
+ """Output L2 ACL test - permit
Test scenario for basic IP ACL with source IP
- Create IPv4 stream for pg0 -> pg1 interface.
- Create ACL with source MAC address.
- Send and verify received packets on pg1 interface.
"""
- key = 'mac_out'
- self.build_classify_table(src_mac='ffffffffffff', key=key)
+ key = "mac_out"
+ self.build_classify_table(src_mac="ffffffffffff", key=key)
self.output_acl_set_interface(self.pg1, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.run_verify_test(self.IP, self.IPV4, -1)
def test_0025_outacl_deny(self):
- """ Output L2 ACL test - deny
+ """Output L2 ACL test - deny
Test scenario for basic IP ACL with source IP
- Create IPv4 stream for pg0 -> pg1 interface.
- Create ACL with source MAC address.
- Send and verify no received packets on pg1 interface.
"""
- key = 'mac_out'
- self.build_classify_table(
- src_mac='ffffffffffff', hit_next_index=0, key=key)
+ key = "mac_out"
+ self.build_classify_table(src_mac="ffffffffffff", hit_next_index=0, key=key)
self.output_acl_set_interface(self.pg1, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.run_verify_negat_test(self.IP, self.IPV4, -1)
def test_0030_inoutacl_permit(self):
- """ Input+Output L2 ACL test - permit
+ """Input+Output L2 ACL test - permit
Test scenario for basic IP ACL with source IP
- Create IPv4 stream for pg0 -> pg1 interface.
- Create ACLs with source MAC address.
- Send and verify received packets on pg1 interface.
"""
- key = 'mac_inout'
- self.build_classify_table(src_mac='ffffffffffff', key=key)
+ key = "mac_inout"
+ self.build_classify_table(src_mac="ffffffffffff", key=key)
self.output_acl_set_interface(self.pg1, self.acl_tbl_idx.get(key))
self.input_acl_set_interface(self.pg0, self.acl_tbl_idx.get(key))
self.acl_active_table = key
self.run_verify_test(self.IP, self.IPV4, -1)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_cli.py b/test/test_cli.py
index 5005bf4c43a..77dfdc0b9ad 100644
--- a/test/test_cli.py
+++ b/test/test_cli.py
@@ -11,7 +11,8 @@ from framework import VppTestCase, VppTestRunner
class TestCLI(VppTestCase):
- """ CLI Test Case """
+ """CLI Test Case"""
+
maxDiff = None
@classmethod
@@ -31,21 +32,21 @@ class TestCLI(VppTestCase):
super(TestCLI, self).tearDown()
def test_cli_retval(self):
- """ CLI inband retval """
- rv = self.vapi.papi.cli_inband(cmd='this command does not exist')
+ """CLI inband retval"""
+ rv = self.vapi.papi.cli_inband(cmd="this command does not exist")
self.assertNotEqual(rv.retval, 0)
- rv = self.vapi.papi.cli_inband(cmd='show version')
+ rv = self.vapi.papi.cli_inband(cmd="show version")
self.assertEqual(rv.retval, 0)
def test_long_cli_delay(self):
- """ Test that VppApiClient raises VppIOError if timeout.""" # noqa
+ """Test that VppApiClient raises VppIOError if timeout.""" # noqa
with self.assertRaises(VPPIOError) as ctx:
- rv = self.vapi.papi.cli_inband(cmd='wait 10')
+ rv = self.vapi.papi.cli_inband(cmd="wait 10")
def test_long_cli_delay_override(self):
- """ Test per-command _timeout option.""" # noqa
- rv = self.vapi.papi.cli_inband(cmd='wait 10', _timeout=15)
+ """Test per-command _timeout option.""" # noqa
+ rv = self.vapi.papi.cli_inband(cmd="wait 10", _timeout=15)
self.assertEqual(rv.retval, 0)
@@ -55,8 +56,10 @@ class TestCLIExtendedVapiTimeout(VppTestCase):
@classmethod
def setUpClass(cls):
cls.vapi_response_timeout = 15
- cls.__doc__ = " CLI Test Case w/ Extended (%ssec) Vapi Timeout " \
- % cls.vapi_response_timeout
+ cls.__doc__ = (
+ " CLI Test Case w/ Extended (%ssec) Vapi Timeout "
+ % cls.vapi_response_timeout
+ )
super(TestCLIExtendedVapiTimeout, cls).setUpClass()
@classmethod
@@ -70,19 +73,21 @@ class TestCLIExtendedVapiTimeout(VppTestCase):
super(TestCLIExtendedVapiTimeout, self).tearDown()
def test_long_cli_delay(self):
- """ Test that delayed result returns with extended timeout."""
+ """Test that delayed result returns with extended timeout."""
wait_secs = self.vapi_response_timeout - 1
# get vpp time as float
start = self.vapi.papi.show_vpe_system_time(
- _no_type_conversion=True).vpe_system_time
- rv = self.vapi.papi.cli_inband(cmd='wait %s' % wait_secs)
+ _no_type_conversion=True
+ ).vpe_system_time
+ rv = self.vapi.papi.cli_inband(cmd="wait %s" % wait_secs)
now = self.vapi.papi.show_vpe_system_time(
- _no_type_conversion=True).vpe_system_time
+ _no_type_conversion=True
+ ).vpe_system_time
# assume that the overhead of the measurement is not more that .5 sec.
self.assertEqual(round(now - start), wait_secs)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_cnat.py b/test/test_cnat.py
index 25c2a6454cb..e2e7c6bab8c 100644
--- a/test/test_cnat.py
+++ b/test/test_cnat.py
@@ -15,8 +15,14 @@ from scapy.layers.inet6 import ICMPv6EchoRequest, ICMPv6EchoReply
import struct
-from ipaddress import ip_address, ip_network, \
- IPv4Address, IPv6Address, IPv4Network, IPv6Network
+from ipaddress import (
+ ip_address,
+ ip_network,
+ IPv4Address,
+ IPv6Address,
+ IPv4Network,
+ IPv6Network,
+)
from vpp_object import VppObject
from vpp_papi import VppEnum
@@ -29,18 +35,27 @@ DST = 1
class CnatCommonTestCase(VppTestCase):
- """ CNat common test class """
+ """CNat common test class"""
#
# turn the scanner off whilst testing otherwise sessions
# will time out
#
- extra_vpp_punt_config = ["cnat", "{",
- "session-db-buckets", "64",
- "session-cleanup-timeout", "0.1",
- "session-max-age", "1",
- "tcp-max-age", "1",
- "scanner", "off", "}"]
+ extra_vpp_punt_config = [
+ "cnat",
+ "{",
+ "session-db-buckets",
+ "64",
+ "session-cleanup-timeout",
+ "0.1",
+ "session-max-age",
+ "1",
+ "tcp-max-age",
+ "1",
+ "scanner",
+ "off",
+ "}",
+ ]
@classmethod
def setUpClass(cls):
@@ -52,7 +67,7 @@ class CnatCommonTestCase(VppTestCase):
class Endpoint(object):
- """ CNat endpoint """
+ """CNat endpoint"""
def __init__(self, pg=None, pgi=None, port=0, is_v6=False, ip=None):
self.port = port
@@ -83,17 +98,18 @@ class Endpoint(object):
return VppEnum.vl_api_address_family_t.ADDRESS_IP4
def encode(self):
- return {'addr': self.ip,
- 'port': self.port,
- 'sw_if_index': self.sw_if_index,
- 'if_af': self._vpp_if_af()}
+ return {
+ "addr": self.ip,
+ "port": self.port,
+ "sw_if_index": self.sw_if_index,
+ "if_af": self._vpp_if_af(),
+ }
def __str__(self):
- return ("%s:%d" % (self.ip, self.port))
+ return "%s:%d" % (self.ip, self.port)
class Translation(VppObject):
-
def __init__(self, test, iproto, vip, paths):
self._test = test
self.vip = vip
@@ -102,7 +118,7 @@ class Translation(VppObject):
self.id = None
def __str__(self):
- return ("%s %s %s" % (self.vip, self.iproto, self.paths))
+ return "%s %s %s" % (self.vip, self.iproto, self.paths)
def _vl4_proto(self):
ip_proto = VppEnum.vl_api_ip_proto_t
@@ -112,21 +128,26 @@ class Translation(VppObject):
}[self.iproto]
def _encoded_paths(self):
- return [{'src_ep': src.encode(),
- 'dst_ep': dst.encode()} for (src, dst) in self.paths]
+ return [
+ {"src_ep": src.encode(), "dst_ep": dst.encode()}
+ for (src, dst) in self.paths
+ ]
def add_vpp_config(self):
r = self._test.vapi.cnat_translation_update(
- {'vip': self.vip.encode(),
- 'ip_proto': self._vl4_proto(),
- 'n_paths': len(self.paths),
- 'paths': self._encoded_paths()})
+ {
+ "vip": self.vip.encode(),
+ "ip_proto": self._vl4_proto(),
+ "n_paths": len(self.paths),
+ "paths": self._encoded_paths(),
+ }
+ )
self._test.registry.register(self, self._test.logger)
self.id = r.id
return self
def remove_vpp_config(self):
- assert(self.id is not None)
+ assert self.id is not None
self._test.vapi.cnat_translation_del(id=self.id)
return self
@@ -172,8 +193,9 @@ class CnatTestContext(object):
def IP46(self):
return IPv6 if self.is_v6 else IP
- def cnat_send(self, src_pg, src_id, src_port, dst_pg, dst_id, dst_port,
- no_replies=False):
+ def cnat_send(
+ self, src_pg, src_id, src_port, dst_pg, dst_id, dst_port, no_replies=False
+ ):
if isinstance(src_id, int):
self.src_addr = self.get_ip46(src_pg.remote_hosts[src_id])
else:
@@ -191,11 +213,12 @@ class CnatTestContext(object):
l4 = self.L4PROTO(id=self.src_port, type=self.dst_port)
elif self.L4PROTO in [ICMP] and self.is_v6:
l4 = ICMPv6EchoRequest(id=self.src_port)
- p1 = (Ether(src=src_pg.remote_mac,
- dst=src_pg.local_mac) /
- self.IP46(src=self.src_addr, dst=self.dst_addr) /
- l4 /
- Raw())
+ p1 = (
+ Ether(src=src_pg.remote_mac, dst=src_pg.local_mac)
+ / self.IP46(src=self.src_addr, dst=self.dst_addr)
+ / l4
+ / Raw()
+ )
if no_replies:
self._test.send_and_assert_no_replies(src_pg, p1 * N_PKTS, dst_pg)
@@ -230,38 +253,35 @@ class CnatTestContext(object):
self._test.assertEqual(rx[self.IP46].dst, self.expect_dst_addr)
self._test.assertEqual(rx[self.IP46].src, self.expect_src_addr)
if self.L4PROTO in [TCP, UDP]:
- self._test.assertEqual(
- rx[self.L4PROTO].dport, self.expect_dst_port)
- self._test.assertEqual(
- rx[self.L4PROTO].sport, self.expect_src_port)
+ self._test.assertEqual(rx[self.L4PROTO].dport, self.expect_dst_port)
+ self._test.assertEqual(rx[self.L4PROTO].sport, self.expect_src_port)
elif self.L4PROTO in [ICMP] and not self.is_v6:
- self._test.assertEqual(
- rx[self.L4PROTO].type, self.expect_dst_port)
- self._test.assertEqual(
- rx[self.L4PROTO].id, self.expect_src_port)
+ self._test.assertEqual(rx[self.L4PROTO].type, self.expect_dst_port)
+ self._test.assertEqual(rx[self.L4PROTO].id, self.expect_src_port)
elif self.L4PROTO in [ICMP] and self.is_v6:
- self._test.assertEqual(
- rx[ICMPv6EchoRequest].id, self.expect_src_port)
+ self._test.assertEqual(rx[ICMPv6EchoRequest].id, self.expect_src_port)
return self
def cnat_send_return(self):
"""This sends the return traffic"""
if self.L4PROTO in [TCP, UDP]:
- l4 = self.L4PROTO(sport=self.expect_dst_port,
- dport=self.expect_src_port)
+ l4 = self.L4PROTO(sport=self.expect_dst_port, dport=self.expect_src_port)
elif self.L4PROTO in [ICMP] and not self.is_v6:
# icmp type 0 if echo reply
l4 = self.L4PROTO(id=self.expect_src_port, type=0)
elif self.L4PROTO in [ICMP] and self.is_v6:
l4 = ICMPv6EchoReply(id=self.expect_src_port)
src_mac = self.expected_dst_pg.remote_mac
- p1 = (Ether(src=src_mac, dst=self.expected_dst_pg.local_mac) /
- self.IP46(src=self.expect_dst_addr, dst=self.expect_src_addr) /
- l4 /
- Raw())
+ p1 = (
+ Ether(src=src_mac, dst=self.expected_dst_pg.local_mac)
+ / self.IP46(src=self.expect_dst_addr, dst=self.expect_src_addr)
+ / l4
+ / Raw()
+ )
self.return_rxs = self._test.send_and_expect(
- self.expected_dst_pg, p1 * N_PKTS, self.expected_src_pg)
+ self.expected_dst_pg, p1 * N_PKTS, self.expected_src_pg
+ )
return self
def cnat_expect_return(self):
@@ -288,12 +308,16 @@ class CnatTestContext(object):
ICMPelem = ICMPv6DestUnreach(code=1) if self.is_v6 else ICMP(type=11)
InnerIP = self.rxs[0][self.IP46]
p1 = (
- Ether(src=self.expected_dst_pg.remote_mac,
- dst=self.expected_dst_pg.local_mac) /
- self.IP46(src=self.expect_dst_addr, dst=self.expect_src_addr) /
- ICMPelem / InnerIP)
+ Ether(
+ src=self.expected_dst_pg.remote_mac, dst=self.expected_dst_pg.local_mac
+ )
+ / self.IP46(src=self.expect_dst_addr, dst=self.expect_src_addr)
+ / ICMPelem
+ / InnerIP
+ )
self.return_rxs = self._test.send_and_expect(
- self.expected_dst_pg, p1 * N_PKTS, self.expected_src_pg)
+ self.expected_dst_pg, p1 * N_PKTS, self.expected_src_pg
+ )
return self
def cnat_expect_icmp_error_return(self):
@@ -306,12 +330,11 @@ class CnatTestContext(object):
self._test.assertEqual(rx[self.IP46].src, self.dst_addr)
self._test.assertEqual(rx[ICMP46][IP46err].src, self.src_addr)
self._test.assertEqual(rx[ICMP46][IP46err].dst, self.dst_addr)
- self._test.assertEqual(
- rx[ICMP46][IP46err][L4err].sport, self.src_port)
- self._test.assertEqual(
- rx[ICMP46][IP46err][L4err].dport, self.dst_port)
+ self._test.assertEqual(rx[ICMP46][IP46err][L4err].sport, self.src_port)
+ self._test.assertEqual(rx[ICMP46][IP46err][L4err].dport, self.dst_port)
return self
+
# -------------------------------------------------------------------
# -------------------------------------------------------------------
# -------------------------------------------------------------------
@@ -319,7 +342,7 @@ class CnatTestContext(object):
class TestCNatTranslation(CnatCommonTestCase):
- """ CNat Translation """
+ """CNat Translation"""
@classmethod
def setUpClass(cls):
@@ -359,7 +382,7 @@ class TestCNatTranslation(CnatCommonTestCase):
super(TestCNatTranslation, self).tearDown()
def cnat_translation(self):
- """ CNat Translation """
+ """CNat Translation"""
self.logger.info(self.vapi.cli("sh cnat client"))
self.logger.info(self.vapi.cli("sh cnat translation"))
@@ -372,11 +395,9 @@ class TestCNatTranslation(CnatCommonTestCase):
ctx = CnatTestContext(self, translation.iproto, vip.is_v6)
for src_pgi, sport in product(range(N_REMOTE_HOSTS), [1234, 1233]):
# from client to vip
- ctx.cnat_send(self.pg0, src_pgi, sport,
- self.pg1, vip.ip, vip.port)
+ ctx.cnat_send(self.pg0, src_pgi, sport, self.pg1, vip.ip, vip.port)
dst_port = translation.paths[0][DST].port
- ctx.cnat_expect(self.pg0, src_pgi, sport,
- self.pg1, nbr, dst_port)
+ ctx.cnat_expect(self.pg0, src_pgi, sport, self.pg1, nbr, dst_port)
# from vip to client
ctx.cnat_send_return().cnat_expect_return()
@@ -384,8 +405,9 @@ class TestCNatTranslation(CnatCommonTestCase):
# packets to the VIP that do not match a
# translation are dropped
#
- ctx.cnat_send(self.pg0, src_pgi, sport, self.pg1,
- vip.ip, 6666, no_replies=True)
+ ctx.cnat_send(
+ self.pg0, src_pgi, sport, self.pg1, vip.ip, 6666, no_replies=True
+ )
#
# packets from the VIP that do not match a
@@ -399,7 +421,8 @@ class TestCNatTranslation(CnatCommonTestCase):
#
old_dst_port = translation.paths[0][DST].port
translation.paths[0][DST].udpate(
- pg=self.pg2, pgi=0, port=5000, is_v6=vip.is_v6)
+ pg=self.pg2, pgi=0, port=5000, is_v6=vip.is_v6
+ )
translation.add_vpp_config()
#
@@ -408,10 +431,10 @@ class TestCNatTranslation(CnatCommonTestCase):
for src_pgi in range(N_REMOTE_HOSTS):
for sport in [1234, 1233]:
# from client to vip
- ctx.cnat_send(self.pg0, src_pgi, sport,
- self.pg1, vip.ip, vip.port)
- ctx.cnat_expect(self.pg0, src_pgi, sport,
- self.pg1, nbr, old_dst_port)
+ ctx.cnat_send(self.pg0, src_pgi, sport, self.pg1, vip.ip, vip.port)
+ ctx.cnat_expect(
+ self.pg0, src_pgi, sport, self.pg1, nbr, old_dst_port
+ )
# from vip to client
ctx.cnat_send_return().cnat_expect_return()
@@ -419,8 +442,7 @@ class TestCNatTranslation(CnatCommonTestCase):
# new flows go to the new backend
#
for src_pgi in range(N_REMOTE_HOSTS):
- ctx.cnat_send(self.pg0, src_pgi, 9999,
- self.pg2, vip.ip, vip.port)
+ ctx.cnat_send(self.pg0, src_pgi, 9999, self.pg2, vip.ip, vip.port)
ctx.cnat_expect(self.pg0, src_pgi, 9999, self.pg2, 0, 5000)
self.logger.info(self.vapi.cli("sh cnat session verbose"))
@@ -444,10 +466,8 @@ class TestCNatTranslation(CnatCommonTestCase):
for src_pgi in range(N_REMOTE_HOSTS):
for sport in [1234, 1233]:
# from client to vip
- ctx.cnat_send(self.pg0, src_pgi, sport,
- self.pg2, vip.ip, vip.port)
- ctx.cnat_expect(self.pg0, src_pgi,
- sport, self.pg2, 0, 5000)
+ ctx.cnat_send(self.pg0, src_pgi, sport, self.pg2, vip.ip, vip.port)
+ ctx.cnat_expect(self.pg0, src_pgi, sport, self.pg2, 0, 5000)
def _test_icmp(self):
@@ -477,51 +497,87 @@ class TestCNatTranslation(CnatCommonTestCase):
def _make_translations_v4(self):
self.translations = []
- self.translations.append(Translation(
- self, TCP, Endpoint(ip="30.0.0.1", port=5555, is_v6=False),
- [(
- Endpoint(is_v6=False),
- Endpoint(pg=self.pg1, pgi=0, port=4001, is_v6=False),
- )]
- ).add_vpp_config())
- self.translations.append(Translation(
- self, TCP, Endpoint(ip="30.0.0.2", port=5554, is_v6=False),
- [(
- Endpoint(is_v6=False),
- Endpoint(pg=self.pg1, pgi=1, port=4002, is_v6=False),
- )]
- ).add_vpp_config())
- self.translations.append(Translation(
- self, UDP, Endpoint(ip="30.0.0.2", port=5553, is_v6=False),
- [(
- Endpoint(is_v6=False),
- Endpoint(pg=self.pg1, pgi=2, port=4003, is_v6=False),
- )]
- ).add_vpp_config())
+ self.translations.append(
+ Translation(
+ self,
+ TCP,
+ Endpoint(ip="30.0.0.1", port=5555, is_v6=False),
+ [
+ (
+ Endpoint(is_v6=False),
+ Endpoint(pg=self.pg1, pgi=0, port=4001, is_v6=False),
+ )
+ ],
+ ).add_vpp_config()
+ )
+ self.translations.append(
+ Translation(
+ self,
+ TCP,
+ Endpoint(ip="30.0.0.2", port=5554, is_v6=False),
+ [
+ (
+ Endpoint(is_v6=False),
+ Endpoint(pg=self.pg1, pgi=1, port=4002, is_v6=False),
+ )
+ ],
+ ).add_vpp_config()
+ )
+ self.translations.append(
+ Translation(
+ self,
+ UDP,
+ Endpoint(ip="30.0.0.2", port=5553, is_v6=False),
+ [
+ (
+ Endpoint(is_v6=False),
+ Endpoint(pg=self.pg1, pgi=2, port=4003, is_v6=False),
+ )
+ ],
+ ).add_vpp_config()
+ )
def _make_translations_v6(self):
self.translations = []
- self.translations.append(Translation(
- self, TCP, Endpoint(ip="30::1", port=5555, is_v6=True),
- [(
- Endpoint(is_v6=True),
- Endpoint(pg=self.pg1, pgi=0, port=4001, is_v6=True),
- )]
- ).add_vpp_config())
- self.translations.append(Translation(
- self, TCP, Endpoint(ip="30::2", port=5554, is_v6=True),
- [(
- Endpoint(is_v6=True),
- Endpoint(pg=self.pg1, pgi=1, port=4002, is_v6=True),
- )]
- ).add_vpp_config())
- self.translations.append(Translation(
- self, UDP, Endpoint(ip="30::2", port=5553, is_v6=True),
- [(
- Endpoint(is_v6=True),
- Endpoint(pg=self.pg1, pgi=2, port=4003, is_v6=True),
- )]
- ).add_vpp_config())
+ self.translations.append(
+ Translation(
+ self,
+ TCP,
+ Endpoint(ip="30::1", port=5555, is_v6=True),
+ [
+ (
+ Endpoint(is_v6=True),
+ Endpoint(pg=self.pg1, pgi=0, port=4001, is_v6=True),
+ )
+ ],
+ ).add_vpp_config()
+ )
+ self.translations.append(
+ Translation(
+ self,
+ TCP,
+ Endpoint(ip="30::2", port=5554, is_v6=True),
+ [
+ (
+ Endpoint(is_v6=True),
+ Endpoint(pg=self.pg1, pgi=1, port=4002, is_v6=True),
+ )
+ ],
+ ).add_vpp_config()
+ )
+ self.translations.append(
+ Translation(
+ self,
+ UDP,
+ Endpoint(ip="30::2", port=5553, is_v6=True),
+ [
+ (
+ Endpoint(is_v6=True),
+ Endpoint(pg=self.pg1, pgi=2, port=4003, is_v6=True),
+ )
+ ],
+ ).add_vpp_config()
+ )
def test_icmp4(self):
# """ CNat Translation icmp v4 """
@@ -545,7 +601,7 @@ class TestCNatTranslation(CnatCommonTestCase):
class TestCNatSourceNAT(CnatCommonTestCase):
- """ CNat Source NAT """
+ """CNat Source NAT"""
@classmethod
def setUpClass(cls):
@@ -559,28 +615,36 @@ class TestCNatSourceNAT(CnatCommonTestCase):
self.vapi.cnat_set_snat_addresses(
snat_ip4=self.pg2.remote_hosts[0].ip4,
snat_ip6=self.pg2.remote_hosts[0].ip6,
- sw_if_index=INVALID_INDEX)
+ sw_if_index=INVALID_INDEX,
+ )
self.vapi.feature_enable_disable(
enable=1 if is_enable else 0,
arc_name="ip6-unicast",
feature_name="cnat-snat-ip6",
- sw_if_index=self.pg0.sw_if_index)
+ sw_if_index=self.pg0.sw_if_index,
+ )
self.vapi.feature_enable_disable(
enable=1 if is_enable else 0,
arc_name="ip4-unicast",
feature_name="cnat-snat-ip4",
- sw_if_index=self.pg0.sw_if_index)
+ sw_if_index=self.pg0.sw_if_index,
+ )
policie_tbls = VppEnum.vl_api_cnat_snat_policy_table_t
self.vapi.cnat_set_snat_policy(
- policy=VppEnum.vl_api_cnat_snat_policies_t.CNAT_POLICY_IF_PFX)
+ policy=VppEnum.vl_api_cnat_snat_policies_t.CNAT_POLICY_IF_PFX
+ )
for i in self.pg_interfaces:
self.vapi.cnat_snat_policy_add_del_if(
- sw_if_index=i.sw_if_index, is_add=1 if is_enable else 0,
- table=policie_tbls.CNAT_POLICY_INCLUDE_V6)
+ sw_if_index=i.sw_if_index,
+ is_add=1 if is_enable else 0,
+ table=policie_tbls.CNAT_POLICY_INCLUDE_V6,
+ )
self.vapi.cnat_snat_policy_add_del_if(
- sw_if_index=i.sw_if_index, is_add=1 if is_enable else 0,
- table=policie_tbls.CNAT_POLICY_INCLUDE_V4)
+ sw_if_index=i.sw_if_index,
+ is_add=1 if is_enable else 0,
+ table=policie_tbls.CNAT_POLICY_INCLUDE_V4,
+ )
def setUp(self):
super(TestCNatSourceNAT, self).setUp()
@@ -624,7 +688,7 @@ class TestCNatSourceNAT(CnatCommonTestCase):
def sourcenat_test_icmp_echo_conf(self, is_v6=False):
ctx = CnatTestContext(self, ICMP, is_v6=is_v6)
# 8 is ICMP type echo (v4 only)
- ctx.cnat_send(self.pg0, 0, 0xfeed, self.pg1, 0, 8)
+ ctx.cnat_send(self.pg0, 0, 0xFEED, self.pg1, 0, 8)
ctx.cnat_expect(self.pg2, 0, None, self.pg1, 0, 8)
ctx.cnat_send_return().cnat_expect_return()
@@ -638,14 +702,15 @@ class TestCNatSourceNAT(CnatCommonTestCase):
# exclude dst address of pg1.1 from snat
if is_v6:
exclude_prefix = ip_network(
- "%s/100" % self.pg1.remote_hosts[1].ip6, strict=False)
+ "%s/100" % self.pg1.remote_hosts[1].ip6, strict=False
+ )
else:
exclude_prefix = ip_network(
- "%s/16" % self.pg1.remote_hosts[1].ip4, strict=False)
+ "%s/16" % self.pg1.remote_hosts[1].ip4, strict=False
+ )
# add remote host to exclude list
- self.vapi.cnat_snat_policy_add_del_exclude_pfx(
- prefix=exclude_prefix, is_add=1)
+ self.vapi.cnat_snat_policy_add_del_exclude_pfx(prefix=exclude_prefix, is_add=1)
# We should not source NAT the id=1
ctx.cnat_send(self.pg0, 0, 1234, self.pg1, 1, 6661)
@@ -658,8 +723,7 @@ class TestCNatSourceNAT(CnatCommonTestCase):
ctx.cnat_send_return().cnat_expect_return()
# remove remote host from exclude list
- self.vapi.cnat_snat_policy_add_del_exclude_pfx(
- prefix=exclude_prefix, is_add=0)
+ self.vapi.cnat_snat_policy_add_del_exclude_pfx(prefix=exclude_prefix, is_add=0)
self.vapi.cnat_session_purge()
# We should source NAT again
@@ -676,7 +740,7 @@ class TestCNatSourceNAT(CnatCommonTestCase):
class TestCNatDHCP(CnatCommonTestCase):
- """ CNat Translation """
+ """CNat Translation"""
@classmethod
def setUpClass(cls):
@@ -703,33 +767,35 @@ class TestCNatDHCP(CnatCommonTestCase):
def check_resolved(self, tr, addr_id, is_v6=False):
qt = tr.query_vpp_config()
- self.assertEqual(str(qt.vip.addr), self.make_addr(
- tr.vip.sw_if_index, addr_id, is_v6))
+ self.assertEqual(
+ str(qt.vip.addr), self.make_addr(tr.vip.sw_if_index, addr_id, is_v6)
+ )
self.assertEqual(len(qt.paths), len(tr.paths))
for path_tr, path_qt in zip(tr.paths, qt.paths):
src_qt = path_qt.src_ep
dst_qt = path_qt.dst_ep
src_tr, dst_tr = path_tr
- self.assertEqual(str(src_qt.addr), self.make_addr(
- src_tr.sw_if_index, addr_id, is_v6))
- self.assertEqual(str(dst_qt.addr), self.make_addr(
- dst_tr.sw_if_index, addr_id, is_v6))
+ self.assertEqual(
+ str(src_qt.addr), self.make_addr(src_tr.sw_if_index, addr_id, is_v6)
+ )
+ self.assertEqual(
+ str(dst_qt.addr), self.make_addr(dst_tr.sw_if_index, addr_id, is_v6)
+ )
def add_del_address(self, pg, addr_id, is_add=True, is_v6=False):
self.vapi.sw_interface_add_del_address(
sw_if_index=pg.sw_if_index,
prefix=self.make_prefix(pg.sw_if_index, addr_id, is_v6),
- is_add=1 if is_add else 0)
+ is_add=1 if is_add else 0,
+ )
def _test_dhcp_v46(self, is_v6):
self.create_pg_interfaces(range(4))
for i in self.pg_interfaces:
i.admin_up()
paths = [
- (Endpoint(pg=self.pg1, is_v6=is_v6),
- Endpoint(pg=self.pg2, is_v6=is_v6)),
- (Endpoint(pg=self.pg1, is_v6=is_v6),
- Endpoint(pg=self.pg3, is_v6=is_v6))
+ (Endpoint(pg=self.pg1, is_v6=is_v6), Endpoint(pg=self.pg2, is_v6=is_v6)),
+ (Endpoint(pg=self.pg1, is_v6=is_v6), Endpoint(pg=self.pg3, is_v6=is_v6)),
]
ep = Endpoint(pg=self.pg0, is_v6=is_v6)
t = Translation(self, TCP, ep, paths).add_vpp_config()
@@ -766,10 +832,13 @@ class TestCNatDHCP(CnatCommonTestCase):
self.add_del_address(pg, addr_id=0, is_add=True, is_v6=False)
self.add_del_address(pg, addr_id=0, is_add=True, is_v6=True)
r = self.vapi.cnat_get_snat_addresses()
- self.assertEqual(str(r.snat_ip4), self.make_addr(
- self.pg0.sw_if_index, addr_id=0, is_v6=False))
- self.assertEqual(str(r.snat_ip6), self.make_addr(
- self.pg0.sw_if_index, addr_id=0, is_v6=True))
+ self.assertEqual(
+ str(r.snat_ip4),
+ self.make_addr(self.pg0.sw_if_index, addr_id=0, is_v6=False),
+ )
+ self.assertEqual(
+ str(r.snat_ip6), self.make_addr(self.pg0.sw_if_index, addr_id=0, is_v6=True)
+ )
# Add a new address on every interface, remove the old one
# and check it is reflected in the cnat config
for pg in self.pg_interfaces:
@@ -778,10 +847,13 @@ class TestCNatDHCP(CnatCommonTestCase):
self.add_del_address(pg, addr_id=0, is_add=False, is_v6=False)
self.add_del_address(pg, addr_id=0, is_add=False, is_v6=True)
r = self.vapi.cnat_get_snat_addresses()
- self.assertEqual(str(r.snat_ip4), self.make_addr(
- self.pg0.sw_if_index, addr_id=1, is_v6=False))
- self.assertEqual(str(r.snat_ip6), self.make_addr(
- self.pg0.sw_if_index, addr_id=1, is_v6=True))
+ self.assertEqual(
+ str(r.snat_ip4),
+ self.make_addr(self.pg0.sw_if_index, addr_id=1, is_v6=False),
+ )
+ self.assertEqual(
+ str(r.snat_ip6), self.make_addr(self.pg0.sw_if_index, addr_id=1, is_v6=True)
+ )
# remove the configuration
for pg in self.pg_interfaces:
self.add_del_address(pg, addr_id=1, is_add=False, is_v6=False)
@@ -789,5 +861,5 @@ class TestCNatDHCP(CnatCommonTestCase):
self.vapi.cnat_set_snat_addresses(sw_if_index=INVALID_INDEX)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_container.py b/test/test_container.py
index 739aaaf915a..d79e5c3c67d 100644
--- a/test/test_container.py
+++ b/test/test_container.py
@@ -24,7 +24,7 @@ class Conn(L4_Conn):
@unittest.skipUnless(config.extended, "part of extended tests")
class ContainerIntegrationTestCase(VppTestCase):
- """ Container integration extended testcases """
+ """Container integration extended testcases"""
@classmethod
def setUpClass(cls):
@@ -43,22 +43,21 @@ class ContainerIntegrationTestCase(VppTestCase):
super(ContainerIntegrationTestCase, cls).tearDownClass()
def tearDown(self):
- """Run standard test teardown and log various show commands
- """
+ """Run standard test teardown and log various show commands"""
super(ContainerIntegrationTestCase, self).tearDown()
def show_commands_at_teardown(self):
self.logger.info(self.vapi.cli("show ip neighbors"))
def run_basic_conn_test(self, af, acl_side):
- """ Basic connectivity test """
+ """Basic connectivity test"""
conn1 = Conn(self, self.pg0, self.pg1, af, UDP, 42001, 4242)
conn1.send_through(0)
# the return packets should pass
conn1.send_through(1)
def run_negative_conn_test(self, af, acl_side):
- """ Packets with local spoofed address """
+ """Packets with local spoofed address"""
conn1 = Conn(self, self.pg0, self.pg1, af, UDP, 42001, 4242)
try:
p2 = conn1.send_through(0).command()
@@ -69,15 +68,15 @@ class ContainerIntegrationTestCase(VppTestCase):
self.assert_equal(p2, None, ": packet should have been dropped")
def test_0010_basic_conn_test(self):
- """ IPv4 basic connectivity test """
+ """IPv4 basic connectivity test"""
self.run_basic_conn_test(AF_INET, 0)
def test_0011_basic_conn_test(self):
- """ IPv6 basic connectivity test """
+ """IPv6 basic connectivity test"""
self.run_basic_conn_test(AF_INET6, 0)
def test_0050_loopback_prepare_test(self):
- """ Create loopbacks overlapping with remote addresses """
+ """Create loopbacks overlapping with remote addresses"""
self.create_loopback_interfaces(2)
for i in range(2):
intf = self.lo_interfaces[i]
@@ -90,47 +89,60 @@ class ContainerIntegrationTestCase(VppTestCase):
intf.config_ip6()
def test_0110_basic_conn_test(self):
- """ IPv4 local-spoof connectivity test """
+ """IPv4 local-spoof connectivity test"""
self.run_negative_conn_test(AF_INET, 0)
def test_0111_basic_conn_test(self):
- """ IPv6 local-spoof connectivity test """
+ """IPv6 local-spoof connectivity test"""
self.run_negative_conn_test(AF_INET, 1)
def test_0200_basic_conn_test(self):
- """ Configure container commands """
+ """Configure container commands"""
for i in range(2):
- for addr in [self.pg_interfaces[i].remote_ip4,
- self.pg_interfaces[i].remote_ip6]:
- self.vapi.ppcli("ip container " + addr + " " +
- self.pg_interfaces[i].name)
- self.vapi.ppcli("stn rule address " + addr +
- " interface " + self.pg_interfaces[i].name)
+ for addr in [
+ self.pg_interfaces[i].remote_ip4,
+ self.pg_interfaces[i].remote_ip6,
+ ]:
+ self.vapi.ppcli(
+ "ip container " + addr + " " + self.pg_interfaces[i].name
+ )
+ self.vapi.ppcli(
+ "stn rule address "
+ + addr
+ + " interface "
+ + self.pg_interfaces[i].name
+ )
def test_0210_basic_conn_test(self):
- """ IPv4 test after configuring container """
+ """IPv4 test after configuring container"""
self.run_basic_conn_test(AF_INET, 0)
def test_0211_basic_conn_test(self):
- """ IPv6 test after configuring container """
+ """IPv6 test after configuring container"""
self.run_basic_conn_test(AF_INET, 1)
def test_0300_unconfigure_commands(self):
- """ Unconfigure container commands """
+ """Unconfigure container commands"""
for i in range(2):
- for addr in [self.pg_interfaces[i].remote_ip4,
- self.pg_interfaces[i].remote_ip6]:
- self.vapi.ppcli("ip container " + addr + " " +
- self.pg_interfaces[i].name +
- " del")
- self.vapi.ppcli("stn rule address " + addr +
- " interface " + self.pg_interfaces[i].name +
- " del")
+ for addr in [
+ self.pg_interfaces[i].remote_ip4,
+ self.pg_interfaces[i].remote_ip6,
+ ]:
+ self.vapi.ppcli(
+ "ip container " + addr + " " + self.pg_interfaces[i].name + " del"
+ )
+ self.vapi.ppcli(
+ "stn rule address "
+ + addr
+ + " interface "
+ + self.pg_interfaces[i].name
+ + " del"
+ )
def test_0410_spoof_test(self):
- """ IPv4 local-spoof after unconfig test """
+ """IPv4 local-spoof after unconfig test"""
self.run_negative_conn_test(AF_INET, 0)
def test_0411_spoof_test(self):
- """ IPv6 local-spoof after unconfig test """
+ """IPv6 local-spoof after unconfig test"""
self.run_negative_conn_test(AF_INET, 1)
diff --git a/test/test_counters.py b/test/test_counters.py
index e4cb85621d0..158b07eb063 100644
--- a/test/test_counters.py
+++ b/test/test_counters.py
@@ -6,7 +6,7 @@ from framework import tag_fixme_vpp_workers
@tag_fixme_vpp_workers
class TestCounters(VppTestCase):
- """ Counters C Unit Tests """
+ """Counters C Unit Tests"""
@classmethod
def setUpClass(cls):
@@ -23,17 +23,17 @@ class TestCounters(VppTestCase):
super(TestCounters, self).tearDown()
def test_counter_simple_expand(self):
- """ Simple Counter Expand """
+ """Simple Counter Expand"""
error = self.vapi.cli("test counter simple expand")
if error:
self.logger.critical(error)
- self.assertNotIn('failed', error)
+ self.assertNotIn("failed", error)
def test_counter_combined_expand(self):
- """ Combined Counter Expand """
+ """Combined Counter Expand"""
error = self.vapi.cli("test counter combined expand")
if error:
self.logger.critical(error)
- self.assertNotIn('failed', error)
+ self.assertNotIn("failed", error)
diff --git a/test/test_crypto.py b/test/test_crypto.py
index aa62dba1bab..07ddd2c0f08 100644
--- a/test/test_crypto.py
+++ b/test/test_crypto.py
@@ -6,7 +6,7 @@ from framework import VppTestCase, VppTestRunner
class TestCrypto(VppTestCase):
- """ Crypto Test Case """
+ """Crypto Test Case"""
@classmethod
def setUpClass(cls):
@@ -17,12 +17,13 @@ class TestCrypto(VppTestCase):
super(TestCrypto, cls).tearDownClass()
def test_crypto(self):
- """ Crypto Unit Tests """
+ """Crypto Unit Tests"""
error = self.vapi.cli("test crypto")
if error:
self.logger.critical(error)
self.assertNotIn("FAIL", error)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_det44.py b/test/test_det44.py
index f137e760c38..ecd57a65b05 100644
--- a/test/test_det44.py
+++ b/test/test_det44.py
@@ -15,7 +15,7 @@ from util import ppp
class TestDET44(VppTestCase):
- """ Deterministic NAT Test Cases """
+ """Deterministic NAT Test Cases"""
@classmethod
def setUpClass(cls):
@@ -27,7 +27,7 @@ class TestDET44(VppTestCase):
cls.udp_port_in = 6304
cls.udp_external_port = 6304
cls.icmp_id_in = 6305
- cls.nat_addr = '10.0.0.3'
+ cls.nat_addr = "10.0.0.3"
cls.create_pg_interfaces(range(3))
cls.interfaces = list(cls.pg_interfaces)
@@ -79,8 +79,9 @@ class TestDET44(VppTestCase):
self.assertEqual(packet[ICMP].id, self.icmp_id_in)
except:
fired = True
- self.logger.error(ppp("Unexpected or invalid packet "
- "(inside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (inside network):", packet)
+ )
if fired:
raise
@@ -112,10 +113,11 @@ class TestDET44(VppTestCase):
"""
# SYN packet in->out
- p = (Ether(src=in_if.remote_mac, dst=in_if.local_mac) /
- IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="S"))
+ p = (
+ Ether(src=in_if.remote_mac, dst=in_if.local_mac)
+ / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="S")
+ )
in_if.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -124,20 +126,22 @@ class TestDET44(VppTestCase):
self.tcp_port_out = p[TCP].sport
# SYN + ACK packet out->in
- p = (Ether(src=out_if.remote_mac, dst=out_if.local_mac) /
- IP(src=out_if.remote_ip4, dst=self.nat_addr) /
- TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
- flags="SA"))
+ p = (
+ Ether(src=out_if.remote_mac, dst=out_if.local_mac)
+ / IP(src=out_if.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="SA")
+ )
out_if.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
in_if.get_capture(1)
# ACK packet in->out
- p = (Ether(src=in_if.remote_mac, dst=in_if.local_mac) /
- IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="A"))
+ p = (
+ Ether(src=in_if.remote_mac, dst=in_if.local_mac)
+ / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="A")
+ )
in_if.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -153,21 +157,27 @@ class TestDET44(VppTestCase):
"""
pkts = []
# TCP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port)
+ )
pkts.append(p)
# UDP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) /
- UDP(sport=self.udp_port_in, dport=self.udp_external_port))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl)
+ / UDP(sport=self.udp_port_in, dport=self.udp_external_port)
+ )
pkts.append(p)
# ICMP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl) /
- ICMP(id=self.icmp_id_in, type='echo-request'))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=ttl)
+ / ICMP(id=self.icmp_id_in, type="echo-request")
+ )
pkts.append(p)
return pkts
@@ -184,21 +194,27 @@ class TestDET44(VppTestCase):
dst_ip = self.nat_addr
pkts = []
# TCP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- TCP(dport=self.tcp_port_out, sport=self.tcp_external_port))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / TCP(dport=self.tcp_port_out, sport=self.tcp_external_port)
+ )
pkts.append(p)
# UDP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- UDP(dport=self.udp_port_out, sport=self.udp_external_port))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / UDP(dport=self.udp_port_out, sport=self.udp_external_port)
+ )
pkts.append(p)
# ICMP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- ICMP(id=self.icmp_external_id, type='echo-reply'))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / ICMP(id=self.icmp_external_id, type="echo-reply")
+ )
pkts.append(p)
return pkts
@@ -223,21 +239,26 @@ class TestDET44(VppTestCase):
else:
self.icmp_external_id = packet[ICMP].id
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(outside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (outside network):", packet)
+ )
raise
def test_deterministic_mode(self):
- """ NAT plugin run deterministic mode """
- in_addr = '172.16.255.0'
- out_addr = '172.17.255.50'
- in_addr_t = '172.16.255.20'
+ """NAT plugin run deterministic mode"""
+ in_addr = "172.16.255.0"
+ out_addr = "172.17.255.50"
+ in_addr_t = "172.16.255.20"
in_plen = 24
out_plen = 32
- self.vapi.det44_add_del_map(is_add=1, in_addr=in_addr,
- in_plen=in_plen, out_addr=out_addr,
- out_plen=out_plen)
+ self.vapi.det44_add_del_map(
+ is_add=1,
+ in_addr=in_addr,
+ in_plen=in_plen,
+ out_addr=out_addr,
+ out_plen=out_plen,
+ )
rep1 = self.vapi.det44_forward(in_addr_t)
self.assertEqual(str(rep1.out_addr), out_addr)
@@ -254,40 +275,46 @@ class TestDET44(VppTestCase):
self.assertEqual(out_plen, dsm.out_plen)
def test_set_timeouts(self):
- """ Set deterministic NAT timeouts """
+ """Set deterministic NAT timeouts"""
timeouts_before = self.vapi.det44_get_timeouts()
self.vapi.det44_set_timeouts(
udp=timeouts_before.udp + 10,
tcp_established=timeouts_before.tcp_established + 10,
tcp_transitory=timeouts_before.tcp_transitory + 10,
- icmp=timeouts_before.icmp + 10)
+ icmp=timeouts_before.icmp + 10,
+ )
timeouts_after = self.vapi.det44_get_timeouts()
self.assertNotEqual(timeouts_before.udp, timeouts_after.udp)
self.assertNotEqual(timeouts_before.icmp, timeouts_after.icmp)
- self.assertNotEqual(timeouts_before.tcp_established,
- timeouts_after.tcp_established)
- self.assertNotEqual(timeouts_before.tcp_transitory,
- timeouts_after.tcp_transitory)
+ self.assertNotEqual(
+ timeouts_before.tcp_established, timeouts_after.tcp_established
+ )
+ self.assertNotEqual(
+ timeouts_before.tcp_transitory, timeouts_after.tcp_transitory
+ )
def test_in(self):
- """ DET44 translation test (TCP, UDP, ICMP) """
+ """DET44 translation test (TCP, UDP, ICMP)"""
nat_ip = "10.0.0.10"
- self.vapi.det44_add_del_map(is_add=1, in_addr=self.pg0.remote_ip4,
- in_plen=32,
- out_addr=socket.inet_aton(nat_ip),
- out_plen=32)
+ self.vapi.det44_add_del_map(
+ is_add=1,
+ in_addr=self.pg0.remote_ip4,
+ in_plen=32,
+ out_addr=socket.inet_aton(nat_ip),
+ out_plen=32,
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1, is_inside=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1, is_inside=0)
+ sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0
+ )
# in2out
pkts = self.create_stream_in(self.pg0, self.pg1)
@@ -330,7 +357,7 @@ class TestDET44(VppTestCase):
self.assertEqual(s.out_port, self.icmp_external_id)
def test_multiple_users(self):
- """ Deterministic NAT multiple users """
+ """Deterministic NAT multiple users"""
nat_ip = "10.0.0.10"
port_in = 80
@@ -339,20 +366,26 @@ class TestDET44(VppTestCase):
host0 = self.pg0.remote_hosts[0]
host1 = self.pg0.remote_hosts[1]
- self.vapi.det44_add_del_map(is_add=1, in_addr=host0.ip4, in_plen=24,
- out_addr=socket.inet_aton(nat_ip),
- out_plen=32)
+ self.vapi.det44_add_del_map(
+ is_add=1,
+ in_addr=host0.ip4,
+ in_plen=24,
+ out_addr=socket.inet_aton(nat_ip),
+ out_plen=32,
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1, is_inside=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1, is_inside=0)
+ sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0
+ )
# host0 to out
- p = (Ether(src=host0.mac, dst=self.pg0.local_mac) /
- IP(src=host0.ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=port_in, dport=external_port))
+ p = (
+ Ether(src=host0.mac, dst=self.pg0.local_mac)
+ / IP(src=host0.ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=port_in, dport=external_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -370,9 +403,11 @@ class TestDET44(VppTestCase):
raise
# host1 to out
- p = (Ether(src=host1.mac, dst=self.pg0.local_mac) /
- IP(src=host1.ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=port_in, dport=external_port))
+ p = (
+ Ether(src=host1.mac, dst=self.pg0.local_mac)
+ / IP(src=host1.ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=port_in, dport=external_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -394,9 +429,11 @@ class TestDET44(VppTestCase):
self.assertEqual(2, dms[0].ses_num)
# out to host0
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=nat_ip) /
- TCP(sport=external_port, dport=port_out0))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=nat_ip)
+ / TCP(sport=external_port, dport=port_out0)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -414,9 +451,11 @@ class TestDET44(VppTestCase):
raise
# out to host1
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=nat_ip) /
- TCP(sport=external_port, dport=port_out1))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=nat_ip)
+ / TCP(sport=external_port, dport=port_out1)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -434,42 +473,44 @@ class TestDET44(VppTestCase):
raise
# session close api test
- self.vapi.det44_close_session_out(socket.inet_aton(nat_ip),
- port_out1,
- self.pg1.remote_ip4,
- external_port)
+ self.vapi.det44_close_session_out(
+ socket.inet_aton(nat_ip), port_out1, self.pg1.remote_ip4, external_port
+ )
dms = self.vapi.det44_map_dump()
self.assertEqual(dms[0].ses_num, 1)
- self.vapi.det44_close_session_in(host0.ip4,
- port_in,
- self.pg1.remote_ip4,
- external_port)
+ self.vapi.det44_close_session_in(
+ host0.ip4, port_in, self.pg1.remote_ip4, external_port
+ )
dms = self.vapi.det44_map_dump()
self.assertEqual(dms[0].ses_num, 0)
def test_tcp_session_close_detection_in(self):
- """ DET44 TCP session close from inside network """
- self.vapi.det44_add_del_map(is_add=1, in_addr=self.pg0.remote_ip4,
- in_plen=32,
- out_addr=socket.inet_aton(self.nat_addr),
- out_plen=32)
+ """DET44 TCP session close from inside network"""
+ self.vapi.det44_add_del_map(
+ is_add=1,
+ in_addr=self.pg0.remote_ip4,
+ in_plen=32,
+ out_addr=socket.inet_aton(self.nat_addr),
+ out_plen=32,
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1, is_inside=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1, is_inside=0)
+ sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0
+ )
self.initiate_tcp_session(self.pg0, self.pg1)
# close the session from inside
try:
# FIN packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="F"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="F")
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -478,17 +519,19 @@ class TestDET44(VppTestCase):
pkts = []
# ACK packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
- flags="A"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="A")
+ )
pkts.append(p)
# FIN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
- flags="F"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="F")
+ )
pkts.append(p)
self.pg1.add_stream(pkts)
@@ -497,10 +540,11 @@ class TestDET44(VppTestCase):
self.pg0.get_capture(2)
# ACK packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="A"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="A")
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -514,27 +558,31 @@ class TestDET44(VppTestCase):
raise
def test_tcp_session_close_detection_out(self):
- """ Deterministic NAT TCP session close from outside network """
- self.vapi.det44_add_del_map(is_add=1, in_addr=self.pg0.remote_ip4,
- in_plen=32,
- out_addr=socket.inet_aton(self.nat_addr),
- out_plen=32)
+ """Deterministic NAT TCP session close from outside network"""
+ self.vapi.det44_add_del_map(
+ is_add=1,
+ in_addr=self.pg0.remote_ip4,
+ in_plen=32,
+ out_addr=socket.inet_aton(self.nat_addr),
+ out_plen=32,
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1, is_inside=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1, is_inside=0)
+ sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0
+ )
self.initiate_tcp_session(self.pg0, self.pg1)
# close the session from outside
try:
# FIN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
- flags="F"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="F")
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -543,17 +591,19 @@ class TestDET44(VppTestCase):
pkts = []
# ACK packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="A"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="A")
+ )
pkts.append(p)
# ACK packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="F"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="F")
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
@@ -562,10 +612,11 @@ class TestDET44(VppTestCase):
self.pg1.get_capture(2)
# ACK packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
- flags="A"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="A")
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -579,21 +630,23 @@ class TestDET44(VppTestCase):
raise
def test_session_timeout(self):
- """ Deterministic NAT session timeouts """
- self.vapi.det44_add_del_map(is_add=1, in_addr=self.pg0.remote_ip4,
- in_plen=32,
- out_addr=socket.inet_aton(self.nat_addr),
- out_plen=32)
+ """Deterministic NAT session timeouts"""
+ self.vapi.det44_add_del_map(
+ is_add=1,
+ in_addr=self.pg0.remote_ip4,
+ in_plen=32,
+ out_addr=socket.inet_aton(self.nat_addr),
+ out_plen=32,
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1, is_inside=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1, is_inside=0)
+ sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0
+ )
self.initiate_tcp_session(self.pg0, self.pg1)
- self.vapi.det44_set_timeouts(udp=5, tcp_established=5,
- tcp_transitory=5, icmp=5)
+ self.vapi.det44_set_timeouts(udp=5, tcp_established=5, tcp_transitory=5, icmp=5)
pkts = self.create_stream_in(self.pg0, self.pg1)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -607,29 +660,35 @@ class TestDET44(VppTestCase):
# TODO: ipfix needs to be separated from NAT base plugin
@unittest.skipUnless(config.extended, "part of extended tests")
def test_session_limit_per_user(self):
- """ Deterministic NAT maximum sessions per user limit """
- self.vapi.det44_add_del_map(is_add=1, in_addr=self.pg0.remote_ip4,
- in_plen=32,
- out_addr=socket.inet_aton(self.nat_addr),
- out_plen=32)
+ """Deterministic NAT maximum sessions per user limit"""
+ self.vapi.det44_add_del_map(
+ is_add=1,
+ in_addr=self.pg0.remote_ip4,
+ in_plen=32,
+ out_addr=socket.inet_aton(self.nat_addr),
+ out_plen=32,
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1, is_inside=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1, is_inside=1
+ )
self.vapi.det44_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1, is_inside=0)
- self.vapi.set_ipfix_exporter(collector_address=self.pg2.remote_ip4,
- src_address=self.pg2.local_ip4,
- path_mtu=512,
- template_interval=10)
- self.vapi.nat_ipfix_enable_disable(domain_id=1, src_port=4739,
- enable=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1, is_inside=0
+ )
+ self.vapi.set_ipfix_exporter(
+ collector_address=self.pg2.remote_ip4,
+ src_address=self.pg2.local_ip4,
+ path_mtu=512,
+ template_interval=10,
+ )
+ self.vapi.nat_ipfix_enable_disable(domain_id=1, src_port=4739, enable=1)
pkts = []
for port in range(1025, 2025):
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP(sport=port, dport=port))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=port, dport=port)
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
@@ -637,9 +696,11 @@ class TestDET44(VppTestCase):
self.pg_start()
self.pg1.get_capture(len(pkts))
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP(sport=3001, dport=3002))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=3001, dport=3002)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -674,8 +735,5 @@ class TestDET44(VppTestCase):
for p in capture:
if p.haslayer(Data):
data = ipfix.decode_data_set(p.getlayer(Set))
- self.verify_ipfix_max_entries_per_user(data,
- 1000,
- self.pg0.remote_ip4)
- self.vapi.nat_ipfix_enable_disable(domain_id=1, src_port=4739,
- enable=0)
+ self.verify_ipfix_max_entries_per_user(data, 1000, self.pg0.remote_ip4)
+ self.vapi.nat_ipfix_enable_disable(domain_id=1, src_port=4739, enable=0)
diff --git a/test/test_dhcp.py b/test/test_dhcp.py
index a3b410c0595..a349356119a 100644
--- a/test/test_dhcp.py
+++ b/test/test_dhcp.py
@@ -16,9 +16,19 @@ from scapy.layers.inet import IP, UDP, ICMP
from scapy.layers.inet6 import IPv6, in6_getnsmac
from scapy.utils6 import in6_mactoifaceid
from scapy.layers.dhcp import DHCP, BOOTP, DHCPTypes
-from scapy.layers.dhcp6 import DHCP6, DHCP6_Solicit, DHCP6_RelayForward, \
- DHCP6_RelayReply, DHCP6_Advertise, DHCP6OptRelayMsg, DHCP6OptIfaceId, \
- DHCP6OptStatusCode, DHCP6OptVSS, DHCP6OptClientLinkLayerAddr, DHCP6_Request
+from scapy.layers.dhcp6 import (
+ DHCP6,
+ DHCP6_Solicit,
+ DHCP6_RelayForward,
+ DHCP6_RelayReply,
+ DHCP6_Advertise,
+ DHCP6OptRelayMsg,
+ DHCP6OptIfaceId,
+ DHCP6OptStatusCode,
+ DHCP6OptVSS,
+ DHCP6OptClientLinkLayerAddr,
+ DHCP6_Request,
+)
from socket import AF_INET, AF_INET6, inet_pton, inet_ntop
from scapy.utils6 import in6_ptop
from vpp_papi import mac_pton, VppEnum
@@ -35,7 +45,7 @@ DHCP6_SERVER_PORT = 546
@tag_run_solo
class TestDHCP(VppTestCase):
- """ DHCP Test Case """
+ """DHCP Test Case"""
@classmethod
def setUpClass(cls):
@@ -136,8 +146,7 @@ class TestDHCP(VppTestCase):
self.assertEqual(six.byte2int(data[2:3]), 0)
self.assertEqual(six.byte2int(data[3:4]), 0)
self.assertEqual(six.byte2int(data[4:5]), 0)
- self.assertEqual(six.byte2int(data[5:6]),
- intf._sw_if_index)
+ self.assertEqual(six.byte2int(data[5:6]), intf._sw_if_index)
#
# next sub-option is the IP address of the client side
@@ -179,16 +188,15 @@ class TestDHCP(VppTestCase):
self.assertEqual(six.byte2int(data[12:13]), 151)
self.assertEqual(six.byte2int(data[13:14]), id_len + 1)
self.assertEqual(six.byte2int(data[14:15]), 0)
- self.assertEqual(data[15:15 + id_len].decode('ascii'),
- vpn_id)
+ self.assertEqual(data[15 : 15 + id_len].decode("ascii"), vpn_id)
# VSS control sub-option
- self.assertEqual(six.byte2int(data[15 + len(vpn_id):
- 16 + len(vpn_id)]),
- 152)
- self.assertEqual(six.byte2int(data[16 + len(vpn_id):
- 17 + len(vpn_id)]),
- 0)
+ self.assertEqual(
+ six.byte2int(data[15 + len(vpn_id) : 16 + len(vpn_id)]), 152
+ )
+ self.assertEqual(
+ six.byte2int(data[16 + len(vpn_id) : 17 + len(vpn_id)]), 0
+ )
found = 1
self.assertTrue(found)
@@ -200,8 +208,7 @@ class TestDHCP(VppTestCase):
found = False
for o in dhcp.options:
if isinstance(o, tuple):
- if o[0] == "message-type" \
- and DHCPTypes[o[1]] == name:
+ if o[0] == "message-type" and DHCPTypes[o[1]] == name:
found = True
self.assertTrue(found)
@@ -219,8 +226,9 @@ class TestDHCP(VppTestCase):
self.assertEqual(udp.sport, DHCP4_SERVER_PORT)
self.verify_dhcp_msg_type(pkt, "offer")
- data = self.validate_relay_options(pkt, intf, intf.local_ip4,
- vpn_id, fib_id, oui)
+ data = self.validate_relay_options(
+ pkt, intf, intf.local_ip4, vpn_id, fib_id, oui
+ )
def verify_orig_dhcp_pkt(self, pkt, intf, dscp, l2_bc=True):
ether = pkt[Ether]
@@ -232,7 +240,7 @@ class TestDHCP(VppTestCase):
ip = pkt[IP]
- if (l2_bc):
+ if l2_bc:
self.assertEqual(ip.dst, "255.255.255.255")
self.assertEqual(ip.src, "0.0.0.0")
else:
@@ -244,17 +252,16 @@ class TestDHCP(VppTestCase):
self.assertEqual(udp.dport, DHCP4_SERVER_PORT)
self.assertEqual(udp.sport, DHCP4_CLIENT_PORT)
- def verify_orig_dhcp_discover(self, pkt, intf, hostname, client_id=None,
- broadcast=True, dscp=0):
+ def verify_orig_dhcp_discover(
+ self, pkt, intf, hostname, client_id=None, broadcast=True, dscp=0
+ ):
self.verify_orig_dhcp_pkt(pkt, intf, dscp)
self.verify_dhcp_msg_type(pkt, "discover")
- self.verify_dhcp_has_option(pkt, "hostname",
- hostname.encode('ascii'))
+ self.verify_dhcp_has_option(pkt, "hostname", hostname.encode("ascii"))
if client_id:
- client_id = '\x00' + client_id
- self.verify_dhcp_has_option(pkt, "client_id",
- client_id.encode('ascii'))
+ client_id = "\x00" + client_id
+ self.verify_dhcp_has_option(pkt, "client_id", client_id.encode("ascii"))
bootp = pkt[BOOTP]
self.assertEqual(bootp.ciaddr, "0.0.0.0")
self.assertEqual(bootp.giaddr, "0.0.0.0")
@@ -263,15 +270,13 @@ class TestDHCP(VppTestCase):
else:
self.assertEqual(bootp.flags, 0x0000)
- def verify_orig_dhcp_request(self, pkt, intf, hostname, ip,
- broadcast=True,
- l2_bc=True,
- dscp=0):
+ def verify_orig_dhcp_request(
+ self, pkt, intf, hostname, ip, broadcast=True, l2_bc=True, dscp=0
+ ):
self.verify_orig_dhcp_pkt(pkt, intf, dscp, l2_bc=l2_bc)
self.verify_dhcp_msg_type(pkt, "request")
- self.verify_dhcp_has_option(pkt, "hostname",
- hostname.encode('ascii'))
+ self.verify_dhcp_has_option(pkt, "hostname", hostname.encode("ascii"))
self.verify_dhcp_has_option(pkt, "requested_addr", ip)
bootp = pkt[BOOTP]
@@ -286,10 +291,17 @@ class TestDHCP(VppTestCase):
else:
self.assertEqual(bootp.flags, 0x0000)
- def verify_relayed_dhcp_discover(self, pkt, intf, src_intf=None,
- fib_id=0, oui=0,
- vpn_id="",
- dst_mac=None, dst_ip=None):
+ def verify_relayed_dhcp_discover(
+ self,
+ pkt,
+ intf,
+ src_intf=None,
+ fib_id=0,
+ oui=0,
+ vpn_id="",
+ dst_mac=None,
+ dst_ip=None,
+ ):
if not dst_mac:
dst_mac = intf.remote_mac
if not dst_ip:
@@ -312,24 +324,27 @@ class TestDHCP(VppTestCase):
is_discover = False
for o in dhcp.options:
if isinstance(o, tuple):
- if o[0] == "message-type" \
- and DHCPTypes[o[1]] == "discover":
+ if o[0] == "message-type" and DHCPTypes[o[1]] == "discover":
is_discover = True
self.assertTrue(is_discover)
- data = self.validate_relay_options(pkt, src_intf,
- src_intf.local_ip4,
- vpn_id,
- fib_id, oui)
+ data = self.validate_relay_options(
+ pkt, src_intf, src_intf.local_ip4, vpn_id, fib_id, oui
+ )
return data
- def verify_dhcp6_solicit(self, pkt, intf,
- peer_ip, peer_mac,
- vpn_id="",
- fib_id=0,
- oui=0,
- dst_mac=None,
- dst_ip=None):
+ def verify_dhcp6_solicit(
+ self,
+ pkt,
+ intf,
+ peer_ip,
+ peer_mac,
+ vpn_id="",
+ fib_id=0,
+ oui=0,
+ dst_mac=None,
+ dst_ip=None,
+ ):
if not dst_mac:
dst_mac = intf.remote_mac
if not dst_ip:
@@ -377,8 +392,7 @@ class TestDHCP(VppTestCase):
vss = pkt[DHCP6OptVSS]
self.assertEqual(vss.optlen, id_len + 1)
self.assertEqual(vss.type, 0)
- self.assertEqual(vss.data[0:id_len].decode('ascii'),
- vpn_id)
+ self.assertEqual(vss.data[0:id_len].decode("ascii"), vpn_id)
# the relay message should be an encoded Solicit
msg = pkt[DHCP6OptRelayMsg]
@@ -402,9 +416,8 @@ class TestDHCP(VppTestCase):
# not sure why this is not decoding
# adv = pkt[DHCP6_Advertise]
- def wait_for_no_route(self, address, length,
- n_tries=50, s_time=1):
- while (n_tries):
+ def wait_for_no_route(self, address, length, n_tries=50, s_time=1):
+ while n_tries:
if not find_route(self, address, length):
return True
n_tries = n_tries - 1
@@ -413,42 +426,45 @@ class TestDHCP(VppTestCase):
return False
def test_dhcp_proxy(self):
- """ DHCPv4 Proxy """
+ """DHCPv4 Proxy"""
#
# Verify no response to DHCP request without DHCP config
#
- p_disc_vrf0 = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg3.remote_mac) /
- IP(src="0.0.0.0", dst="255.255.255.255") /
- UDP(sport=DHCP4_CLIENT_PORT,
- dport=DHCP4_SERVER_PORT) /
- BOOTP(op=1) /
- DHCP(options=[('message-type', 'discover'), ('end')]))
+ p_disc_vrf0 = (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg3.remote_mac)
+ / IP(src="0.0.0.0", dst="255.255.255.255")
+ / UDP(sport=DHCP4_CLIENT_PORT, dport=DHCP4_SERVER_PORT)
+ / BOOTP(op=1)
+ / DHCP(options=[("message-type", "discover"), ("end")])
+ )
pkts_disc_vrf0 = [p_disc_vrf0]
- p_disc_vrf1 = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg4.remote_mac) /
- IP(src="0.0.0.0", dst="255.255.255.255") /
- UDP(sport=DHCP4_CLIENT_PORT,
- dport=DHCP4_SERVER_PORT) /
- BOOTP(op=1) /
- DHCP(options=[('message-type', 'discover'), ('end')]))
+ p_disc_vrf1 = (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg4.remote_mac)
+ / IP(src="0.0.0.0", dst="255.255.255.255")
+ / UDP(sport=DHCP4_CLIENT_PORT, dport=DHCP4_SERVER_PORT)
+ / BOOTP(op=1)
+ / DHCP(options=[("message-type", "discover"), ("end")])
+ )
pkts_disc_vrf1 = [p_disc_vrf1]
- p_disc_vrf2 = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg5.remote_mac) /
- IP(src="0.0.0.0", dst="255.255.255.255") /
- UDP(sport=DHCP4_CLIENT_PORT,
- dport=DHCP4_SERVER_PORT) /
- BOOTP(op=1) /
- DHCP(options=[('message-type', 'discover'), ('end')]))
+ p_disc_vrf2 = (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg5.remote_mac)
+ / IP(src="0.0.0.0", dst="255.255.255.255")
+ / UDP(sport=DHCP4_CLIENT_PORT, dport=DHCP4_SERVER_PORT)
+ / BOOTP(op=1)
+ / DHCP(options=[("message-type", "discover"), ("end")])
+ )
pkts_disc_vrf2 = [p_disc_vrf2]
- self.send_and_assert_no_replies(self.pg3, pkts_disc_vrf0,
- "DHCP with no configuration")
- self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1,
- "DHCP with no configuration")
- self.send_and_assert_no_replies(self.pg5, pkts_disc_vrf2,
- "DHCP with no configuration")
+ self.send_and_assert_no_replies(
+ self.pg3, pkts_disc_vrf0, "DHCP with no configuration"
+ )
+ self.send_and_assert_no_replies(
+ self.pg4, pkts_disc_vrf1, "DHCP with no configuration"
+ )
+ self.send_and_assert_no_replies(
+ self.pg5, pkts_disc_vrf2, "DHCP with no configuration"
+ )
#
# Enable DHCP proxy in VRF 0
@@ -463,23 +479,25 @@ class TestDHCP(VppTestCase):
# Discover packets from the client are dropped because there is no
# IP address configured on the client facing interface
#
- self.send_and_assert_no_replies(self.pg3, pkts_disc_vrf0,
- "Discover DHCP no relay address")
+ self.send_and_assert_no_replies(
+ self.pg3, pkts_disc_vrf0, "Discover DHCP no relay address"
+ )
#
# Inject a response from the server
# dropped, because there is no IP addrees on the
# client interfce to fill in the option.
#
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) /
- BOOTP(op=1) /
- DHCP(options=[('message-type', 'offer'), ('end')]))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT)
+ / BOOTP(op=1)
+ / DHCP(options=[("message-type", "offer"), ("end")])
+ )
pkts = [p]
- self.send_and_assert_no_replies(self.pg3, pkts,
- "Offer DHCP no relay address")
+ self.send_and_assert_no_replies(self.pg3, pkts, "Offer DHCP no relay address")
#
# configure an IP address on the client facing interface
@@ -500,21 +518,26 @@ class TestDHCP(VppTestCase):
rx = self.pg0.get_capture(1)
rx = rx[0]
- option_82 = self.verify_relayed_dhcp_discover(rx, self.pg0,
- src_intf=self.pg3)
+ option_82 = self.verify_relayed_dhcp_discover(rx, self.pg0, src_intf=self.pg3)
#
# Create an DHCP offer reply from the server with a correctly formatted
# option 82. i.e. send back what we just captured
# The offer, sent mcast to the client, still has option 82.
#
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) /
- BOOTP(op=1) /
- DHCP(options=[('message-type', 'offer'),
- ('relay_agent_Information', option_82),
- ('end')]))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT)
+ / BOOTP(op=1)
+ / DHCP(
+ options=[
+ ("message-type", "offer"),
+ ("relay_agent_Information", option_82),
+ ("end"),
+ ]
+ )
+ )
pkts = [p]
self.pg0.add_stream(pkts)
@@ -533,36 +556,51 @@ class TestDHCP(VppTestCase):
# to client
bad_ip = option_82[0:8] + scapy.compat.chb(33) + option_82[9:]
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) /
- BOOTP(op=1) /
- DHCP(options=[('message-type', 'offer'),
- ('relay_agent_Information', bad_ip),
- ('end')]))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT)
+ / BOOTP(op=1)
+ / DHCP(
+ options=[
+ ("message-type", "offer"),
+ ("relay_agent_Information", bad_ip),
+ ("end"),
+ ]
+ )
+ )
pkts = [p]
- self.send_and_assert_no_replies(self.pg0, pkts,
- "DHCP offer option 82 bad address")
+ self.send_and_assert_no_replies(
+ self.pg0, pkts, "DHCP offer option 82 bad address"
+ )
# 2. Not a sw_if_index VPP knows
bad_if_index = option_82[0:2] + scapy.compat.chb(33) + option_82[3:]
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) /
- BOOTP(op=1) /
- DHCP(options=[('message-type', 'offer'),
- ('relay_agent_Information', bad_if_index),
- ('end')]))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT)
+ / BOOTP(op=1)
+ / DHCP(
+ options=[
+ ("message-type", "offer"),
+ ("relay_agent_Information", bad_if_index),
+ ("end"),
+ ]
+ )
+ )
pkts = [p]
- self.send_and_assert_no_replies(self.pg0, pkts,
- "DHCP offer option 82 bad if index")
+ self.send_and_assert_no_replies(
+ self.pg0, pkts, "DHCP offer option 82 bad if index"
+ )
#
# Send a DHCP request in VRF 1. should be dropped.
#
- self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1,
- "DHCP with no configuration VRF 1")
+ self.send_and_assert_no_replies(
+ self.pg4, pkts_disc_vrf1, "DHCP with no configuration VRF 1"
+ )
#
# Delete the DHCP config in VRF 0
@@ -570,10 +608,12 @@ class TestDHCP(VppTestCase):
#
Proxy.remove_vpp_config()
- self.send_and_assert_no_replies(self.pg3, pkts_disc_vrf0,
- "DHCP config removed VRF 0")
- self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1,
- "DHCP config removed VRF 1")
+ self.send_and_assert_no_replies(
+ self.pg3, pkts_disc_vrf0, "DHCP config removed VRF 0"
+ )
+ self.send_and_assert_no_replies(
+ self.pg4, pkts_disc_vrf1, "DHCP config removed VRF 1"
+ )
#
# Add DHCP config for VRF 1 & 2
@@ -581,31 +621,27 @@ class TestDHCP(VppTestCase):
server_addr1 = self.pg1.remote_ip4
src_addr1 = self.pg1.local_ip4
Proxy1 = VppDHCPProxy(
- self,
- server_addr1,
- src_addr1,
- rx_vrf_id=1,
- server_vrf_id=1)
+ self, server_addr1, src_addr1, rx_vrf_id=1, server_vrf_id=1
+ )
Proxy1.add_vpp_config()
server_addr2 = self.pg2.remote_ip4
src_addr2 = self.pg2.local_ip4
Proxy2 = VppDHCPProxy(
- self,
- server_addr2,
- src_addr2,
- rx_vrf_id=2,
- server_vrf_id=2)
+ self, server_addr2, src_addr2, rx_vrf_id=2, server_vrf_id=2
+ )
Proxy2.add_vpp_config()
#
# Confim DHCP requests ok in VRF 1 & 2.
# - dropped on IP config on client interface
#
- self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1,
- "DHCP config removed VRF 1")
- self.send_and_assert_no_replies(self.pg5, pkts_disc_vrf2,
- "DHCP config removed VRF 2")
+ self.send_and_assert_no_replies(
+ self.pg4, pkts_disc_vrf1, "DHCP config removed VRF 1"
+ )
+ self.send_and_assert_no_replies(
+ self.pg5, pkts_disc_vrf2, "DHCP config removed VRF 2"
+ )
#
# configure an IP address on the client facing interface
@@ -630,10 +666,10 @@ class TestDHCP(VppTestCase):
# Add VSS config
# table=1, vss_type=1, vpn_index=1, oui=4
# table=2, vss_type=0, vpn_id = "ip4-table-2"
- self.vapi.dhcp_proxy_set_vss(tbl_id=1, vss_type=1,
- vpn_index=1, oui=4, is_add=1)
- self.vapi.dhcp_proxy_set_vss(tbl_id=2, vss_type=0,
- vpn_ascii_id="ip4-table-2", is_add=1)
+ self.vapi.dhcp_proxy_set_vss(tbl_id=1, vss_type=1, vpn_index=1, oui=4, is_add=1)
+ self.vapi.dhcp_proxy_set_vss(
+ tbl_id=2, vss_type=0, vpn_ascii_id="ip4-table-2", is_add=1
+ )
self.pg4.add_stream(pkts_disc_vrf1)
self.pg_enable_capture(self.pg_interfaces)
@@ -641,9 +677,9 @@ class TestDHCP(VppTestCase):
rx = self.pg1.get_capture(1)
rx = rx[0]
- self.verify_relayed_dhcp_discover(rx, self.pg1,
- src_intf=self.pg4,
- fib_id=1, oui=4)
+ self.verify_relayed_dhcp_discover(
+ rx, self.pg1, src_intf=self.pg4, fib_id=1, oui=4
+ )
self.pg5.add_stream(pkts_disc_vrf2)
self.pg_enable_capture(self.pg_interfaces)
@@ -651,9 +687,9 @@ class TestDHCP(VppTestCase):
rx = self.pg2.get_capture(1)
rx = rx[0]
- self.verify_relayed_dhcp_discover(rx, self.pg2,
- src_intf=self.pg5,
- vpn_id="ip4-table-2")
+ self.verify_relayed_dhcp_discover(
+ rx, self.pg2, src_intf=self.pg5, vpn_id="ip4-table-2"
+ )
#
# Add a second DHCP server in VRF 1
@@ -663,20 +699,19 @@ class TestDHCP(VppTestCase):
server_addr12 = self.pg1.remote_hosts[1].ip4
Proxy12 = VppDHCPProxy(
- self,
- server_addr12,
- src_addr,
- rx_vrf_id=1,
- server_vrf_id=1)
+ self, server_addr12, src_addr, rx_vrf_id=1, server_vrf_id=1
+ )
Proxy12.add_vpp_config()
#
# We'll need an ARP entry for the server to send it packets
#
- arp_entry = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[1].mac,
- self.pg1.remote_hosts[1].ip4)
+ arp_entry = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[1].mac,
+ self.pg1.remote_hosts[1].ip4,
+ )
arp_entry.add_vpp_config()
#
@@ -691,32 +726,47 @@ class TestDHCP(VppTestCase):
rx = self.pg1.get_capture(2)
option_82 = self.verify_relayed_dhcp_discover(
- rx[0], self.pg1,
+ rx[0],
+ self.pg1,
src_intf=self.pg4,
dst_mac=self.pg1.remote_hosts[1].mac,
dst_ip=self.pg1.remote_hosts[1].ip4,
- fib_id=1, oui=4)
- self.verify_relayed_dhcp_discover(rx[1], self.pg1,
- src_intf=self.pg4,
- fib_id=1, oui=4)
+ fib_id=1,
+ oui=4,
+ )
+ self.verify_relayed_dhcp_discover(
+ rx[1], self.pg1, src_intf=self.pg4, fib_id=1, oui=4
+ )
#
# Send both packets back. Client gets both.
#
- p1 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4) /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) /
- BOOTP(op=1) /
- DHCP(options=[('message-type', 'offer'),
- ('relay_agent_Information', option_82),
- ('end')]))
- p2 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_hosts[1].ip4, dst=self.pg1.local_ip4) /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) /
- BOOTP(op=1) /
- DHCP(options=[('message-type', 'offer'),
- ('relay_agent_Information', option_82),
- ('end')]))
+ p1 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4)
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT)
+ / BOOTP(op=1)
+ / DHCP(
+ options=[
+ ("message-type", "offer"),
+ ("relay_agent_Information", option_82),
+ ("end"),
+ ]
+ )
+ )
+ p2 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_hosts[1].ip4, dst=self.pg1.local_ip4)
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT)
+ / BOOTP(op=1)
+ / DHCP(
+ options=[
+ ("message-type", "offer"),
+ ("relay_agent_Information", option_82),
+ ("end"),
+ ]
+ )
+ )
pkts = [p1, p2]
self.pg1.add_stream(pkts)
@@ -731,27 +781,31 @@ class TestDHCP(VppTestCase):
#
# Ensure offers from non-servers are dropeed
#
- p2 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src="8.8.8.8", dst=self.pg1.local_ip4) /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT) /
- BOOTP(op=1) /
- DHCP(options=[('message-type', 'offer'),
- ('relay_agent_Information', option_82),
- ('end')]))
- self.send_and_assert_no_replies(self.pg1, p2,
- "DHCP offer from non-server")
+ p2 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src="8.8.8.8", dst=self.pg1.local_ip4)
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_SERVER_PORT)
+ / BOOTP(op=1)
+ / DHCP(
+ options=[
+ ("message-type", "offer"),
+ ("relay_agent_Information", option_82),
+ ("end"),
+ ]
+ )
+ )
+ self.send_and_assert_no_replies(self.pg1, p2, "DHCP offer from non-server")
#
# Ensure only the discover is sent to multiple servers
#
- p_req_vrf1 = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg4.remote_mac) /
- IP(src="0.0.0.0", dst="255.255.255.255") /
- UDP(sport=DHCP4_CLIENT_PORT,
- dport=DHCP4_SERVER_PORT) /
- BOOTP(op=1) /
- DHCP(options=[('message-type', 'request'),
- ('end')]))
+ p_req_vrf1 = (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg4.remote_mac)
+ / IP(src="0.0.0.0", dst="255.255.255.255")
+ / UDP(sport=DHCP4_CLIENT_PORT, dport=DHCP4_SERVER_PORT)
+ / BOOTP(op=1)
+ / DHCP(options=[("message-type", "request"), ("end")])
+ )
self.pg4.add_stream(p_req_vrf1)
self.pg_enable_capture(self.pg_interfaces)
@@ -773,9 +827,9 @@ class TestDHCP(VppTestCase):
rx = self.pg1.get_capture(1)
rx = rx[0]
- self.verify_relayed_dhcp_discover(rx, self.pg1,
- src_intf=self.pg4,
- fib_id=1, oui=4)
+ self.verify_relayed_dhcp_discover(
+ rx, self.pg1, src_intf=self.pg4, fib_id=1, oui=4
+ )
#
# Remove the VSS config
@@ -798,19 +852,16 @@ class TestDHCP(VppTestCase):
Proxy1.remove_vpp_config()
Proxy2.remove_vpp_config()
- self.send_and_assert_no_replies(self.pg3, pkts_disc_vrf0,
- "DHCP cleanup VRF 0")
- self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1,
- "DHCP cleanup VRF 1")
- self.send_and_assert_no_replies(self.pg5, pkts_disc_vrf2,
- "DHCP cleanup VRF 2")
+ self.send_and_assert_no_replies(self.pg3, pkts_disc_vrf0, "DHCP cleanup VRF 0")
+ self.send_and_assert_no_replies(self.pg4, pkts_disc_vrf1, "DHCP cleanup VRF 1")
+ self.send_and_assert_no_replies(self.pg5, pkts_disc_vrf2, "DHCP cleanup VRF 2")
self.pg3.unconfig_ip4()
self.pg4.unconfig_ip4()
self.pg5.unconfig_ip4()
def test_dhcp6_proxy(self):
- """ DHCPv6 Proxy"""
+ """DHCPv6 Proxy"""
#
# Verify no response to DHCP request without DHCP config
#
@@ -826,31 +877,34 @@ class TestDHCP(VppTestCase):
src_addr_vrf2 = self.pg2.local_ip6
dmac = in6_getnsmac(inet_pton(socket.AF_INET6, dhcp_solicit_dst))
- p_solicit_vrf0 = (Ether(dst=dmac, src=self.pg3.remote_mac) /
- IPv6(src=dhcp_solicit_src_vrf0,
- dst=dhcp_solicit_dst) /
- UDP(sport=DHCP6_SERVER_PORT,
- dport=DHCP6_CLIENT_PORT) /
- DHCP6_Solicit())
- p_solicit_vrf1 = (Ether(dst=dmac, src=self.pg4.remote_mac) /
- IPv6(src=dhcp_solicit_src_vrf1,
- dst=dhcp_solicit_dst) /
- UDP(sport=DHCP6_SERVER_PORT,
- dport=DHCP6_CLIENT_PORT) /
- DHCP6_Solicit())
- p_solicit_vrf2 = (Ether(dst=dmac, src=self.pg5.remote_mac) /
- IPv6(src=dhcp_solicit_src_vrf2,
- dst=dhcp_solicit_dst) /
- UDP(sport=DHCP6_SERVER_PORT,
- dport=DHCP6_CLIENT_PORT) /
- DHCP6_Solicit())
-
- self.send_and_assert_no_replies(self.pg3, p_solicit_vrf0,
- "DHCP with no configuration")
- self.send_and_assert_no_replies(self.pg4, p_solicit_vrf1,
- "DHCP with no configuration")
- self.send_and_assert_no_replies(self.pg5, p_solicit_vrf2,
- "DHCP with no configuration")
+ p_solicit_vrf0 = (
+ Ether(dst=dmac, src=self.pg3.remote_mac)
+ / IPv6(src=dhcp_solicit_src_vrf0, dst=dhcp_solicit_dst)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_CLIENT_PORT)
+ / DHCP6_Solicit()
+ )
+ p_solicit_vrf1 = (
+ Ether(dst=dmac, src=self.pg4.remote_mac)
+ / IPv6(src=dhcp_solicit_src_vrf1, dst=dhcp_solicit_dst)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_CLIENT_PORT)
+ / DHCP6_Solicit()
+ )
+ p_solicit_vrf2 = (
+ Ether(dst=dmac, src=self.pg5.remote_mac)
+ / IPv6(src=dhcp_solicit_src_vrf2, dst=dhcp_solicit_dst)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_CLIENT_PORT)
+ / DHCP6_Solicit()
+ )
+
+ self.send_and_assert_no_replies(
+ self.pg3, p_solicit_vrf0, "DHCP with no configuration"
+ )
+ self.send_and_assert_no_replies(
+ self.pg4, p_solicit_vrf1, "DHCP with no configuration"
+ )
+ self.send_and_assert_no_replies(
+ self.pg5, p_solicit_vrf2, "DHCP with no configuration"
+ )
#
# DHCPv6 config in VRF 0.
@@ -858,17 +912,16 @@ class TestDHCP(VppTestCase):
# IPv6 config
#
Proxy = VppDHCPProxy(
- self,
- server_addr_vrf0,
- src_addr_vrf0,
- rx_vrf_id=0,
- server_vrf_id=0)
+ self, server_addr_vrf0, src_addr_vrf0, rx_vrf_id=0, server_vrf_id=0
+ )
Proxy.add_vpp_config()
- self.send_and_assert_no_replies(self.pg3, p_solicit_vrf0,
- "DHCP with no configuration")
- self.send_and_assert_no_replies(self.pg4, p_solicit_vrf1,
- "DHCP with no configuration")
+ self.send_and_assert_no_replies(
+ self.pg3, p_solicit_vrf0, "DHCP with no configuration"
+ )
+ self.send_and_assert_no_replies(
+ self.pg4, p_solicit_vrf1, "DHCP with no configuration"
+ )
#
# configure an IP address on the client facing interface
@@ -884,62 +937,70 @@ class TestDHCP(VppTestCase):
rx = self.pg0.get_capture(1)
- self.verify_dhcp6_solicit(rx[0], self.pg0,
- dhcp_solicit_src_vrf0,
- self.pg3.remote_mac)
+ self.verify_dhcp6_solicit(
+ rx[0], self.pg0, dhcp_solicit_src_vrf0, self.pg3.remote_mac
+ )
#
# Exception cases for rejected relay responses
#
# 1 - not a relay reply
- p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) /
- UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) /
- DHCP6_Advertise())
- self.send_and_assert_no_replies(self.pg3, p_adv_vrf0,
- "DHCP6 not a relay reply")
+ p_adv_vrf0 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT)
+ / DHCP6_Advertise()
+ )
+ self.send_and_assert_no_replies(self.pg3, p_adv_vrf0, "DHCP6 not a relay reply")
# 2 - no relay message option
- p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) /
- UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) /
- DHCP6_RelayReply() /
- DHCP6_Advertise())
- self.send_and_assert_no_replies(self.pg3, p_adv_vrf0,
- "DHCP not a relay message")
+ p_adv_vrf0 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT)
+ / DHCP6_RelayReply()
+ / DHCP6_Advertise()
+ )
+ self.send_and_assert_no_replies(
+ self.pg3, p_adv_vrf0, "DHCP not a relay message"
+ )
# 3 - no circuit ID
- p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) /
- UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) /
- DHCP6_RelayReply() /
- DHCP6OptRelayMsg(optlen=0) /
- DHCP6_Advertise())
- self.send_and_assert_no_replies(self.pg3, p_adv_vrf0,
- "DHCP6 no circuit ID")
+ p_adv_vrf0 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT)
+ / DHCP6_RelayReply()
+ / DHCP6OptRelayMsg(optlen=0)
+ / DHCP6_Advertise()
+ )
+ self.send_and_assert_no_replies(self.pg3, p_adv_vrf0, "DHCP6 no circuit ID")
# 4 - wrong circuit ID
- p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) /
- UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) /
- DHCP6_RelayReply() /
- DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x05') /
- DHCP6OptRelayMsg(optlen=0) /
- DHCP6_Advertise())
- self.send_and_assert_no_replies(self.pg3, p_adv_vrf0,
- "DHCP6 wrong circuit ID")
+ p_adv_vrf0 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT)
+ / DHCP6_RelayReply()
+ / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x05")
+ / DHCP6OptRelayMsg(optlen=0)
+ / DHCP6_Advertise()
+ )
+ self.send_and_assert_no_replies(self.pg3, p_adv_vrf0, "DHCP6 wrong circuit ID")
#
# Send the relay response (the advertisement)
# - no peer address
- p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) /
- UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) /
- DHCP6_RelayReply() /
- DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x04') /
- DHCP6OptRelayMsg(optlen=0) /
- DHCP6_Advertise(trid=1) /
- DHCP6OptStatusCode(statuscode=0))
+ p_adv_vrf0 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT)
+ / DHCP6_RelayReply()
+ / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x04")
+ / DHCP6OptRelayMsg(optlen=0)
+ / DHCP6_Advertise(trid=1)
+ / DHCP6OptStatusCode(statuscode=0)
+ )
pkts_adv_vrf0 = [p_adv_vrf0]
self.pg0.add_stream(pkts_adv_vrf0)
@@ -953,14 +1014,16 @@ class TestDHCP(VppTestCase):
#
# Send the relay response (the advertisement)
# - with peer address
- p_adv_vrf0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) /
- UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) /
- DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf0) /
- DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x04') /
- DHCP6OptRelayMsg(optlen=0) /
- DHCP6_Advertise(trid=1) /
- DHCP6OptStatusCode(statuscode=0))
+ p_adv_vrf0 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT)
+ / DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf0)
+ / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x04")
+ / DHCP6OptRelayMsg(optlen=0)
+ / DHCP6_Advertise(trid=1)
+ / DHCP6OptStatusCode(statuscode=0)
+ )
pkts_adv_vrf0 = [p_adv_vrf0]
self.pg0.add_stream(pkts_adv_vrf0)
@@ -975,20 +1038,14 @@ class TestDHCP(VppTestCase):
# Add all the config for VRF 1 & 2
#
Proxy1 = VppDHCPProxy(
- self,
- server_addr_vrf1,
- src_addr_vrf1,
- rx_vrf_id=1,
- server_vrf_id=1)
+ self, server_addr_vrf1, src_addr_vrf1, rx_vrf_id=1, server_vrf_id=1
+ )
Proxy1.add_vpp_config()
self.pg4.config_ip6()
Proxy2 = VppDHCPProxy(
- self,
- server_addr_vrf2,
- src_addr_vrf2,
- rx_vrf_id=2,
- server_vrf_id=2)
+ self, server_addr_vrf2, src_addr_vrf2, rx_vrf_id=2, server_vrf_id=2
+ )
Proxy2.add_vpp_config()
self.pg5.config_ip6()
@@ -1001,9 +1058,9 @@ class TestDHCP(VppTestCase):
rx = self.pg1.get_capture(1)
- self.verify_dhcp6_solicit(rx[0], self.pg1,
- dhcp_solicit_src_vrf1,
- self.pg4.remote_mac)
+ self.verify_dhcp6_solicit(
+ rx[0], self.pg1, dhcp_solicit_src_vrf1, self.pg4.remote_mac
+ )
#
# VRF 2 solicit
@@ -1014,21 +1071,23 @@ class TestDHCP(VppTestCase):
rx = self.pg2.get_capture(1)
- self.verify_dhcp6_solicit(rx[0], self.pg2,
- dhcp_solicit_src_vrf2,
- self.pg5.remote_mac)
+ self.verify_dhcp6_solicit(
+ rx[0], self.pg2, dhcp_solicit_src_vrf2, self.pg5.remote_mac
+ )
#
# VRF 1 Advert
#
- p_adv_vrf1 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(dst=self.pg1.local_ip6, src=self.pg1.remote_ip6) /
- UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) /
- DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) /
- DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x05') /
- DHCP6OptRelayMsg(optlen=0) /
- DHCP6_Advertise(trid=1) /
- DHCP6OptStatusCode(statuscode=0))
+ p_adv_vrf1 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(dst=self.pg1.local_ip6, src=self.pg1.remote_ip6)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT)
+ / DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1)
+ / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x05")
+ / DHCP6OptRelayMsg(optlen=0)
+ / DHCP6_Advertise(trid=1)
+ / DHCP6OptStatusCode(statuscode=0)
+ )
pkts_adv_vrf1 = [p_adv_vrf1]
self.pg1.add_stream(pkts_adv_vrf1)
@@ -1043,13 +1102,11 @@ class TestDHCP(VppTestCase):
# Add VSS config
#
self.vapi.dhcp_proxy_set_vss(
- tbl_id=1, vss_type=1, oui=4, vpn_index=1, is_ipv6=1, is_add=1)
+ tbl_id=1, vss_type=1, oui=4, vpn_index=1, is_ipv6=1, is_add=1
+ )
self.vapi.dhcp_proxy_set_vss(
- tbl_id=2,
- vss_type=0,
- vpn_ascii_id="IPv6-table-2",
- is_ipv6=1,
- is_add=1)
+ tbl_id=2, vss_type=0, vpn_ascii_id="IPv6-table-2", is_ipv6=1, is_add=1
+ )
self.pg4.add_stream(p_solicit_vrf1)
self.pg_enable_capture(self.pg_interfaces)
@@ -1057,11 +1114,9 @@ class TestDHCP(VppTestCase):
rx = self.pg1.get_capture(1)
- self.verify_dhcp6_solicit(rx[0], self.pg1,
- dhcp_solicit_src_vrf1,
- self.pg4.remote_mac,
- fib_id=1,
- oui=4)
+ self.verify_dhcp6_solicit(
+ rx[0], self.pg1, dhcp_solicit_src_vrf1, self.pg4.remote_mac, fib_id=1, oui=4
+ )
self.pg5.add_stream(p_solicit_vrf2)
self.pg_enable_capture(self.pg_interfaces)
@@ -1069,10 +1124,13 @@ class TestDHCP(VppTestCase):
rx = self.pg2.get_capture(1)
- self.verify_dhcp6_solicit(rx[0], self.pg2,
- dhcp_solicit_src_vrf2,
- self.pg5.remote_mac,
- vpn_id="IPv6-table-2")
+ self.verify_dhcp6_solicit(
+ rx[0],
+ self.pg2,
+ dhcp_solicit_src_vrf2,
+ self.pg5.remote_mac,
+ vpn_id="IPv6-table-2",
+ )
#
# Remove the VSS config
@@ -1086,9 +1144,9 @@ class TestDHCP(VppTestCase):
rx = self.pg1.get_capture(1)
- self.verify_dhcp6_solicit(rx[0], self.pg1,
- dhcp_solicit_src_vrf1,
- self.pg4.remote_mac)
+ self.verify_dhcp6_solicit(
+ rx[0], self.pg1, dhcp_solicit_src_vrf1, self.pg4.remote_mac
+ )
#
# Add a second DHCP server in VRF 1
@@ -1098,20 +1156,19 @@ class TestDHCP(VppTestCase):
server_addr12 = self.pg1.remote_hosts[1].ip6
Proxy12 = VppDHCPProxy(
- self,
- server_addr12,
- src_addr_vrf1,
- rx_vrf_id=1,
- server_vrf_id=1)
+ self, server_addr12, src_addr_vrf1, rx_vrf_id=1, server_vrf_id=1
+ )
Proxy12.add_vpp_config()
#
# We'll need an ND entry for the server to send it packets
#
- nd_entry = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[1].mac,
- self.pg1.remote_hosts[1].ip6)
+ nd_entry = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[1].mac,
+ self.pg1.remote_hosts[1].ip6,
+ )
nd_entry.add_vpp_config()
#
@@ -1125,34 +1182,41 @@ class TestDHCP(VppTestCase):
rx = self.pg1.get_capture(2)
- self.verify_dhcp6_solicit(rx[0], self.pg1,
- dhcp_solicit_src_vrf1,
- self.pg4.remote_mac)
- self.verify_dhcp6_solicit(rx[1], self.pg1,
- dhcp_solicit_src_vrf1,
- self.pg4.remote_mac,
- dst_mac=self.pg1.remote_hosts[1].mac,
- dst_ip=self.pg1.remote_hosts[1].ip6)
+ self.verify_dhcp6_solicit(
+ rx[0], self.pg1, dhcp_solicit_src_vrf1, self.pg4.remote_mac
+ )
+ self.verify_dhcp6_solicit(
+ rx[1],
+ self.pg1,
+ dhcp_solicit_src_vrf1,
+ self.pg4.remote_mac,
+ dst_mac=self.pg1.remote_hosts[1].mac,
+ dst_ip=self.pg1.remote_hosts[1].ip6,
+ )
#
# Send both packets back. Client gets both.
#
- p1 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(dst=self.pg1.local_ip6, src=self.pg1.remote_ip6) /
- UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) /
- DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) /
- DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x05') /
- DHCP6OptRelayMsg(optlen=0) /
- DHCP6_Advertise(trid=1) /
- DHCP6OptStatusCode(statuscode=0))
- p2 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_hosts[1].mac) /
- IPv6(dst=self.pg1.local_ip6, src=self.pg1._remote_hosts[1].ip6) /
- UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) /
- DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) /
- DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x05') /
- DHCP6OptRelayMsg(optlen=0) /
- DHCP6_Advertise(trid=1) /
- DHCP6OptStatusCode(statuscode=0))
+ p1 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(dst=self.pg1.local_ip6, src=self.pg1.remote_ip6)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT)
+ / DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1)
+ / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x05")
+ / DHCP6OptRelayMsg(optlen=0)
+ / DHCP6_Advertise(trid=1)
+ / DHCP6OptStatusCode(statuscode=0)
+ )
+ p2 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_hosts[1].mac)
+ / IPv6(dst=self.pg1.local_ip6, src=self.pg1._remote_hosts[1].ip6)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT)
+ / DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1)
+ / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x05")
+ / DHCP6OptRelayMsg(optlen=0)
+ / DHCP6_Advertise(trid=1)
+ / DHCP6OptStatusCode(statuscode=0)
+ )
pkts = [p1, p2]
@@ -1168,12 +1232,12 @@ class TestDHCP(VppTestCase):
#
# Ensure only solicit messages are duplicated
#
- p_request_vrf1 = (Ether(dst=dmac, src=self.pg4.remote_mac) /
- IPv6(src=dhcp_solicit_src_vrf1,
- dst=dhcp_solicit_dst) /
- UDP(sport=DHCP6_SERVER_PORT,
- dport=DHCP6_CLIENT_PORT) /
- DHCP6_Request())
+ p_request_vrf1 = (
+ Ether(dst=dmac, src=self.pg4.remote_mac)
+ / IPv6(src=dhcp_solicit_src_vrf1, dst=dhcp_solicit_dst)
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_CLIENT_PORT)
+ / DHCP6_Request()
+ )
self.pg4.add_stream(p_request_vrf1)
self.pg_enable_capture(self.pg_interfaces)
@@ -1185,16 +1249,17 @@ class TestDHCP(VppTestCase):
# Test we drop DHCP packets from addresses that are not configured as
# DHCP servers
#
- p2 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_hosts[1].mac) /
- IPv6(dst=self.pg1.local_ip6, src="3001::1") /
- UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT) /
- DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1) /
- DHCP6OptIfaceId(optlen=4, ifaceid='\x00\x00\x00\x05') /
- DHCP6OptRelayMsg(optlen=0) /
- DHCP6_Advertise(trid=1) /
- DHCP6OptStatusCode(statuscode=0))
- self.send_and_assert_no_replies(self.pg1, p2,
- "DHCP6 not from server")
+ p2 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_hosts[1].mac)
+ / IPv6(dst=self.pg1.local_ip6, src="3001::1")
+ / UDP(sport=DHCP6_SERVER_PORT, dport=DHCP6_SERVER_PORT)
+ / DHCP6_RelayReply(peeraddr=dhcp_solicit_src_vrf1)
+ / DHCP6OptIfaceId(optlen=4, ifaceid="\x00\x00\x00\x05")
+ / DHCP6OptRelayMsg(optlen=0)
+ / DHCP6_Advertise(trid=1)
+ / DHCP6OptStatusCode(statuscode=0)
+ )
+ self.send_and_assert_no_replies(self.pg1, p2, "DHCP6 not from server")
#
# Remove the second DHCP server
@@ -1210,9 +1275,9 @@ class TestDHCP(VppTestCase):
rx = self.pg1.get_capture(1)
- self.verify_dhcp6_solicit(rx[0], self.pg1,
- dhcp_solicit_src_vrf1,
- self.pg4.remote_mac)
+ self.verify_dhcp6_solicit(
+ rx[0], self.pg1, dhcp_solicit_src_vrf1, self.pg4.remote_mac
+ )
#
# Cleanup
@@ -1226,10 +1291,10 @@ class TestDHCP(VppTestCase):
self.pg5.unconfig_ip6()
def test_dhcp_client(self):
- """ DHCP Client"""
+ """DHCP Client"""
vdscp = VppEnum.vl_api_ip_dscp_t
- hostname = 'universal-dp'
+ hostname = "universal-dp"
self.pg_enable_capture(self.pg_interfaces)
@@ -1247,38 +1312,50 @@ class TestDHCP(VppTestCase):
#
# Send back on offer, expect the request
#
- p_offer = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst="255.255.255.255") /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) /
- BOOTP(op=1,
- yiaddr=self.pg3.local_ip4,
- chaddr=mac_pton(self.pg3.local_mac)) /
- DHCP(options=[('message-type', 'offer'),
- ('server_id', self.pg3.remote_ip4),
- 'end']))
+ p_offer = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst="255.255.255.255")
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT)
+ / BOOTP(
+ op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac)
+ )
+ / DHCP(
+ options=[
+ ("message-type", "offer"),
+ ("server_id", self.pg3.remote_ip4),
+ "end",
+ ]
+ )
+ )
self.pg3.add_stream(p_offer)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg3.get_capture(1)
- self.verify_orig_dhcp_request(rx[0], self.pg3, hostname,
- self.pg3.local_ip4)
+ self.verify_orig_dhcp_request(rx[0], self.pg3, hostname, self.pg3.local_ip4)
#
# Send an acknowledgment
#
- p_ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst="255.255.255.255") /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) /
- BOOTP(op=1, yiaddr=self.pg3.local_ip4,
- chaddr=mac_pton(self.pg3.local_mac)) /
- DHCP(options=[('message-type', 'ack'),
- ('subnet_mask', "255.255.255.0"),
- ('router', self.pg3.remote_ip4),
- ('server_id', self.pg3.remote_ip4),
- ('lease_time', 43200),
- 'end']))
+ p_ack = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst="255.255.255.255")
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT)
+ / BOOTP(
+ op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac)
+ )
+ / DHCP(
+ options=[
+ ("message-type", "ack"),
+ ("subnet_mask", "255.255.255.0"),
+ ("router", self.pg3.remote_ip4),
+ ("server_id", self.pg3.remote_ip4),
+ ("lease_time", 43200),
+ "end",
+ ]
+ )
+ )
self.pg3.add_stream(p_ack)
self.pg_enable_capture(self.pg_interfaces)
@@ -1317,16 +1394,19 @@ class TestDHCP(VppTestCase):
self.pg3.admin_down()
self.sleep(1)
self.pg3.admin_up()
- Client.set_client(self.pg3.sw_if_index, hostname,
- id=self.pg3.local_mac,
- dscp=vdscp.IP_API_DSCP_EF)
+ Client.set_client(
+ self.pg3.sw_if_index,
+ hostname,
+ id=self.pg3.local_mac,
+ dscp=vdscp.IP_API_DSCP_EF,
+ )
Client.add_vpp_config()
rx = self.pg3.get_capture(1)
- self.verify_orig_dhcp_discover(rx[0], self.pg3, hostname,
- self.pg3.local_mac,
- dscp=vdscp.IP_API_DSCP_EF)
+ self.verify_orig_dhcp_discover(
+ rx[0], self.pg3, hostname, self.pg3.local_mac, dscp=vdscp.IP_API_DSCP_EF
+ )
# TODO: VPP DHCP client should not accept DHCP OFFER message with
# the XID (Transaction ID) not matching the XID of the most recent
@@ -1338,24 +1418,31 @@ class TestDHCP(VppTestCase):
self.pg_start()
rx = self.pg3.get_capture(1)
- self.verify_orig_dhcp_request(rx[0], self.pg3, hostname,
- self.pg3.local_ip4,
- dscp=vdscp.IP_API_DSCP_EF)
+ self.verify_orig_dhcp_request(
+ rx[0], self.pg3, hostname, self.pg3.local_ip4, dscp=vdscp.IP_API_DSCP_EF
+ )
#
# unicast the ack to the offered address
#
- p_ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) /
- BOOTP(op=1, yiaddr=self.pg3.local_ip4,
- chaddr=mac_pton(self.pg3.local_mac)) /
- DHCP(options=[('message-type', 'ack'),
- ('subnet_mask', "255.255.255.0"),
- ('router', self.pg3.remote_ip4),
- ('server_id', self.pg3.remote_ip4),
- ('lease_time', 43200),
- 'end']))
+ p_ack = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4)
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT)
+ / BOOTP(
+ op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac)
+ )
+ / DHCP(
+ options=[
+ ("message-type", "ack"),
+ ("subnet_mask", "255.255.255.0"),
+ ("router", self.pg3.remote_ip4),
+ ("server_id", self.pg3.remote_ip4),
+ ("lease_time", 43200),
+ "end",
+ ]
+ )
+ )
self.pg3.add_stream(p_ack)
self.pg_enable_capture(self.pg_interfaces)
@@ -1391,55 +1478,65 @@ class TestDHCP(VppTestCase):
#
# Configure DHCP client on PG3 and capture the discover sent
#
- Client.set_client(
- self.pg3.sw_if_index,
- hostname,
- set_broadcast_flag=False)
+ Client.set_client(self.pg3.sw_if_index, hostname, set_broadcast_flag=False)
Client.add_vpp_config()
rx = self.pg3.get_capture(1)
- self.verify_orig_dhcp_discover(rx[0], self.pg3, hostname,
- broadcast=False)
+ self.verify_orig_dhcp_discover(rx[0], self.pg3, hostname, broadcast=False)
#
# Send back on offer, unicasted to the offered address.
# Expect the request.
#
- p_offer = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) /
- BOOTP(op=1, yiaddr=self.pg3.local_ip4,
- chaddr=mac_pton(self.pg3.local_mac)) /
- DHCP(options=[('message-type', 'offer'),
- ('server_id', self.pg3.remote_ip4),
- 'end']))
+ p_offer = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4)
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT)
+ / BOOTP(
+ op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac)
+ )
+ / DHCP(
+ options=[
+ ("message-type", "offer"),
+ ("server_id", self.pg3.remote_ip4),
+ "end",
+ ]
+ )
+ )
self.pg3.add_stream(p_offer)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg3.get_capture(1)
- self.verify_orig_dhcp_request(rx[0], self.pg3, hostname,
- self.pg3.local_ip4,
- broadcast=False)
+ self.verify_orig_dhcp_request(
+ rx[0], self.pg3, hostname, self.pg3.local_ip4, broadcast=False
+ )
#
# Send an acknowledgment, the lease renewal time is 2 seconds
# so we should expect the renew straight after
#
- p_ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) /
- BOOTP(op=1, yiaddr=self.pg3.local_ip4,
- chaddr=mac_pton(self.pg3.local_mac)) /
- DHCP(options=[('message-type', 'ack'),
- ('subnet_mask', "255.255.255.0"),
- ('router', self.pg3.remote_ip4),
- ('server_id', self.pg3.remote_ip4),
- ('lease_time', 43200),
- ('renewal_time', 2),
- 'end']))
+ p_ack = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4)
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT)
+ / BOOTP(
+ op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac)
+ )
+ / DHCP(
+ options=[
+ ("message-type", "ack"),
+ ("subnet_mask", "255.255.255.0"),
+ ("router", self.pg3.remote_ip4),
+ ("server_id", self.pg3.remote_ip4),
+ ("lease_time", 43200),
+ ("renewal_time", 2),
+ "end",
+ ]
+ )
+ )
self.pg3.add_stream(p_ack)
self.pg_enable_capture(self.pg_interfaces)
@@ -1465,19 +1562,15 @@ class TestDHCP(VppTestCase):
#
clients = self.vapi.dhcp_client_dump()
- self.assertEqual(clients[0].client.sw_if_index,
- self.pg3.sw_if_index)
- self.assertEqual(clients[0].lease.sw_if_index,
- self.pg3.sw_if_index)
+ self.assertEqual(clients[0].client.sw_if_index, self.pg3.sw_if_index)
+ self.assertEqual(clients[0].lease.sw_if_index, self.pg3.sw_if_index)
self.assertEqual(clients[0].client.hostname, hostname)
self.assertEqual(clients[0].lease.hostname, hostname)
# 0 = DISCOVER, 1 = REQUEST, 2 = BOUND
self.assertEqual(clients[0].lease.state, 2)
self.assertEqual(clients[0].lease.mask_width, 24)
- self.assertEqual(str(clients[0].lease.router_address),
- self.pg3.remote_ip4)
- self.assertEqual(str(clients[0].lease.host_address),
- self.pg3.local_ip4)
+ self.assertEqual(str(clients[0].lease.router_address), self.pg3.remote_ip4)
+ self.assertEqual(str(clients[0].lease.host_address), self.pg3.local_ip4)
#
# wait for the unicasted renewal
@@ -1490,37 +1583,46 @@ class TestDHCP(VppTestCase):
self.assertEqual(rx[0][ARP].pdst, self.pg3.remote_ip4)
# respond to the arp
- p_arp = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- ARP(op="is-at",
- hwdst=self.pg3.local_mac,
- hwsrc=self.pg3.remote_mac,
- pdst=self.pg3.local_ip4,
- psrc=self.pg3.remote_ip4))
+ p_arp = Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) / ARP(
+ op="is-at",
+ hwdst=self.pg3.local_mac,
+ hwsrc=self.pg3.remote_mac,
+ pdst=self.pg3.local_ip4,
+ psrc=self.pg3.remote_ip4,
+ )
self.pg3.add_stream(p_arp)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
# the next packet is the unicasted renewal
rx = self.pg3.get_capture(1, timeout=10)
- self.verify_orig_dhcp_request(rx[0], self.pg3, hostname,
- self.pg3.local_ip4,
- l2_bc=False,
- broadcast=False)
+ self.verify_orig_dhcp_request(
+ rx[0], self.pg3, hostname, self.pg3.local_ip4, l2_bc=False, broadcast=False
+ )
# send an ACK with different data from the original offer *
self.pg3.generate_remote_hosts(4)
- p_ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) /
- BOOTP(op=1, yiaddr=self.pg3.remote_hosts[3].ip4,
- chaddr=mac_pton(self.pg3.local_mac)) /
- DHCP(options=[('message-type', 'ack'),
- ('subnet_mask', "255.255.255.0"),
- ('router', self.pg3.remote_hosts[1].ip4),
- ('server_id', self.pg3.remote_hosts[2].ip4),
- ('lease_time', 43200),
- ('renewal_time', 2),
- 'end']))
+ p_ack = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4)
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT)
+ / BOOTP(
+ op=1,
+ yiaddr=self.pg3.remote_hosts[3].ip4,
+ chaddr=mac_pton(self.pg3.local_mac),
+ )
+ / DHCP(
+ options=[
+ ("message-type", "ack"),
+ ("subnet_mask", "255.255.255.0"),
+ ("router", self.pg3.remote_hosts[1].ip4),
+ ("server_id", self.pg3.remote_hosts[2].ip4),
+ ("lease_time", 43200),
+ ("renewal_time", 2),
+ "end",
+ ]
+ )
+ )
self.pg3.add_stream(p_ack)
self.pg_enable_capture(self.pg_interfaces)
@@ -1531,19 +1633,19 @@ class TestDHCP(VppTestCase):
#
clients = self.vapi.dhcp_client_dump()
- self.assertEqual(clients[0].client.sw_if_index,
- self.pg3.sw_if_index)
- self.assertEqual(clients[0].lease.sw_if_index,
- self.pg3.sw_if_index)
+ self.assertEqual(clients[0].client.sw_if_index, self.pg3.sw_if_index)
+ self.assertEqual(clients[0].lease.sw_if_index, self.pg3.sw_if_index)
self.assertEqual(clients[0].client.hostname, hostname)
self.assertEqual(clients[0].lease.hostname, hostname)
# 0 = DISCOVER, 1 = REQUEST, 2 = BOUND
self.assertEqual(clients[0].lease.state, 2)
self.assertEqual(clients[0].lease.mask_width, 24)
- self.assertEqual(str(clients[0].lease.router_address),
- self.pg3.remote_hosts[1].ip4)
- self.assertEqual(str(clients[0].lease.host_address),
- self.pg3.remote_hosts[3].ip4)
+ self.assertEqual(
+ str(clients[0].lease.router_address), self.pg3.remote_hosts[1].ip4
+ )
+ self.assertEqual(
+ str(clients[0].lease.host_address), self.pg3.remote_hosts[3].ip4
+ )
#
# remove the DHCP config
@@ -1577,39 +1679,51 @@ class TestDHCP(VppTestCase):
# Send back on offer with requested lease time, expect the request
#
lease_time = 1
- p_offer = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst='255.255.255.255') /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) /
- BOOTP(op=1,
- yiaddr=self.pg3.local_ip4,
- chaddr=mac_pton(self.pg3.local_mac)) /
- DHCP(options=[('message-type', 'offer'),
- ('server_id', self.pg3.remote_ip4),
- ('lease_time', lease_time),
- 'end']))
+ p_offer = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst="255.255.255.255")
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT)
+ / BOOTP(
+ op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac)
+ )
+ / DHCP(
+ options=[
+ ("message-type", "offer"),
+ ("server_id", self.pg3.remote_ip4),
+ ("lease_time", lease_time),
+ "end",
+ ]
+ )
+ )
self.pg3.add_stream(p_offer)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg3.get_capture(1)
- self.verify_orig_dhcp_request(rx[0], self.pg3, hostname,
- self.pg3.local_ip4)
+ self.verify_orig_dhcp_request(rx[0], self.pg3, hostname, self.pg3.local_ip4)
#
# Send an acknowledgment
#
- p_ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst='255.255.255.255') /
- UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT) /
- BOOTP(op=1, yiaddr=self.pg3.local_ip4,
- chaddr=mac_pton(self.pg3.local_mac)) /
- DHCP(options=[('message-type', 'ack'),
- ('subnet_mask', '255.255.255.0'),
- ('router', self.pg3.remote_ip4),
- ('server_id', self.pg3.remote_ip4),
- ('lease_time', lease_time),
- 'end']))
+ p_ack = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst="255.255.255.255")
+ / UDP(sport=DHCP4_SERVER_PORT, dport=DHCP4_CLIENT_PORT)
+ / BOOTP(
+ op=1, yiaddr=self.pg3.local_ip4, chaddr=mac_pton(self.pg3.local_mac)
+ )
+ / DHCP(
+ options=[
+ ("message-type", "ack"),
+ ("subnet_mask", "255.255.255.0"),
+ ("router", self.pg3.remote_ip4),
+ ("server_id", self.pg3.remote_ip4),
+ ("lease_time", lease_time),
+ "end",
+ ]
+ )
+ )
self.pg3.add_stream(p_ack)
self.pg_enable_capture(self.pg_interfaces)
@@ -1641,11 +1755,11 @@ class TestDHCP(VppTestCase):
Client.remove_vpp_config()
def test_dhcp_client_vlan(self):
- """ DHCP Client w/ VLAN"""
+ """DHCP Client w/ VLAN"""
vdscp = VppEnum.vl_api_ip_dscp_t
vqos = VppEnum.vl_api_qos_source_t
- hostname = 'universal-dp'
+ hostname = "universal-dp"
self.pg_enable_capture(self.pg_interfaces)
@@ -1653,24 +1767,20 @@ class TestDHCP(VppTestCase):
vlan_100.admin_up()
output = [scapy.compat.chb(4)] * 256
- os = b''.join(output)
- rows = [{'outputs': os},
- {'outputs': os},
- {'outputs': os},
- {'outputs': os}]
+ os = b"".join(output)
+ rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}]
qem1 = VppQosEgressMap(self, 1, rows).add_vpp_config()
- qm1 = VppQosMark(self, vlan_100, qem1,
- vqos.QOS_API_SOURCE_VLAN).add_vpp_config()
+ qm1 = VppQosMark(
+ self, vlan_100, qem1, vqos.QOS_API_SOURCE_VLAN
+ ).add_vpp_config()
#
# Configure DHCP client on PG3 and capture the discover sent
#
Client = VppDHCPClient(
- self,
- vlan_100.sw_if_index,
- hostname,
- dscp=vdscp.IP_API_DSCP_EF)
+ self, vlan_100.sw_if_index, hostname, dscp=vdscp.IP_API_DSCP_EF
+ )
Client.add_vpp_config()
rx = self.pg3.get_capture(1)
@@ -1678,9 +1788,10 @@ class TestDHCP(VppTestCase):
self.assertEqual(rx[0][Dot1Q].vlan, 100)
self.assertEqual(rx[0][Dot1Q].prio, 2)
- self.verify_orig_dhcp_discover(rx[0], self.pg3, hostname,
- dscp=vdscp.IP_API_DSCP_EF)
+ self.verify_orig_dhcp_discover(
+ rx[0], self.pg3, hostname, dscp=vdscp.IP_API_DSCP_EF
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_dhcp6.py b/test/test_dhcp6.py
index 57eb113fb13..8a00cb81f90 100644
--- a/test/test_dhcp6.py
+++ b/test/test_dhcp6.py
@@ -1,10 +1,24 @@
from socket import AF_INET6, inet_ntop, inet_pton
-from scapy.layers.dhcp6 import DHCP6_Advertise, DHCP6OptClientId, \
- DHCP6OptStatusCode, DHCP6OptPref, DHCP6OptIA_PD, DHCP6OptIAPrefix, \
- DHCP6OptServerId, DHCP6_Solicit, DHCP6_Reply, DHCP6_Request, DHCP6_Renew, \
- DHCP6_Rebind, DUID_LL, DHCP6_Release, DHCP6OptElapsedTime, DHCP6OptIA_NA, \
- DHCP6OptIAAddress
+from scapy.layers.dhcp6 import (
+ DHCP6_Advertise,
+ DHCP6OptClientId,
+ DHCP6OptStatusCode,
+ DHCP6OptPref,
+ DHCP6OptIA_PD,
+ DHCP6OptIAPrefix,
+ DHCP6OptServerId,
+ DHCP6_Solicit,
+ DHCP6_Reply,
+ DHCP6_Request,
+ DHCP6_Renew,
+ DHCP6_Rebind,
+ DUID_LL,
+ DHCP6_Release,
+ DHCP6OptElapsedTime,
+ DHCP6OptIA_NA,
+ DHCP6OptIAAddress,
+)
from scapy.layers.inet6 import IPv6, Ether, UDP
from scapy.utils6 import in6_mactoifaceid
@@ -21,7 +35,7 @@ def ip6_normalize(ip6):
class TestDHCPv6DataPlane(VppTestCase):
- """ DHCPv6 Data Plane Test Case """
+ """DHCPv6 Data Plane Test Case"""
@classmethod
def setUpClass(cls):
@@ -49,25 +63,23 @@ class TestDHCPv6DataPlane(VppTestCase):
super(TestDHCPv6DataPlane, self).tearDown()
def test_dhcp_ia_na_send_solicit_receive_advertise(self):
- """ Verify DHCPv6 IA NA Solicit packet and Advertise event """
+ """Verify DHCPv6 IA NA Solicit packet and Advertise event"""
self.vapi.dhcp6_clients_enable_disable(enable=1)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- address = {'address': '1:2:3::5',
- 'preferred_time': 60,
- 'valid_time': 120}
+ address = {"address": "1:2:3::5", "preferred_time": 60, "valid_time": 120}
self.vapi.dhcp6_send_client_message(
- server_index=0xffffffff,
+ server_index=0xFFFFFFFF,
mrc=1,
msg_type=VppEnum.vl_api_dhcpv6_msg_type_t.DHCPV6_MSG_API_SOLICIT,
sw_if_index=self.pg0.sw_if_index,
T1=20,
T2=40,
addresses=[address],
- n_addresses=len(
- [address]))
+ n_addresses=len([address]),
+ )
rx_list = self.pg0.get_capture(1)
self.assertEqual(len(rx_list), 1)
packet = rx_list[0]
@@ -89,27 +101,27 @@ class TestDHCPv6DataPlane(VppTestCase):
self.assert_equal(ia_na.T2, 40)
self.assert_equal(len(ia_na.ianaopts), 1)
address = ia_na.ianaopts[0]
- self.assert_equal(address.addr, '1:2:3::5')
+ self.assert_equal(address.addr, "1:2:3::5")
self.assert_equal(address.preflft, 60)
self.assert_equal(address.validlft, 120)
- self.vapi.want_dhcp6_reply_events(enable_disable=1,
- pid=os.getpid())
+ self.vapi.want_dhcp6_reply_events(enable_disable=1, pid=os.getpid())
try:
- ia_na_opts = DHCP6OptIAAddress(addr='7:8::2', preflft=60,
- validlft=120)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=util.mk_ll_addr(self.pg0.remote_mac),
- dst=self.pg0.local_ip6_ll) /
- UDP(sport=547, dport=546) /
- DHCP6_Advertise(trid=trid) /
- DHCP6OptServerId(duid=self.server_duid) /
- DHCP6OptClientId(duid=client_duid) /
- DHCP6OptPref(prefval=7) /
- DHCP6OptStatusCode(statuscode=1) /
- DHCP6OptIA_NA(iaid=1, T1=20, T2=40, ianaopts=ia_na_opts)
- )
+ ia_na_opts = DHCP6OptIAAddress(addr="7:8::2", preflft=60, validlft=120)
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(
+ src=util.mk_ll_addr(self.pg0.remote_mac), dst=self.pg0.local_ip6_ll
+ )
+ / UDP(sport=547, dport=546)
+ / DHCP6_Advertise(trid=trid)
+ / DHCP6OptServerId(duid=self.server_duid)
+ / DHCP6OptClientId(duid=client_duid)
+ / DHCP6OptPref(prefval=7)
+ / DHCP6OptStatusCode(statuscode=1)
+ / DHCP6OptIA_NA(iaid=1, T1=20, T2=40, ianaopts=ia_na_opts)
+ )
self.pg0.add_stream([p])
self.pg_start()
@@ -123,36 +135,41 @@ class TestDHCPv6DataPlane(VppTestCase):
reported_address = ev.addresses[0]
address = ia_na_opts.getfieldval("addr")
self.assert_equal(str(reported_address.address), address)
- self.assert_equal(reported_address.preferred_time,
- ia_na_opts.getfieldval("preflft"))
- self.assert_equal(reported_address.valid_time,
- ia_na_opts.getfieldval("validlft"))
+ self.assert_equal(
+ reported_address.preferred_time, ia_na_opts.getfieldval("preflft")
+ )
+ self.assert_equal(
+ reported_address.valid_time, ia_na_opts.getfieldval("validlft")
+ )
finally:
self.vapi.want_dhcp6_reply_events(enable_disable=0)
self.vapi.dhcp6_clients_enable_disable(enable=0)
def test_dhcp_pd_send_solicit_receive_advertise(self):
- """ Verify DHCPv6 PD Solicit packet and Advertise event """
+ """Verify DHCPv6 PD Solicit packet and Advertise event"""
self.vapi.dhcp6_clients_enable_disable(enable=1)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- prefix = {'prefix': {'address': '1:2:3::', 'len': 50},
- 'preferred_time': 60,
- 'valid_time': 120}
+ prefix = {
+ "prefix": {"address": "1:2:3::", "len": 50},
+ "preferred_time": 60,
+ "valid_time": 120,
+ }
prefixes = [prefix]
self.vapi.dhcp6_pd_send_client_message(
- server_index=0xffffffff,
+ server_index=0xFFFFFFFF,
mrc=1,
msg_type=VppEnum.vl_api_dhcpv6_msg_type_t.DHCPV6_MSG_API_SOLICIT,
sw_if_index=self.pg0.sw_if_index,
T1=20,
T2=40,
prefixes=prefixes,
- n_prefixes=len(prefixes))
+ n_prefixes=len(prefixes),
+ )
rx_list = self.pg0.get_capture(1)
self.assertEqual(len(rx_list), 1)
packet = rx_list[0]
@@ -174,28 +191,30 @@ class TestDHCPv6DataPlane(VppTestCase):
self.assert_equal(ia_pd.T2, 40)
self.assert_equal(len(ia_pd.iapdopt), 1)
prefix = ia_pd.iapdopt[0]
- self.assert_equal(prefix.prefix, '1:2:3::')
+ self.assert_equal(prefix.prefix, "1:2:3::")
self.assert_equal(prefix.plen, 50)
self.assert_equal(prefix.preflft, 60)
self.assert_equal(prefix.validlft, 120)
- self.vapi.want_dhcp6_pd_reply_events(enable_disable=1,
- pid=os.getpid())
+ self.vapi.want_dhcp6_pd_reply_events(enable_disable=1, pid=os.getpid())
try:
- ia_pd_opts = DHCP6OptIAPrefix(prefix='7:8::', plen=56, preflft=60,
- validlft=120)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=util.mk_ll_addr(self.pg0.remote_mac),
- dst=self.pg0.local_ip6_ll) /
- UDP(sport=547, dport=546) /
- DHCP6_Advertise(trid=trid) /
- DHCP6OptServerId(duid=self.server_duid) /
- DHCP6OptClientId(duid=client_duid) /
- DHCP6OptPref(prefval=7) /
- DHCP6OptStatusCode(statuscode=1) /
- DHCP6OptIA_PD(iaid=1, T1=20, T2=40, iapdopt=ia_pd_opts)
- )
+ ia_pd_opts = DHCP6OptIAPrefix(
+ prefix="7:8::", plen=56, preflft=60, validlft=120
+ )
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(
+ src=util.mk_ll_addr(self.pg0.remote_mac), dst=self.pg0.local_ip6_ll
+ )
+ / UDP(sport=547, dport=546)
+ / DHCP6_Advertise(trid=trid)
+ / DHCP6OptServerId(duid=self.server_duid)
+ / DHCP6OptClientId(duid=client_duid)
+ / DHCP6OptPref(prefval=7)
+ / DHCP6OptStatusCode(statuscode=1)
+ / DHCP6OptIA_PD(iaid=1, T1=20, T2=40, iapdopt=ia_pd_opts)
+ )
self.pg0.add_stream([p])
self.pg_start()
@@ -208,14 +227,17 @@ class TestDHCPv6DataPlane(VppTestCase):
reported_prefix = ev.prefixes[0]
prefix = ia_pd_opts.getfieldval("prefix")
+ self.assert_equal(str(reported_prefix.prefix).split("/")[0], prefix)
+ self.assert_equal(
+ int(str(reported_prefix.prefix).split("/")[1]),
+ ia_pd_opts.getfieldval("plen"),
+ )
self.assert_equal(
- str(reported_prefix.prefix).split('/')[0], prefix)
- self.assert_equal(int(str(reported_prefix.prefix).split('/')[1]),
- ia_pd_opts.getfieldval("plen"))
- self.assert_equal(reported_prefix.preferred_time,
- ia_pd_opts.getfieldval("preflft"))
- self.assert_equal(reported_prefix.valid_time,
- ia_pd_opts.getfieldval("validlft"))
+ reported_prefix.preferred_time, ia_pd_opts.getfieldval("preflft")
+ )
+ self.assert_equal(
+ reported_prefix.valid_time, ia_pd_opts.getfieldval("validlft")
+ )
finally:
self.vapi.want_dhcp6_pd_reply_events(enable_disable=0)
@@ -224,7 +246,7 @@ class TestDHCPv6DataPlane(VppTestCase):
@tag_run_solo
class TestDHCPv6IANAControlPlane(VppTestCase):
- """ DHCPv6 IA NA Control Plane Test Case """
+ """DHCPv6 IA NA Control Plane Test Case"""
@classmethod
def setUpClass(cls):
@@ -248,18 +270,19 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
self.T2 = 2
fib = self.vapi.ip_route_dump(0, True)
- self.initial_addresses = set(self.get_interface_addresses(fib,
- self.pg0))
+ self.initial_addresses = set(self.get_interface_addresses(fib, self.pg0))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.vapi.dhcp6_client_enable_disable(sw_if_index=self.pg0.sw_if_index,
- enable=1)
+ self.vapi.dhcp6_client_enable_disable(
+ sw_if_index=self.pg0.sw_if_index, enable=1
+ )
def tearDown(self):
- self.vapi.dhcp6_client_enable_disable(sw_if_index=self.pg0.sw_if_index,
- enable=0)
+ self.vapi.dhcp6_client_enable_disable(
+ sw_if_index=self.pg0.sw_if_index, enable=0
+ )
for i in self.interfaces:
i.admin_down()
@@ -302,12 +325,12 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
self.trid = packet[msg_type].trid
ip = packet[IPv6]
udp = packet[UDP]
- self.assertEqual(ip.dst, 'ff02::1:2')
+ self.assertEqual(ip.dst, "ff02::1:2")
self.assertEqual(udp.sport, 546)
self.assertEqual(udp.dport, 547)
dhcpv6 = packet[msg_type]
elapsed_time = dhcpv6[DHCP6OptElapsedTime]
- if (is_resend):
+ if is_resend:
self.assertNotEqual(elapsed_time.elapsedtime, 0)
else:
self.assertEqual(elapsed_time.elapsedtime, 0)
@@ -346,15 +369,15 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
opt_ia_na = DHCP6OptIA_NA(iaid=1, T1=t1, T2=t2)
else:
opt_ia_na = DHCP6OptIA_NA(iaid=1, T1=t1, T2=t2, ianaopts=ianaopts)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=util.mk_ll_addr(self.pg0.remote_mac),
- dst=self.pg0.local_ip6_ll) /
- UDP(sport=547, dport=546) /
- msg_type(trid=self.trid) /
- DHCP6OptServerId(duid=self.server_duid) /
- DHCP6OptClientId(duid=self.client_duid) /
- opt_ia_na
- )
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=util.mk_ll_addr(self.pg0.remote_mac), dst=self.pg0.local_ip6_ll)
+ / UDP(sport=547, dport=546)
+ / msg_type(trid=self.trid)
+ / DHCP6OptServerId(duid=self.server_duid)
+ / DHCP6OptClientId(duid=self.client_duid)
+ / opt_ia_na
+ )
self.pg0.add_stream([p])
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -366,7 +389,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
self.send_packet(DHCP6_Reply, t1, t2, ianaopts)
def test_T1_and_T2_timeouts(self):
- """ Test T1 and T2 timeouts """
+ """Test T1 and T2 timeouts"""
self.wait_for_solicit()
self.send_advertise()
@@ -384,10 +407,9 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
self.wait_for_rebind()
def test_addresses(self):
- """ Test handling of addresses """
+ """Test handling of addresses"""
- ia_na_opts = DHCP6OptIAAddress(addr='7:8::2', preflft=1,
- validlft=2)
+ ia_na_opts = DHCP6OptIAAddress(addr="7:8::2", preflft=1, validlft=2)
self.wait_for_solicit()
self.send_advertise(t1=20, t2=40, ianaopts=ia_na_opts)
@@ -399,7 +421,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
new_addresses = self.get_addresses()
self.assertEqual(len(new_addresses), 1)
addr = list(new_addresses)[0]
- self.assertEqual(addr, '7:8::2')
+ self.assertEqual(addr, "7:8::2")
self.sleep(2)
@@ -410,7 +432,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
self.assertEqual(len(new_addresses), 0)
def test_sending_client_messages_solicit(self):
- """ VPP receives messages from DHCPv6 client """
+ """VPP receives messages from DHCPv6 client"""
self.wait_for_solicit()
self.send_packet(DHCP6_Solicit)
@@ -421,7 +443,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
self.wait_for_solicit(is_resend=True)
def test_sending_inappropriate_packets(self):
- """ Server sends messages with inappropriate message types """
+ """Server sends messages with inappropriate message types"""
self.wait_for_solicit()
self.send_reply()
@@ -434,7 +456,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
self.wait_for_renew()
def test_no_address_available_in_advertise(self):
- """ Advertise message contains NoAddrsAvail status code """
+ """Advertise message contains NoAddrsAvail status code"""
self.wait_for_solicit()
noavail = DHCP6OptStatusCode(statuscode=2) # NoAddrsAvail
@@ -442,12 +464,12 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
self.wait_for_solicit(is_resend=True)
def test_preferred_greater_than_valid_lifetime(self):
- """ Preferred lifetime is greater than valid lifetime """
+ """Preferred lifetime is greater than valid lifetime"""
self.wait_for_solicit()
self.send_advertise()
self.wait_for_request()
- ia_na_opts = DHCP6OptIAAddress(addr='7:8::2', preflft=4, validlft=3)
+ ia_na_opts = DHCP6OptIAAddress(addr="7:8::2", preflft=4, validlft=3)
self.send_reply(ianaopts=ia_na_opts)
self.sleep(0.5)
@@ -459,12 +481,12 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
self.assertEqual(len(new_addresses), 0)
def test_T1_greater_than_T2(self):
- """ T1 is greater than T2 """
+ """T1 is greater than T2"""
self.wait_for_solicit()
self.send_advertise()
self.wait_for_request()
- ia_na_opts = DHCP6OptIAAddress(addr='7:8::2', preflft=4, validlft=8)
+ ia_na_opts = DHCP6OptIAAddress(addr="7:8::2", preflft=4, validlft=8)
self.send_reply(t1=80, t2=40, ianaopts=ia_na_opts)
self.sleep(0.5)
@@ -478,7 +500,7 @@ class TestDHCPv6IANAControlPlane(VppTestCase):
@tag_fixme_vpp_workers
class TestDHCPv6PDControlPlane(VppTestCase):
- """ DHCPv6 PD Control Plane Test Case """
+ """DHCPv6 PD Control Plane Test Case"""
@classmethod
def setUpClass(cls):
@@ -502,22 +524,19 @@ class TestDHCPv6PDControlPlane(VppTestCase):
self.T2 = 2
fib = self.vapi.ip_route_dump(0, True)
- self.initial_addresses = set(self.get_interface_addresses(fib,
- self.pg1))
+ self.initial_addresses = set(self.get_interface_addresses(fib, self.pg1))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.prefix_group = 'my-pd-prefix-group'
+ self.prefix_group = "my-pd-prefix-group"
self.vapi.dhcp6_pd_client_enable_disable(
- enable=1,
- sw_if_index=self.pg0.sw_if_index,
- prefix_group=self.prefix_group)
+ enable=1, sw_if_index=self.pg0.sw_if_index, prefix_group=self.prefix_group
+ )
def tearDown(self):
- self.vapi.dhcp6_pd_client_enable_disable(self.pg0.sw_if_index,
- enable=0)
+ self.vapi.dhcp6_pd_client_enable_disable(self.pg0.sw_if_index, enable=0)
for i in self.interfaces:
i.admin_down()
@@ -560,12 +579,12 @@ class TestDHCPv6PDControlPlane(VppTestCase):
self.trid = packet[msg_type].trid
ip = packet[IPv6]
udp = packet[UDP]
- self.assertEqual(ip.dst, 'ff02::1:2')
+ self.assertEqual(ip.dst, "ff02::1:2")
self.assertEqual(udp.sport, 546)
self.assertEqual(udp.dport, 547)
dhcpv6 = packet[msg_type]
elapsed_time = dhcpv6[DHCP6OptElapsedTime]
- if (is_resend):
+ if is_resend:
self.assertNotEqual(elapsed_time.elapsedtime, 0)
else:
self.assertEqual(elapsed_time.elapsedtime, 0)
@@ -604,15 +623,15 @@ class TestDHCPv6PDControlPlane(VppTestCase):
opt_ia_pd = DHCP6OptIA_PD(iaid=1, T1=t1, T2=t2)
else:
opt_ia_pd = DHCP6OptIA_PD(iaid=1, T1=t1, T2=t2, iapdopt=iapdopt)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=util.mk_ll_addr(self.pg0.remote_mac),
- dst=self.pg0.local_ip6_ll) /
- UDP(sport=547, dport=546) /
- msg_type(trid=self.trid) /
- DHCP6OptServerId(duid=self.server_duid) /
- DHCP6OptClientId(duid=self.client_duid) /
- opt_ia_pd
- )
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=util.mk_ll_addr(self.pg0.remote_mac), dst=self.pg0.local_ip6_ll)
+ / UDP(sport=547, dport=546)
+ / msg_type(trid=self.trid)
+ / DHCP6OptServerId(duid=self.server_duid)
+ / DHCP6OptClientId(duid=self.client_duid)
+ / opt_ia_pd
+ )
self.pg0.add_stream([p])
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -624,7 +643,7 @@ class TestDHCPv6PDControlPlane(VppTestCase):
self.send_packet(DHCP6_Reply, t1, t2, iapdopt)
def test_T1_and_T2_timeouts(self):
- """ Test T1 and T2 timeouts """
+ """Test T1 and T2 timeouts"""
self.wait_for_solicit()
self.send_advertise()
@@ -642,18 +661,20 @@ class TestDHCPv6PDControlPlane(VppTestCase):
self.wait_for_rebind()
def test_prefixes(self):
- """ Test handling of prefixes """
+ """Test handling of prefixes"""
- address1 = '::2:0:0:0:405/60'
- address2 = '::76:0:0:0:406/62'
+ address1 = "::2:0:0:0:405/60"
+ address2 = "::76:0:0:0:406/62"
try:
self.vapi.ip6_add_del_address_using_prefix(
sw_if_index=self.pg1.sw_if_index,
address_with_prefix=address1,
- prefix_group=self.prefix_group)
+ prefix_group=self.prefix_group,
+ )
- ia_pd_opts = DHCP6OptIAPrefix(prefix='7:8::', plen=56, preflft=2,
- validlft=3)
+ ia_pd_opts = DHCP6OptIAPrefix(
+ prefix="7:8::", plen=56, preflft=2, validlft=3
+ )
self.wait_for_solicit()
self.send_advertise(t1=20, t2=40, iapdopt=ia_pd_opts)
@@ -665,14 +686,15 @@ class TestDHCPv6PDControlPlane(VppTestCase):
new_addresses = self.get_addresses()
self.assertEqual(len(new_addresses), 1)
addr = list(new_addresses)[0]
- self.assertEqual(addr, '7:8:0:2::405')
+ self.assertEqual(addr, "7:8:0:2::405")
self.sleep(1)
self.vapi.ip6_add_del_address_using_prefix(
sw_if_index=self.pg1.sw_if_index,
address_with_prefix=address2,
- prefix_group=self.prefix_group)
+ prefix_group=self.prefix_group,
+ )
self.sleep(1)
@@ -683,10 +705,10 @@ class TestDHCPv6PDControlPlane(VppTestCase):
self.assertEqual(len(new_addresses), 2)
addr1 = list(new_addresses)[0]
addr2 = list(new_addresses)[1]
- if addr1 == '7:8:0:76::406':
+ if addr1 == "7:8:0:76::406":
addr1, addr2 = addr2, addr1
- self.assertEqual(addr1, '7:8:0:2::405')
- self.assertEqual(addr2, '7:8:0:76::406')
+ self.assertEqual(addr1, "7:8:0:2::405")
+ self.assertEqual(addr2, "7:8:0:76::406")
self.sleep(1)
@@ -701,15 +723,19 @@ class TestDHCPv6PDControlPlane(VppTestCase):
self.vapi.ip6_add_del_address_using_prefix(
sw_if_index=self.pg1.sw_if_index,
address_with_prefix=address1,
- prefix_group=self.prefix_group, is_add=0)
+ prefix_group=self.prefix_group,
+ is_add=0,
+ )
if address2 is not None:
self.vapi.ip6_add_del_address_using_prefix(
sw_if_index=self.pg1.sw_if_index,
address_with_prefix=address2,
- prefix_group=self.prefix_group, is_add=0)
+ prefix_group=self.prefix_group,
+ is_add=0,
+ )
def test_sending_client_messages_solicit(self):
- """ VPP receives messages from DHCPv6 client """
+ """VPP receives messages from DHCPv6 client"""
self.wait_for_solicit()
self.send_packet(DHCP6_Solicit)
@@ -720,7 +746,7 @@ class TestDHCPv6PDControlPlane(VppTestCase):
self.wait_for_solicit(is_resend=True)
def test_sending_inappropriate_packets(self):
- """ Server sends messages with inappropriate message types """
+ """Server sends messages with inappropriate message types"""
self.wait_for_solicit()
self.send_reply()
@@ -733,7 +759,7 @@ class TestDHCPv6PDControlPlane(VppTestCase):
self.wait_for_renew()
def test_no_prefix_available_in_advertise(self):
- """ Advertise message contains NoPrefixAvail status code """
+ """Advertise message contains NoPrefixAvail status code"""
self.wait_for_solicit()
noavail = DHCP6OptStatusCode(statuscode=6) # NoPrefixAvail
@@ -741,20 +767,22 @@ class TestDHCPv6PDControlPlane(VppTestCase):
self.wait_for_solicit(is_resend=True)
def test_preferred_greater_than_valid_lifetime(self):
- """ Preferred lifetime is greater than valid lifetime """
+ """Preferred lifetime is greater than valid lifetime"""
- address1 = '::2:0:0:0:405/60'
+ address1 = "::2:0:0:0:405/60"
try:
self.vapi.ip6_add_del_address_using_prefix(
sw_if_index=self.pg1.sw_if_index,
address_with_prefix=address1,
- prefix_group=self.prefix_group)
+ prefix_group=self.prefix_group,
+ )
self.wait_for_solicit()
self.send_advertise()
self.wait_for_request()
- ia_pd_opts = DHCP6OptIAPrefix(prefix='7:8::', plen=56, preflft=4,
- validlft=3)
+ ia_pd_opts = DHCP6OptIAPrefix(
+ prefix="7:8::", plen=56, preflft=4, validlft=3
+ )
self.send_reply(iapdopt=ia_pd_opts)
self.sleep(0.5)
@@ -770,23 +798,26 @@ class TestDHCPv6PDControlPlane(VppTestCase):
sw_if_index=self.pg1.sw_if_index,
address_with_prefix=address1,
prefix_group=self.prefix_group,
- is_add=0)
+ is_add=0,
+ )
def test_T1_greater_than_T2(self):
- """ T1 is greater than T2 """
+ """T1 is greater than T2"""
- address1 = '::2:0:0:0:405/60'
+ address1 = "::2:0:0:0:405/60"
try:
self.vapi.ip6_add_del_address_using_prefix(
sw_if_index=self.pg1.sw_if_index,
address_with_prefix=address1,
- prefix_group=self.prefix_group)
+ prefix_group=self.prefix_group,
+ )
self.wait_for_solicit()
self.send_advertise()
self.wait_for_request()
- ia_pd_opts = DHCP6OptIAPrefix(prefix='7:8::', plen=56, preflft=4,
- validlft=8)
+ ia_pd_opts = DHCP6OptIAPrefix(
+ prefix="7:8::", plen=56, preflft=4, validlft=8
+ )
self.send_reply(t1=80, t2=40, iapdopt=ia_pd_opts)
self.sleep(0.5)
@@ -802,4 +833,5 @@ class TestDHCPv6PDControlPlane(VppTestCase):
sw_if_index=self.pg1.sw_if_index,
prefix_group=self.prefix_group,
address_with_prefix=address1,
- is_add=False)
+ is_add=False,
+ )
diff --git a/test/test_dns.py b/test/test_dns.py
index fb8958c511b..acc9bfe889c 100644
--- a/test/test_dns.py
+++ b/test/test_dns.py
@@ -15,7 +15,7 @@ from scapy.layers.dns import DNSRR, DNS, DNSQR
class TestDns(VppTestCase):
- """ Dns Test Cases """
+ """Dns Test Cases"""
@classmethod
def setUpClass(cls):
@@ -43,15 +43,19 @@ class TestDns(VppTestCase):
:param VppInterface src_if: Interface to create packet stream for.
"""
- good_request = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=src_if.remote_ip4) /
- UDP(sport=1234, dport=53) /
- DNS(rd=1, qd=DNSQR(qname="bozo.clown.org")))
-
- bad_request = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=src_if.remote_ip4) /
- UDP(sport=1234, dport=53) /
- DNS(rd=1, qd=DNSQR(qname="no.clown.org")))
+ good_request = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=src_if.remote_ip4)
+ / UDP(sport=1234, dport=53)
+ / DNS(rd=1, qd=DNSQR(qname="bozo.clown.org"))
+ )
+
+ bad_request = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=src_if.remote_ip4)
+ / UDP(sport=1234, dport=53)
+ / DNS(rd=1, qd=DNSQR(qname="no.clown.org"))
+ )
pkts = [good_request, bad_request]
return pkts
@@ -65,14 +69,15 @@ class TestDns(VppTestCase):
self.logger.info("Verifying capture on interface %s" % dst_if.name)
for packet in capture:
dns = packet[DNS]
- self.assertEqual(dns.an[0].rdata, '1.2.3.4')
+ self.assertEqual(dns.an[0].rdata, "1.2.3.4")
def test_dns_unittest(self):
- """ DNS Name Resolver Basic Functional Test """
+ """DNS Name Resolver Basic Functional Test"""
# Set up an upstream name resolver. We won't actually go there
self.vapi.dns_name_server_add_del(
- is_ip6=0, is_add=1, server_address=IPv4Address(u'8.8.8.8').packed)
+ is_ip6=0, is_add=1, server_address=IPv4Address("8.8.8.8").packed
+ )
# Enable name resolution
self.vapi.dns_enable_disable(enable=1)
@@ -81,13 +86,13 @@ class TestDns(VppTestCase):
self.logger.info(self.vapi.cli("dns cache add bozo.clown.org 1.2.3.4"))
# Test the binary API
- rv = self.vapi.dns_resolve_name(name=b'bozo.clown.org')
- self.assertEqual(rv.ip4_address, IPv4Address(u'1.2.3.4').packed)
+ rv = self.vapi.dns_resolve_name(name=b"bozo.clown.org")
+ self.assertEqual(rv.ip4_address, IPv4Address("1.2.3.4").packed)
# Configure 127.0.0.1/8 on the pg interface
self.vapi.sw_interface_add_del_address(
- sw_if_index=self.pg0.sw_if_index,
- prefix="127.0.0.1/8")
+ sw_if_index=self.pg0.sw_if_index, prefix="127.0.0.1/8"
+ )
# Send a couple of DNS request packets, one for bozo.clown.org
# and one for no.clown.org which won't resolve
@@ -102,8 +107,9 @@ class TestDns(VppTestCase):
# Make sure that the cache contents are correct
str = self.vapi.cli("show dns cache verbose")
- self.assertIn('1.2.3.4', str)
- self.assertIn('[P] no.clown.org:', str)
+ self.assertIn("1.2.3.4", str)
+ self.assertIn("[P] no.clown.org:", str)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_dslite.py b/test/test_dslite.py
index 912ae17da58..cd3482b1cb5 100644
--- a/test/test_dslite.py
+++ b/test/test_dslite.py
@@ -11,8 +11,15 @@ from framework import VppTestCase, VppTestRunner
import scapy.compat
from scapy.layers.inet import IP, TCP, UDP, ICMP
from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror
-from scapy.layers.inet6 import IPv6, ICMPv6EchoRequest, ICMPv6EchoReply, \
- ICMPv6ND_NS, ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, fragment6
+from scapy.layers.inet6 import (
+ IPv6,
+ ICMPv6EchoRequest,
+ ICMPv6EchoReply,
+ ICMPv6ND_NS,
+ ICMPv6ND_NA,
+ ICMPv6NDOptDstLLAddr,
+ fragment6,
+)
from scapy.layers.inet6 import ICMPv6DestUnreach, IPerror6, IPv6ExtHdrFragment
from scapy.layers.l2 import Ether, ARP, GRE
from scapy.data import IP_PROTOS
@@ -28,22 +35,32 @@ from io import BytesIO
from vpp_papi import VppEnum
from vpp_ip_route import VppIpRoute, VppRoutePath, FibPathType
from vpp_neighbor import VppNeighbor
-from scapy.all import bind_layers, Packet, ByteEnumField, ShortField, \
- IPField, IntField, LongField, XByteField, FlagsField, FieldLenField, \
- PacketListField
+from scapy.all import (
+ bind_layers,
+ Packet,
+ ByteEnumField,
+ ShortField,
+ IPField,
+ IntField,
+ LongField,
+ XByteField,
+ FlagsField,
+ FieldLenField,
+ PacketListField,
+)
from ipaddress import IPv6Network
@tag_fixme_vpp_workers
class TestDSlite(VppTestCase):
- """ DS-Lite Test Cases """
+ """DS-Lite Test Cases"""
@classmethod
def setUpClass(cls):
super(TestDSlite, cls).setUpClass()
try:
- cls.nat_addr = '10.0.0.3'
+ cls.nat_addr = "10.0.0.3"
cls.create_pg_interfaces(range(3))
cls.pg0.admin_up()
@@ -65,44 +82,45 @@ class TestDSlite(VppTestCase):
def tearDownClass(cls):
super(TestDSlite, cls).tearDownClass()
- def verify_syslog_apmadd(self, data, isaddr, isport, xsaddr, xsport,
- sv6enc, proto):
- message = data.decode('utf-8')
+ def verify_syslog_apmadd(self, data, isaddr, isport, xsaddr, xsport, sv6enc, proto):
+ message = data.decode("utf-8")
try:
message = SyslogMessage.parse(message)
except ParseError as e:
self.logger.error(e)
else:
self.assertEqual(message.severity, SyslogSeverity.info)
- self.assertEqual(message.appname, 'NAT')
- self.assertEqual(message.msgid, 'APMADD')
- sd_params = message.sd.get('napmap')
+ self.assertEqual(message.appname, "NAT")
+ self.assertEqual(message.msgid, "APMADD")
+ sd_params = message.sd.get("napmap")
self.assertTrue(sd_params is not None)
- self.assertEqual(sd_params.get('IATYP'), 'IPv4')
- self.assertEqual(sd_params.get('ISADDR'), isaddr)
- self.assertEqual(sd_params.get('ISPORT'), "%d" % isport)
- self.assertEqual(sd_params.get('XATYP'), 'IPv4')
- self.assertEqual(sd_params.get('XSADDR'), xsaddr)
- self.assertEqual(sd_params.get('XSPORT'), "%d" % xsport)
- self.assertEqual(sd_params.get('PROTO'), "%d" % proto)
- self.assertTrue(sd_params.get('SSUBIX') is not None)
- self.assertEqual(sd_params.get('SV6ENC'), sv6enc)
+ self.assertEqual(sd_params.get("IATYP"), "IPv4")
+ self.assertEqual(sd_params.get("ISADDR"), isaddr)
+ self.assertEqual(sd_params.get("ISPORT"), "%d" % isport)
+ self.assertEqual(sd_params.get("XATYP"), "IPv4")
+ self.assertEqual(sd_params.get("XSADDR"), xsaddr)
+ self.assertEqual(sd_params.get("XSPORT"), "%d" % xsport)
+ self.assertEqual(sd_params.get("PROTO"), "%d" % proto)
+ self.assertTrue(sd_params.get("SSUBIX") is not None)
+ self.assertEqual(sd_params.get("SV6ENC"), sv6enc)
def test_dslite(self):
- """ Test DS-Lite """
- self.vapi.dslite_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- is_add=1)
- aftr_ip4 = '192.0.0.1'
- aftr_ip6 = '2001:db8:85a3::8a2e:370:1'
+ """Test DS-Lite"""
+ self.vapi.dslite_add_del_pool_addr_range(
+ start_addr=self.nat_addr, end_addr=self.nat_addr, is_add=1
+ )
+ aftr_ip4 = "192.0.0.1"
+ aftr_ip6 = "2001:db8:85a3::8a2e:370:1"
self.vapi.dslite_set_aftr_addr(ip4_addr=aftr_ip4, ip6_addr=aftr_ip6)
self.vapi.syslog_set_sender(self.pg2.local_ip4, self.pg2.remote_ip4)
# UDP
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[0].ip6) /
- IP(dst=self.pg0.remote_ip4, src='192.168.1.1') /
- UDP(sport=20000, dport=10000))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[0].ip6)
+ / IP(dst=self.pg0.remote_ip4, src="192.168.1.1")
+ / UDP(sport=20000, dport=10000)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -116,13 +134,21 @@ class TestDSlite(VppTestCase):
self.assert_packet_checksums_valid(capture)
out_port = capture[UDP].sport
capture = self.pg2.get_capture(1)
- self.verify_syslog_apmadd(capture[0][Raw].load, '192.168.1.1',
- 20000, self.nat_addr, out_port,
- self.pg1.remote_hosts[0].ip6, IP_PROTOS.udp)
-
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(dst=self.nat_addr, src=self.pg0.remote_ip4) /
- UDP(sport=10000, dport=out_port))
+ self.verify_syslog_apmadd(
+ capture[0][Raw].load,
+ "192.168.1.1",
+ 20000,
+ self.nat_addr,
+ out_port,
+ self.pg1.remote_hosts[0].ip6,
+ IP_PROTOS.udp,
+ )
+
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(dst=self.nat_addr, src=self.pg0.remote_ip4)
+ / UDP(sport=10000, dport=out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -131,16 +157,18 @@ class TestDSlite(VppTestCase):
self.assertEqual(capture[IPv6].src, aftr_ip6)
self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[0].ip6)
self.assertEqual(capture[IP].src, self.pg0.remote_ip4)
- self.assertEqual(capture[IP].dst, '192.168.1.1')
+ self.assertEqual(capture[IP].dst, "192.168.1.1")
self.assertEqual(capture[UDP].sport, 10000)
self.assertEqual(capture[UDP].dport, 20000)
self.assert_packet_checksums_valid(capture)
# TCP
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[1].ip6) /
- IP(dst=self.pg0.remote_ip4, src='192.168.1.1') /
- TCP(sport=20001, dport=10001))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[1].ip6)
+ / IP(dst=self.pg0.remote_ip4, src="192.168.1.1")
+ / TCP(sport=20001, dport=10001)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -154,9 +182,11 @@ class TestDSlite(VppTestCase):
self.assert_packet_checksums_valid(capture)
out_port = capture[TCP].sport
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(dst=self.nat_addr, src=self.pg0.remote_ip4) /
- TCP(sport=10001, dport=out_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(dst=self.nat_addr, src=self.pg0.remote_ip4)
+ / TCP(sport=10001, dport=out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -165,16 +195,18 @@ class TestDSlite(VppTestCase):
self.assertEqual(capture[IPv6].src, aftr_ip6)
self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[1].ip6)
self.assertEqual(capture[IP].src, self.pg0.remote_ip4)
- self.assertEqual(capture[IP].dst, '192.168.1.1')
+ self.assertEqual(capture[IP].dst, "192.168.1.1")
self.assertEqual(capture[TCP].sport, 10001)
self.assertEqual(capture[TCP].dport, 20001)
self.assert_packet_checksums_valid(capture)
# ICMP
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[1].ip6) /
- IP(dst=self.pg0.remote_ip4, src='192.168.1.1') /
- ICMP(id=4000, type='echo-request'))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(dst=aftr_ip6, src=self.pg1.remote_hosts[1].ip6)
+ / IP(dst=self.pg0.remote_ip4, src="192.168.1.1")
+ / ICMP(id=4000, type="echo-request")
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -187,9 +219,11 @@ class TestDSlite(VppTestCase):
self.assert_packet_checksums_valid(capture)
out_id = capture[ICMP].id
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(dst=self.nat_addr, src=self.pg0.remote_ip4) /
- ICMP(id=out_id, type='echo-reply'))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(dst=self.nat_addr, src=self.pg0.remote_ip4)
+ / ICMP(id=out_id, type="echo-reply")
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -198,14 +232,16 @@ class TestDSlite(VppTestCase):
self.assertEqual(capture[IPv6].src, aftr_ip6)
self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[1].ip6)
self.assertEqual(capture[IP].src, self.pg0.remote_ip4)
- self.assertEqual(capture[IP].dst, '192.168.1.1')
+ self.assertEqual(capture[IP].dst, "192.168.1.1")
self.assertEqual(capture[ICMP].id, 4000)
self.assert_packet_checksums_valid(capture)
# ping DS-Lite AFTR tunnel endpoint address
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_hosts[1].ip6, dst=aftr_ip6) /
- ICMPv6EchoRequest())
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_hosts[1].ip6, dst=aftr_ip6)
+ / ICMPv6EchoRequest()
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -215,9 +251,9 @@ class TestDSlite(VppTestCase):
self.assertEqual(capture[IPv6].dst, self.pg1.remote_hosts[1].ip6)
self.assertTrue(capture.haslayer(ICMPv6EchoReply))
- b4s = self.statistics.get_counter('/dslite/total-b4s')
+ b4s = self.statistics.get_counter("/dslite/total-b4s")
self.assertEqual(b4s[0][0], 2)
- sessions = self.statistics.get_counter('/dslite/total-sessions')
+ sessions = self.statistics.get_counter("/dslite/total-sessions")
self.assertEqual(sessions[0][0], 3)
def tearDown(self):
@@ -225,13 +261,12 @@ class TestDSlite(VppTestCase):
def show_commands_at_teardown(self):
self.logger.info(self.vapi.cli("show dslite pool"))
- self.logger.info(
- self.vapi.cli("show dslite aftr-tunnel-endpoint-address"))
+ self.logger.info(self.vapi.cli("show dslite aftr-tunnel-endpoint-address"))
self.logger.info(self.vapi.cli("show dslite sessions"))
class TestDSliteCE(VppTestCase):
- """ DS-Lite CE Test Cases """
+ """DS-Lite CE Test Cases"""
@classmethod
def setUpConstants(cls):
@@ -261,25 +296,30 @@ class TestDSliteCE(VppTestCase):
super(TestDSliteCE, cls).tearDownClass()
def test_dslite_ce(self):
- """ Test DS-Lite CE """
- b4_ip4 = '192.0.0.2'
- b4_ip6 = '2001:db8:62aa::375e:f4c1:1'
+ """Test DS-Lite CE"""
+ b4_ip4 = "192.0.0.2"
+ b4_ip6 = "2001:db8:62aa::375e:f4c1:1"
self.vapi.dslite_set_b4_addr(ip4_addr=b4_ip4, ip6_addr=b4_ip6)
- aftr_ip4 = '192.0.0.1'
- aftr_ip6 = '2001:db8:85a3::8a2e:370:1'
+ aftr_ip4 = "192.0.0.1"
+ aftr_ip6 = "2001:db8:85a3::8a2e:370:1"
aftr_ip6_n = socket.inet_pton(socket.AF_INET6, aftr_ip6)
self.vapi.dslite_set_aftr_addr(ip4_addr=aftr_ip4, ip6_addr=aftr_ip6)
- r1 = VppIpRoute(self, aftr_ip6, 128,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ r1 = VppIpRoute(
+ self,
+ aftr_ip6,
+ 128,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ )
r1.add_vpp_config()
# UDP encapsulation
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(dst=self.pg1.remote_ip4, src=self.pg0.remote_ip4) /
- UDP(sport=10000, dport=20000))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(dst=self.pg1.remote_ip4, src=self.pg0.remote_ip4)
+ / UDP(sport=10000, dport=20000)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -294,10 +334,12 @@ class TestDSliteCE(VppTestCase):
self.assert_packet_checksums_valid(capture)
# UDP decapsulation
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(dst=b4_ip6, src=aftr_ip6) /
- IP(dst=self.pg0.remote_ip4, src=self.pg1.remote_ip4) /
- UDP(sport=20000, dport=10000))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(dst=b4_ip6, src=aftr_ip6)
+ / IP(dst=self.pg0.remote_ip4, src=self.pg1.remote_ip4)
+ / UDP(sport=20000, dport=10000)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -311,9 +353,11 @@ class TestDSliteCE(VppTestCase):
self.assert_packet_checksums_valid(capture)
# ping DS-Lite B4 tunnel endpoint address
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_hosts[0].ip6, dst=b4_ip6) /
- ICMPv6EchoRequest())
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_hosts[0].ip6, dst=b4_ip6)
+ / ICMPv6EchoRequest()
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -327,7 +371,5 @@ class TestDSliteCE(VppTestCase):
super(TestDSliteCE, self).tearDown()
def show_commands_at_teardown(self):
- self.logger.info(
- self.vapi.cli("show dslite aftr-tunnel-endpoint-address"))
- self.logger.info(
- self.vapi.cli("show dslite b4-tunnel-endpoint-address"))
+ self.logger.info(self.vapi.cli("show dslite aftr-tunnel-endpoint-address"))
+ self.logger.info(self.vapi.cli("show dslite b4-tunnel-endpoint-address"))
diff --git a/test/test_dvr.py b/test/test_dvr.py
index c0424a3047f..cd2e09a9d46 100644
--- a/test/test_dvr.py
+++ b/test/test_dvr.py
@@ -17,7 +17,7 @@ NUM_PKTS = 67
class TestDVR(VppTestCase):
- """ Distributed Virtual Router """
+ """Distributed Virtual Router"""
@classmethod
def setUpClass(cls):
@@ -62,7 +62,7 @@ class TestDVR(VppTestCase):
self.assertFalse(p.haslayer(Dot1Q))
def test_dvr(self):
- """ Distributed Virtual Router """
+ """Distributed Virtual Router"""
#
# A packet destined to an IP address that is L2 bridged via
@@ -72,18 +72,18 @@ class TestDVR(VppTestCase):
ip_tag_bridged = "10.10.10.11"
any_src_addr = "1.1.1.1"
- pkt_no_tag = (Ether(src=self.pg0.remote_mac,
- dst=self.loop0.local_mac) /
- IP(src=any_src_addr,
- dst=ip_non_tag_bridged) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- pkt_tag = (Ether(src=self.pg0.remote_mac,
- dst=self.loop0.local_mac) /
- IP(src=any_src_addr,
- dst=ip_tag_bridged) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkt_no_tag = (
+ Ether(src=self.pg0.remote_mac, dst=self.loop0.local_mac)
+ / IP(src=any_src_addr, dst=ip_non_tag_bridged)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ pkt_tag = (
+ Ether(src=self.pg0.remote_mac, dst=self.loop0.local_mac)
+ / IP(src=any_src_addr, dst=ip_tag_bridged)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# Two sub-interfaces so we can test VLAN tag push/pop
@@ -97,32 +97,45 @@ class TestDVR(VppTestCase):
# Put all the interfaces into a new bridge domain
#
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg0.sw_if_index, bd_id=1)
+ rx_sw_if_index=self.pg0.sw_if_index, bd_id=1
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg1.sw_if_index, bd_id=1)
+ rx_sw_if_index=self.pg1.sw_if_index, bd_id=1
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=sub_if_on_pg2.sw_if_index, bd_id=1)
+ rx_sw_if_index=sub_if_on_pg2.sw_if_index, bd_id=1
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=sub_if_on_pg3.sw_if_index, bd_id=1)
+ rx_sw_if_index=sub_if_on_pg3.sw_if_index, bd_id=1
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.loop0.sw_if_index, bd_id=1,
- port_type=L2_PORT_TYPE.BVI)
+ rx_sw_if_index=self.loop0.sw_if_index, bd_id=1, port_type=L2_PORT_TYPE.BVI
+ )
self.vapi.l2_interface_vlan_tag_rewrite(
- sw_if_index=sub_if_on_pg2.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1,
- push_dot1q=92)
+ sw_if_index=sub_if_on_pg2.sw_if_index,
+ vtr_op=L2_VTR_OP.L2_POP_1,
+ push_dot1q=92,
+ )
self.vapi.l2_interface_vlan_tag_rewrite(
- sw_if_index=sub_if_on_pg3.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1,
- push_dot1q=93)
+ sw_if_index=sub_if_on_pg3.sw_if_index,
+ vtr_op=L2_VTR_OP.L2_POP_1,
+ push_dot1q=93,
+ )
#
# Add routes to bridge the traffic via a tagged an nontagged interface
#
route_no_tag = VppIpRoute(
- self, ip_non_tag_bridged, 32,
- [VppRoutePath("0.0.0.0",
- self.pg1.sw_if_index,
- type=FibPathType.FIB_PATH_TYPE_DVR)])
+ self,
+ ip_non_tag_bridged,
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0", self.pg1.sw_if_index, type=FibPathType.FIB_PATH_TYPE_DVR
+ )
+ ],
+ )
route_no_tag.add_vpp_config()
#
@@ -137,10 +150,17 @@ class TestDVR(VppTestCase):
# Add routes to bridge the traffic via a tagged interface
#
route_with_tag = VppIpRoute(
- self, ip_tag_bridged, 32,
- [VppRoutePath("0.0.0.0",
- sub_if_on_pg3.sw_if_index,
- type=FibPathType.FIB_PATH_TYPE_DVR)])
+ self,
+ ip_tag_bridged,
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ sub_if_on_pg3.sw_if_index,
+ type=FibPathType.FIB_PATH_TYPE_DVR,
+ )
+ ],
+ )
route_with_tag.add_vpp_config()
#
@@ -154,58 +174,58 @@ class TestDVR(VppTestCase):
#
# Tag to tag
#
- pkt_tag_to_tag = (Ether(src=self.pg2.remote_mac,
- dst=self.loop0.local_mac) /
- Dot1Q(vlan=92) /
- IP(src=any_src_addr,
- dst=ip_tag_bridged) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
-
- rx = self.send_and_expect(self.pg2,
- pkt_tag_to_tag * NUM_PKTS,
- self.pg3)
+ pkt_tag_to_tag = (
+ Ether(src=self.pg2.remote_mac, dst=self.loop0.local_mac)
+ / Dot1Q(vlan=92)
+ / IP(src=any_src_addr, dst=ip_tag_bridged)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+
+ rx = self.send_and_expect(self.pg2, pkt_tag_to_tag * NUM_PKTS, self.pg3)
self.assert_same_mac_addr(pkt_tag_to_tag, rx)
self.assert_has_vlan_tag(93, rx)
#
# Tag to non-Tag
#
- pkt_tag_to_non_tag = (Ether(src=self.pg2.remote_mac,
- dst=self.loop0.local_mac) /
- Dot1Q(vlan=92) /
- IP(src=any_src_addr,
- dst=ip_non_tag_bridged) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
-
- rx = self.send_and_expect(self.pg2,
- pkt_tag_to_non_tag * NUM_PKTS,
- self.pg1)
+ pkt_tag_to_non_tag = (
+ Ether(src=self.pg2.remote_mac, dst=self.loop0.local_mac)
+ / Dot1Q(vlan=92)
+ / IP(src=any_src_addr, dst=ip_non_tag_bridged)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+
+ rx = self.send_and_expect(self.pg2, pkt_tag_to_non_tag * NUM_PKTS, self.pg1)
self.assert_same_mac_addr(pkt_tag_to_tag, rx)
self.assert_has_no_tag(rx)
#
# Add an output L3 ACL that will block the traffic
#
- rule_1 = AclRule(is_permit=0, proto=17, ports=1234,
- src_prefix=IPv4Network((any_src_addr, 32)),
- dst_prefix=IPv4Network((ip_non_tag_bridged, 32)))
+ rule_1 = AclRule(
+ is_permit=0,
+ proto=17,
+ ports=1234,
+ src_prefix=IPv4Network((any_src_addr, 32)),
+ dst_prefix=IPv4Network((ip_non_tag_bridged, 32)),
+ )
acl = VppAcl(self, rules=[rule_1])
acl.add_vpp_config()
#
# Apply the ACL on the output interface
#
- acl_if1 = VppAclInterface(self, sw_if_index=self.pg1.sw_if_index,
- n_input=0, acls=[acl])
+ acl_if1 = VppAclInterface(
+ self, sw_if_index=self.pg1.sw_if_index, n_input=0, acls=[acl]
+ )
acl_if1.add_vpp_config()
#
# Send packet's that should match the ACL and be dropped
#
- rx = self.send_and_assert_no_replies(self.pg2,
- pkt_tag_to_non_tag * NUM_PKTS)
+ rx = self.send_and_assert_no_replies(self.pg2, pkt_tag_to_non_tag * NUM_PKTS)
#
# cleanup
@@ -214,16 +234,23 @@ class TestDVR(VppTestCase):
acl.remove_vpp_config()
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg0.sw_if_index, bd_id=1, enable=0)
+ rx_sw_if_index=self.pg0.sw_if_index, bd_id=1, enable=0
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg1.sw_if_index, bd_id=1, enable=0)
+ rx_sw_if_index=self.pg1.sw_if_index, bd_id=1, enable=0
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=sub_if_on_pg2.sw_if_index, bd_id=1, enable=0)
+ rx_sw_if_index=sub_if_on_pg2.sw_if_index, bd_id=1, enable=0
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=sub_if_on_pg3.sw_if_index, bd_id=1, enable=0)
+ rx_sw_if_index=sub_if_on_pg3.sw_if_index, bd_id=1, enable=0
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.loop0.sw_if_index, bd_id=1,
- port_type=L2_PORT_TYPE.BVI, enable=0)
+ rx_sw_if_index=self.loop0.sw_if_index,
+ bd_id=1,
+ port_type=L2_PORT_TYPE.BVI,
+ enable=0,
+ )
#
# Do a FIB dump to make sure the paths are correctly reported as DVR
@@ -231,16 +258,14 @@ class TestDVR(VppTestCase):
routes = self.vapi.ip_route_dump(0)
for r in routes:
- if (ip_tag_bridged == str(r.route.prefix.network_address)):
- self.assertEqual(r.route.paths[0].sw_if_index,
- sub_if_on_pg3.sw_if_index)
- self.assertEqual(r.route.paths[0].type,
- FibPathType.FIB_PATH_TYPE_DVR)
- if (ip_non_tag_bridged == str(r.route.prefix.network_address)):
- self.assertEqual(r.route.paths[0].sw_if_index,
- self.pg1.sw_if_index)
- self.assertEqual(r.route.paths[0].type,
- FibPathType.FIB_PATH_TYPE_DVR)
+ if ip_tag_bridged == str(r.route.prefix.network_address):
+ self.assertEqual(
+ r.route.paths[0].sw_if_index, sub_if_on_pg3.sw_if_index
+ )
+ self.assertEqual(r.route.paths[0].type, FibPathType.FIB_PATH_TYPE_DVR)
+ if ip_non_tag_bridged == str(r.route.prefix.network_address):
+ self.assertEqual(r.route.paths[0].sw_if_index, self.pg1.sw_if_index)
+ self.assertEqual(r.route.paths[0].type, FibPathType.FIB_PATH_TYPE_DVR)
#
# the explicit route delete is require so it happens before
@@ -253,5 +278,5 @@ class TestDVR(VppTestCase):
sub_if_on_pg2.remove_vpp_config()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_endian.py b/test/test_endian.py
index 462ee2b6b57..bb54a03fd13 100644
--- a/test/test_endian.py
+++ b/test/test_endian.py
@@ -24,15 +24,20 @@ class TestEndian(framework.VppTestCase):
def test_f64_endian_value(self):
try:
rv = self.vapi.get_f64_endian_value(f64_one=F64_ONE)
- self.assertEqual(rv.f64_one_result, F64_ONE,
- "client incorrectly deserializes f64 values. "
- "Expected: %r. Received: %r." % (
- F64_ONE, rv.f64_one_result))
+ self.assertEqual(
+ rv.f64_one_result,
+ F64_ONE,
+ "client incorrectly deserializes f64 values. "
+ "Expected: %r. Received: %r." % (F64_ONE, rv.f64_one_result),
+ )
except vpp_papi_provider.UnexpectedApiReturnValueError:
- self.fail('client incorrectly serializes f64 values.')
+ self.fail("client incorrectly serializes f64 values.")
def test_get_f64_increment_by_one(self):
expected = 43.0
rv = self.vapi.get_f64_increment_by_one(f64_value=42.0)
- self.assertEqual(rv.f64_value, expected, 'Expected %r, received:%r.'
- % (expected, rv.f64_value))
+ self.assertEqual(
+ rv.f64_value,
+ expected,
+ "Expected %r, received:%r." % (expected, rv.f64_value),
+ )
diff --git a/test/test_fib.py b/test/test_fib.py
index 7c08722d803..136918e1232 100644
--- a/test/test_fib.py
+++ b/test/test_fib.py
@@ -8,7 +8,7 @@ from framework import VppTestCase, VppTestRunner
@tag_fixme_vpp_workers
class TestFIB(VppTestCase):
- """ FIB Test Case """
+ """FIB Test Case"""
@classmethod
def setUpClass(cls):
@@ -19,7 +19,7 @@ class TestFIB(VppTestCase):
super(TestFIB, cls).tearDownClass()
def test_fib(self):
- """ FIB Unit Tests """
+ """FIB Unit Tests"""
error = self.vapi.cli("test fib")
# shameless test of CLIs to bump lcov results...
@@ -44,5 +44,6 @@ class TestFIB(VppTestCase):
self.logger.critical(error)
self.assertNotIn("Failed", error)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_flowprobe.py b/test/test_flowprobe.py
index 5bafd39eceb..6b271790f76 100644
--- a/test/test_flowprobe.py
+++ b/test/test_flowprobe.py
@@ -29,17 +29,26 @@ from vpp_papi import VppEnum
class VppCFLOW(VppObject):
"""CFLOW object for IPFIX exporter and Flowprobe feature"""
- def __init__(self, test, intf='pg2', active=0, passive=0, timeout=100,
- mtu=1024, datapath='l2', layer='l2 l3 l4'):
+ def __init__(
+ self,
+ test,
+ intf="pg2",
+ active=0,
+ passive=0,
+ timeout=100,
+ mtu=1024,
+ datapath="l2",
+ layer="l2 l3 l4",
+ ):
self._test = test
self._intf = intf
self._active = active
if passive == 0 or passive < active:
- self._passive = active+1
+ self._passive = active + 1
else:
self._passive = passive
- self._datapath = datapath # l2 ip4 ip6
- self._collect = layer # l2 l3 l4
+ self._datapath = datapath # l2 ip4 ip6
+ self._collect = layer # l2 l3 l4
self._timeout = timeout
self._mtu = mtu
self._configured = False
@@ -49,18 +58,17 @@ class VppCFLOW(VppObject):
l2_flag = 0
l3_flag = 0
l4_flag = 0
- if 'l2' in self._collect.lower():
- l2_flag = (VppEnum.vl_api_flowprobe_record_flags_t.
- FLOWPROBE_RECORD_FLAG_L2)
- if 'l3' in self._collect.lower():
- l3_flag = (VppEnum.vl_api_flowprobe_record_flags_t.
- FLOWPROBE_RECORD_FLAG_L3)
- if 'l4' in self._collect.lower():
- l4_flag = (VppEnum.vl_api_flowprobe_record_flags_t.
- FLOWPROBE_RECORD_FLAG_L4)
+ if "l2" in self._collect.lower():
+ l2_flag = VppEnum.vl_api_flowprobe_record_flags_t.FLOWPROBE_RECORD_FLAG_L2
+ if "l3" in self._collect.lower():
+ l3_flag = VppEnum.vl_api_flowprobe_record_flags_t.FLOWPROBE_RECORD_FLAG_L3
+ if "l4" in self._collect.lower():
+ l4_flag = VppEnum.vl_api_flowprobe_record_flags_t.FLOWPROBE_RECORD_FLAG_L4
self._test.vapi.flowprobe_params(
record_flags=(l2_flag | l3_flag | l4_flag),
- active_timer=self._active, passive_timer=self._passive)
+ active_timer=self._active,
+ passive_timer=self._passive,
+ )
self.enable_flowprobe_feature()
self._test.vapi.cli("ipfix flush")
self._configured = True
@@ -76,18 +84,21 @@ class VppCFLOW(VppObject):
collector_address=self._test.pg0.remote_ip4,
src_address=self._test.pg0.local_ip4,
path_mtu=self._mtu,
- template_interval=self._timeout)
+ template_interval=self._timeout,
+ )
def enable_flowprobe_feature(self):
- self._test.vapi.ppcli("flowprobe feature add-del %s %s" %
- (self._intf, self._datapath))
+ self._test.vapi.ppcli(
+ "flowprobe feature add-del %s %s" % (self._intf, self._datapath)
+ )
def disable_exporter(self):
self._test.vapi.cli("set ipfix exporter collector 0.0.0.0")
def disable_flowprobe_feature(self):
- self._test.vapi.cli("flowprobe feature add-del %s %s disable" %
- (self._intf, self._datapath))
+ self._test.vapi.cli(
+ "flowprobe feature add-del %s %s disable" % (self._intf, self._datapath)
+ )
def object_id(self):
return "ipfix-collector-%s-%s" % (self._src, self.dst)
@@ -99,8 +110,7 @@ class VppCFLOW(VppObject):
templates = []
self._test.assertIn(count, (1, 2, 3))
for _ in range(count):
- p = self._test.wait_for_cflow_packet(self._test.collector, 2,
- timeout)
+ p = self._test.wait_for_cflow_packet(self._test.collector, 2, timeout)
self._test.assertTrue(p.haslayer(IPFIX))
if decoder is not None and p.haslayer(Template):
templates.append(p[Template].templateID)
@@ -109,7 +119,7 @@ class VppCFLOW(VppObject):
class MethodHolder(VppTestCase):
- """ Flow-per-packet plugin: test L2, IP4, IP6 reporting """
+ """Flow-per-packet plugin: test L2, IP4, IP6 reporting"""
# Test variables
debug_print = False
@@ -135,9 +145,11 @@ class MethodHolder(VppTestCase):
# and put interfaces to this BD
cls.vapi.bridge_domain_add_del(bd_id=1, uu_flood=1, learn=1)
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg1._sw_if_index, bd_id=1)
+ rx_sw_if_index=cls.pg1._sw_if_index, bd_id=1
+ )
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg2._sw_if_index, bd_id=1)
+ rx_sw_if_index=cls.pg2._sw_if_index, bd_id=1
+ )
# Set up all interfaces
for i in cls.pg_interfaces:
@@ -173,8 +185,9 @@ class MethodHolder(VppTestCase):
def tearDownClass(cls):
super(MethodHolder, cls).tearDownClass()
- def create_stream(self, src_if=None, dst_if=None, packets=None,
- size=None, ip_ver='v4'):
+ def create_stream(
+ self, src_if=None, dst_if=None, packets=None, size=None, ip_ver="v4"
+ ):
"""Create a packet stream to tickle the plugin
:param VppInterface src_if: Source interface for packet stream
@@ -194,7 +207,7 @@ class MethodHolder(VppTestCase):
info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(info)
p = Ether(src=src_if.remote_mac, dst=src_if.local_mac)
- if ip_ver == 'v4':
+ if ip_ver == "v4":
p /= IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4)
else:
p /= IPv6(src=src_if.remote_ip6, dst=dst_if.remote_ip6)
@@ -226,16 +239,16 @@ class MethodHolder(VppTestCase):
self.pg_start()
return dst_if.get_capture(len(self.pkts))
- def verify_cflow_data_detail(self, decoder, capture, cflow,
- data_set={1: 'octets', 2: 'packets'},
- ip_ver='v4'):
+ def verify_cflow_data_detail(
+ self, decoder, capture, cflow, data_set={1: "octets", 2: "packets"}, ip_ver="v4"
+ ):
if self.debug_print:
print(capture[0].show())
if cflow.haslayer(Data):
data = decoder.decode_data_set(cflow.getlayer(Set))
if self.debug_print:
print(data)
- if ip_ver == 'v4':
+ if ip_ver == "v4":
ip_layer = capture[0][IP]
else:
ip_layer = capture[0][IPv6]
@@ -251,35 +264,31 @@ class MethodHolder(VppTestCase):
if field not in record.keys():
continue
value = data_set[field]
- if value == 'octets':
+ if value == "octets":
value = ip_layer.len
- if ip_ver == 'v6':
- value += 40 # ??? is this correct
- elif value == 'packets':
+ if ip_ver == "v6":
+ value += 40 # ??? is this correct
+ elif value == "packets":
value = 1
- elif value == 'src_ip':
- if ip_ver == 'v4':
- ip = socket.inet_pton(socket.AF_INET,
- ip_layer.src)
+ elif value == "src_ip":
+ if ip_ver == "v4":
+ ip = socket.inet_pton(socket.AF_INET, ip_layer.src)
else:
- ip = socket.inet_pton(socket.AF_INET6,
- ip_layer.src)
+ ip = socket.inet_pton(socket.AF_INET6, ip_layer.src)
value = int(binascii.hexlify(ip), 16)
- elif value == 'dst_ip':
- if ip_ver == 'v4':
- ip = socket.inet_pton(socket.AF_INET,
- ip_layer.dst)
+ elif value == "dst_ip":
+ if ip_ver == "v4":
+ ip = socket.inet_pton(socket.AF_INET, ip_layer.dst)
else:
- ip = socket.inet_pton(socket.AF_INET6,
- ip_layer.dst)
+ ip = socket.inet_pton(socket.AF_INET6, ip_layer.dst)
value = int(binascii.hexlify(ip), 16)
- elif value == 'sport':
+ elif value == "sport":
value = int(capture[0][UDP].sport)
- elif value == 'dport':
+ elif value == "dport":
value = int(capture[0][UDP].dport)
- self.assertEqual(int(binascii.hexlify(
- record[field]), 16),
- value)
+ self.assertEqual(
+ int(binascii.hexlify(record[field]), 16), value
+ )
def verify_cflow_data_notimer(self, decoder, capture, cflows):
idx = 0
@@ -292,14 +301,12 @@ class MethodHolder(VppTestCase):
for rec in data:
p = capture[idx]
idx += 1
- self.assertEqual(p[IP].len, int(
- binascii.hexlify(rec[1]), 16))
- self.assertEqual(1, int(
- binascii.hexlify(rec[2]), 16))
+ self.assertEqual(p[IP].len, int(binascii.hexlify(rec[1]), 16))
+ self.assertEqual(1, int(binascii.hexlify(rec[2]), 16))
self.assertEqual(len(capture), idx)
def wait_for_cflow_packet(self, collector_intf, set_id=2, timeout=1):
- """ wait for CFLOW packet and verify its correctness
+ """wait for CFLOW packet and verify its correctness
:param timeout: how long to wait
@@ -327,7 +334,7 @@ class Flowprobe(MethodHolder):
super(Flowprobe, cls).tearDownClass()
def test_0001(self):
- """ timer less than template timeout"""
+ """timer less than template timeout"""
self.logger.info("FFP_TEST_START_0001")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
@@ -351,7 +358,7 @@ class Flowprobe(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0001")
def test_0002(self):
- """ timer greater than template timeout"""
+ """timer greater than template timeout"""
self.logger.info("FFP_TEST_START_0002")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
@@ -384,26 +391,33 @@ class Flowprobe(MethodHolder):
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
- ipfix = VppCFLOW(test=self, intf='pg8', datapath="ip4",
- layer='l2 l3 l4', active=2)
+ ipfix = VppCFLOW(
+ test=self, intf="pg8", datapath="ip4", layer="l2 l3 l4", active=2
+ )
ipfix.add_vpp_config()
- route_9001 = VppIpRoute(self, "9.0.0.0", 24,
- [VppRoutePath(self.pg8._remote_hosts[0].ip4,
- self.pg8.sw_if_index)])
+ route_9001 = VppIpRoute(
+ self,
+ "9.0.0.0",
+ 24,
+ [VppRoutePath(self.pg8._remote_hosts[0].ip4, self.pg8.sw_if_index)],
+ )
route_9001.add_vpp_config()
ipfix_decoder = IPFIXDecoder()
templates = ipfix.verify_templates(ipfix_decoder, count=1)
- self.pkts = [(Ether(dst=self.pg7.local_mac,
- src=self.pg7.remote_mac) /
- IP(src=self.pg7.remote_ip4, dst="9.0.0.100") /
- TCP(sport=1234, dport=4321, flags=80) /
- Raw(b'\xa5' * 100))]
+ self.pkts = [
+ (
+ Ether(dst=self.pg7.local_mac, src=self.pg7.remote_mac)
+ / IP(src=self.pg7.remote_ip4, dst="9.0.0.100")
+ / TCP(sport=1234, dport=4321, flags=80)
+ / Raw(b"\xa5" * 100)
+ )
+ ]
nowUTC = int(time.time())
- nowUNIX = nowUTC+2208988800
+ nowUNIX = nowUTC + 2208988800
self.send_packets(src_if=self.pg7, dst_if=self.pg8)
cflow = self.wait_for_cflow_packet(self.collector, templates[0], 10)
@@ -435,11 +449,9 @@ class Flowprobe(MethodHolder):
# ethernet type
self.assertEqual(int(binascii.hexlify(record[256]), 16), 8)
# src ip
- self.assertEqual(inet_ntop(socket.AF_INET, record[8]),
- self.pg7.remote_ip4)
+ self.assertEqual(inet_ntop(socket.AF_INET, record[8]), self.pg7.remote_ip4)
# dst ip
- self.assertEqual(inet_ntop(socket.AF_INET, record[12]),
- "9.0.0.100")
+ self.assertEqual(inet_ntop(socket.AF_INET, record[12]), "9.0.0.100")
# protocol (TCP)
self.assertEqual(int(binascii.hexlify(record[4]), 16), 6)
# src port
@@ -466,11 +478,11 @@ class Datapath(MethodHolder):
super(Datapath, cls).tearDownClass()
def test_templatesL2(self):
- """ verify template on L2 datapath"""
+ """verify template on L2 datapath"""
self.logger.info("FFP_TEST_START_0000")
self.pg_enable_capture(self.pg_interfaces)
- ipfix = VppCFLOW(test=self, layer='l2')
+ ipfix = VppCFLOW(test=self, layer="l2")
ipfix.add_vpp_config()
# template packet should arrive immediately
@@ -482,12 +494,12 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0000")
def test_L2onL2(self):
- """ L2 data on L2 datapath"""
+ """L2 data on L2 datapath"""
self.logger.info("FFP_TEST_START_0001")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
- ipfix = VppCFLOW(test=self, layer='l2')
+ ipfix = VppCFLOW(test=self, layer="l2")
ipfix.add_vpp_config()
ipfix_decoder = IPFIXDecoder()
@@ -500,20 +512,21 @@ class Datapath(MethodHolder):
# make sure the one packet we expect actually showed up
self.vapi.ipfix_flush()
cflow = self.wait_for_cflow_packet(self.collector, templates[0])
- self.verify_cflow_data_detail(ipfix_decoder, capture, cflow,
- {2: 'packets', 256: 8})
+ self.verify_cflow_data_detail(
+ ipfix_decoder, capture, cflow, {2: "packets", 256: 8}
+ )
self.collector.get_capture(2)
ipfix.remove_vpp_config()
self.logger.info("FFP_TEST_FINISH_0001")
def test_L3onL2(self):
- """ L3 data on L2 datapath"""
+ """L3 data on L2 datapath"""
self.logger.info("FFP_TEST_START_0002")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
- ipfix = VppCFLOW(test=self, layer='l3')
+ ipfix = VppCFLOW(test=self, layer="l3")
ipfix.add_vpp_config()
ipfix_decoder = IPFIXDecoder()
@@ -526,9 +539,12 @@ class Datapath(MethodHolder):
# make sure the one packet we expect actually showed up
self.vapi.ipfix_flush()
cflow = self.wait_for_cflow_packet(self.collector, templates[0])
- self.verify_cflow_data_detail(ipfix_decoder, capture, cflow,
- {2: 'packets', 4: 17,
- 8: 'src_ip', 12: 'dst_ip'})
+ self.verify_cflow_data_detail(
+ ipfix_decoder,
+ capture,
+ cflow,
+ {2: "packets", 4: 17, 8: "src_ip", 12: "dst_ip"},
+ )
self.collector.get_capture(3)
@@ -536,12 +552,12 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0002")
def test_L4onL2(self):
- """ L4 data on L2 datapath"""
+ """L4 data on L2 datapath"""
self.logger.info("FFP_TEST_START_0003")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
- ipfix = VppCFLOW(test=self, layer='l4')
+ ipfix = VppCFLOW(test=self, layer="l4")
ipfix.add_vpp_config()
ipfix_decoder = IPFIXDecoder()
@@ -554,8 +570,9 @@ class Datapath(MethodHolder):
# make sure the one packet we expect actually showed up
self.vapi.ipfix_flush()
cflow = self.wait_for_cflow_packet(self.collector, templates[0])
- self.verify_cflow_data_detail(ipfix_decoder, capture, cflow,
- {2: 'packets', 7: 'sport', 11: 'dport'})
+ self.verify_cflow_data_detail(
+ ipfix_decoder, capture, cflow, {2: "packets", 7: "sport", 11: "dport"}
+ )
self.collector.get_capture(3)
@@ -563,12 +580,12 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0003")
def test_templatesIp4(self):
- """ verify templates on IP4 datapath"""
+ """verify templates on IP4 datapath"""
self.logger.info("FFP_TEST_START_0000")
self.pg_enable_capture(self.pg_interfaces)
- ipfix = VppCFLOW(test=self, datapath='ip4')
+ ipfix = VppCFLOW(test=self, datapath="ip4")
ipfix.add_vpp_config()
# template packet should arrive immediately
@@ -581,12 +598,12 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0000")
def test_L2onIP4(self):
- """ L2 data on IP4 datapath"""
+ """L2 data on IP4 datapath"""
self.logger.info("FFP_TEST_START_0001")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
- ipfix = VppCFLOW(test=self, intf='pg4', layer='l2', datapath='ip4')
+ ipfix = VppCFLOW(test=self, intf="pg4", layer="l2", datapath="ip4")
ipfix.add_vpp_config()
ipfix_decoder = IPFIXDecoder()
@@ -599,8 +616,9 @@ class Datapath(MethodHolder):
# make sure the one packet we expect actually showed up
self.vapi.ipfix_flush()
cflow = self.wait_for_cflow_packet(self.collector, templates[0])
- self.verify_cflow_data_detail(ipfix_decoder, capture, cflow,
- {2: 'packets', 256: 8})
+ self.verify_cflow_data_detail(
+ ipfix_decoder, capture, cflow, {2: "packets", 256: 8}
+ )
# expected two templates and one cflow packet
self.collector.get_capture(2)
@@ -609,12 +627,12 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0001")
def test_L3onIP4(self):
- """ L3 data on IP4 datapath"""
+ """L3 data on IP4 datapath"""
self.logger.info("FFP_TEST_START_0002")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
- ipfix = VppCFLOW(test=self, intf='pg4', layer='l3', datapath='ip4')
+ ipfix = VppCFLOW(test=self, intf="pg4", layer="l3", datapath="ip4")
ipfix.add_vpp_config()
ipfix_decoder = IPFIXDecoder()
@@ -627,9 +645,12 @@ class Datapath(MethodHolder):
# make sure the one packet we expect actually showed up
self.vapi.ipfix_flush()
cflow = self.wait_for_cflow_packet(self.collector, templates[0])
- self.verify_cflow_data_detail(ipfix_decoder, capture, cflow,
- {1: 'octets', 2: 'packets',
- 8: 'src_ip', 12: 'dst_ip'})
+ self.verify_cflow_data_detail(
+ ipfix_decoder,
+ capture,
+ cflow,
+ {1: "octets", 2: "packets", 8: "src_ip", 12: "dst_ip"},
+ )
# expected two templates and one cflow packet
self.collector.get_capture(2)
@@ -638,12 +659,12 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0002")
def test_L4onIP4(self):
- """ L4 data on IP4 datapath"""
+ """L4 data on IP4 datapath"""
self.logger.info("FFP_TEST_START_0003")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
- ipfix = VppCFLOW(test=self, intf='pg4', layer='l4', datapath='ip4')
+ ipfix = VppCFLOW(test=self, intf="pg4", layer="l4", datapath="ip4")
ipfix.add_vpp_config()
ipfix_decoder = IPFIXDecoder()
@@ -656,8 +677,9 @@ class Datapath(MethodHolder):
# make sure the one packet we expect actually showed up
self.vapi.ipfix_flush()
cflow = self.wait_for_cflow_packet(self.collector, templates[0])
- self.verify_cflow_data_detail(ipfix_decoder, capture, cflow,
- {2: 'packets', 7: 'sport', 11: 'dport'})
+ self.verify_cflow_data_detail(
+ ipfix_decoder, capture, cflow, {2: "packets", 7: "sport", 11: "dport"}
+ )
# expected two templates and one cflow packet
self.collector.get_capture(2)
@@ -666,11 +688,11 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0003")
def test_templatesIP6(self):
- """ verify templates on IP6 datapath"""
+ """verify templates on IP6 datapath"""
self.logger.info("FFP_TEST_START_0000")
self.pg_enable_capture(self.pg_interfaces)
- ipfix = VppCFLOW(test=self, datapath='ip6')
+ ipfix = VppCFLOW(test=self, datapath="ip6")
ipfix.add_vpp_config()
# template packet should arrive immediately
@@ -682,28 +704,27 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0000")
def test_L2onIP6(self):
- """ L2 data on IP6 datapath"""
+ """L2 data on IP6 datapath"""
self.logger.info("FFP_TEST_START_0001")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
- ipfix = VppCFLOW(test=self, intf='pg6', layer='l2', datapath='ip6')
+ ipfix = VppCFLOW(test=self, intf="pg6", layer="l2", datapath="ip6")
ipfix.add_vpp_config()
ipfix_decoder = IPFIXDecoder()
# template packet should arrive immediately
templates = ipfix.verify_templates(ipfix_decoder, count=1)
- self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1,
- ip_ver='IPv6')
+ self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1, ip_ver="IPv6")
capture = self.send_packets(src_if=self.pg5, dst_if=self.pg6)
# make sure the one packet we expect actually showed up
self.vapi.ipfix_flush()
cflow = self.wait_for_cflow_packet(self.collector, templates[0])
- self.verify_cflow_data_detail(ipfix_decoder, capture, cflow,
- {2: 'packets', 256: 56710},
- ip_ver='v6')
+ self.verify_cflow_data_detail(
+ ipfix_decoder, capture, cflow, {2: "packets", 256: 56710}, ip_ver="v6"
+ )
# expected two templates and one cflow packet
self.collector.get_capture(2)
@@ -712,29 +733,31 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0001")
def test_L3onIP6(self):
- """ L3 data on IP6 datapath"""
+ """L3 data on IP6 datapath"""
self.logger.info("FFP_TEST_START_0002")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
- ipfix = VppCFLOW(test=self, intf='pg6', layer='l3', datapath='ip6')
+ ipfix = VppCFLOW(test=self, intf="pg6", layer="l3", datapath="ip6")
ipfix.add_vpp_config()
ipfix_decoder = IPFIXDecoder()
# template packet should arrive immediately
templates = ipfix.verify_templates(ipfix_decoder, count=1)
- self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1,
- ip_ver='IPv6')
+ self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1, ip_ver="IPv6")
capture = self.send_packets(src_if=self.pg5, dst_if=self.pg6)
# make sure the one packet we expect actually showed up
self.vapi.ipfix_flush()
cflow = self.wait_for_cflow_packet(self.collector, templates[0])
- self.verify_cflow_data_detail(ipfix_decoder, capture, cflow,
- {2: 'packets',
- 27: 'src_ip', 28: 'dst_ip'},
- ip_ver='v6')
+ self.verify_cflow_data_detail(
+ ipfix_decoder,
+ capture,
+ cflow,
+ {2: "packets", 27: "src_ip", 28: "dst_ip"},
+ ip_ver="v6",
+ )
# expected two templates and one cflow packet
self.collector.get_capture(2)
@@ -743,28 +766,31 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0002")
def test_L4onIP6(self):
- """ L4 data on IP6 datapath"""
+ """L4 data on IP6 datapath"""
self.logger.info("FFP_TEST_START_0003")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
- ipfix = VppCFLOW(test=self, intf='pg6', layer='l4', datapath='ip6')
+ ipfix = VppCFLOW(test=self, intf="pg6", layer="l4", datapath="ip6")
ipfix.add_vpp_config()
ipfix_decoder = IPFIXDecoder()
# template packet should arrive immediately
templates = ipfix.verify_templates(ipfix_decoder, count=1)
- self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1,
- ip_ver='IPv6')
+ self.create_stream(src_if=self.pg5, dst_if=self.pg6, packets=1, ip_ver="IPv6")
capture = self.send_packets(src_if=self.pg5, dst_if=self.pg6)
# make sure the one packet we expect actually showed up
self.vapi.ipfix_flush()
cflow = self.wait_for_cflow_packet(self.collector, templates[0])
- self.verify_cflow_data_detail(ipfix_decoder, capture, cflow,
- {2: 'packets', 7: 'sport', 11: 'dport'},
- ip_ver='v6')
+ self.verify_cflow_data_detail(
+ ipfix_decoder,
+ capture,
+ cflow,
+ {2: "packets", 7: "sport", 11: "dport"},
+ ip_ver="v6",
+ )
# expected two templates and one cflow packet
self.collector.get_capture(2)
@@ -773,7 +799,7 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0003")
def test_0001(self):
- """ no timers, one CFLOW packet, 9 Flows inside"""
+ """no timers, one CFLOW packet, 9 Flows inside"""
self.logger.info("FFP_TEST_START_0001")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
@@ -798,7 +824,7 @@ class Datapath(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0001")
def test_0002(self):
- """ no timers, two CFLOW packets (mtu=256), 3 Flows in each"""
+ """no timers, two CFLOW packets (mtu=256), 3 Flows in each"""
self.logger.info("FFP_TEST_START_0002")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
@@ -817,10 +843,8 @@ class Datapath(MethodHolder):
# make sure the one packet we expect actually showed up
cflows = []
self.vapi.ipfix_flush()
- cflows.append(self.wait_for_cflow_packet(self.collector,
- templates[1]))
- cflows.append(self.wait_for_cflow_packet(self.collector,
- templates[1]))
+ cflows.append(self.wait_for_cflow_packet(self.collector, templates[1]))
+ cflows.append(self.wait_for_cflow_packet(self.collector, templates[1]))
self.verify_cflow_data_notimer(ipfix_decoder, capture, cflows)
self.collector.get_capture(5)
@@ -841,7 +865,7 @@ class DisableIPFIX(MethodHolder):
super(DisableIPFIX, cls).tearDownClass()
def test_0001(self):
- """ disable IPFIX after first packets"""
+ """disable IPFIX after first packets"""
self.logger.info("FFP_TEST_START_0001")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
@@ -889,8 +913,7 @@ class ReenableIPFIX(MethodHolder):
super(ReenableIPFIX, cls).tearDownClass()
def test_0011(self):
- """ disable IPFIX after first packets and re-enable after few packets
- """
+ """disable IPFIX after first packets and re-enable after few packets"""
self.logger.info("FFP_TEST_START_0001")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
@@ -957,7 +980,7 @@ class DisableFP(MethodHolder):
super(DisableFP, cls).tearDownClass()
def test_0001(self):
- """ disable flowprobe feature after first packets"""
+ """disable flowprobe feature after first packets"""
self.logger.info("FFP_TEST_START_0001")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
@@ -1004,8 +1027,8 @@ class ReenableFP(MethodHolder):
super(ReenableFP, cls).tearDownClass()
def test_0001(self):
- """ disable flowprobe feature after first packets and re-enable
- after few packets """
+ """disable flowprobe feature after first packets and re-enable
+ after few packets"""
self.logger.info("FFP_TEST_START_0001")
self.pg_enable_capture(self.pg_interfaces)
self.pkts = []
@@ -1054,5 +1077,5 @@ class ReenableFP(MethodHolder):
self.logger.info("FFP_TEST_FINISH_0001")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_geneve.py b/test/test_geneve.py
index 9ce1f8ff643..f6886c636d3 100644
--- a/test/test_geneve.py
+++ b/test/test_geneve.py
@@ -16,7 +16,7 @@ from vpp_ip import INVALID_INDEX
class TestGeneve(BridgeDomain, VppTestCase):
- """ GENEVE Test Case """
+ """GENEVE Test Case"""
def __init__(self, *args):
BridgeDomain.__init__(self)
@@ -28,14 +28,16 @@ class TestGeneve(BridgeDomain, VppTestCase):
Encapsulate the original payload frame by adding GENEVE header with its
UDP, IP and Ethernet fields
"""
- return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=self.dport, dport=self.dport, chksum=0) /
- GENEVE(vni=vni) /
- pkt)
+ return (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ / GENEVE(vni=vni)
+ / pkt
+ )
def ip_range(self, start, end):
- """ range of remote ip's """
+ """range of remote ip's"""
return ip4_range(self.pg0.remote_ip4, start, end)
def encap_mcast(self, pkt, src_ip, src_mac, vni):
@@ -43,11 +45,13 @@ class TestGeneve(BridgeDomain, VppTestCase):
Encapsulate the original payload frame by adding GENEVE header with its
UDP, IP and Ethernet fields
"""
- return (Ether(src=src_mac, dst=self.mcast_mac) /
- IP(src=src_ip, dst=self.mcast_ip4) /
- UDP(sport=self.dport, dport=self.dport, chksum=0) /
- GENEVE(vni=vni) /
- pkt)
+ return (
+ Ether(src=src_mac, dst=self.mcast_mac)
+ / IP(src=src_ip, dst=self.mcast_ip4)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ / GENEVE(vni=vni)
+ / pkt
+ )
def decapsulate(self, pkt):
"""
@@ -89,19 +93,20 @@ class TestGeneve(BridgeDomain, VppTestCase):
ip_range_start = 10
ip_range_end = ip_range_start + n_ucast_tunnels
next_hop_address = cls.pg0.remote_ip4
- for dest_ip4 in ip4_range(next_hop_address, ip_range_start,
- ip_range_end):
+ for dest_ip4 in ip4_range(next_hop_address, ip_range_start, ip_range_end):
# add host route so dest_ip4 will not be resolved
- rip = VppIpRoute(cls, dest_ip4, 32,
- [VppRoutePath(next_hop_address,
- INVALID_INDEX)],
- register=False)
+ rip = VppIpRoute(
+ cls,
+ dest_ip4,
+ 32,
+ [VppRoutePath(next_hop_address, INVALID_INDEX)],
+ register=False,
+ )
rip.add_vpp_config()
r = cls.vapi.geneve_add_del_tunnel(
- local_address=cls.pg0.local_ip4, remote_address=dest_ip4,
- vni=vni)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=vni)
+ local_address=cls.pg0.local_ip4, remote_address=dest_ip4, vni=vni
+ )
+ cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, bd_id=vni)
@classmethod
def add_del_shared_mcast_dst_load(cls, is_add):
@@ -115,9 +120,12 @@ class TestGeneve(BridgeDomain, VppTestCase):
for vni in range(vni_start, vni_end):
r = cls.vapi.geneve_add_del_tunnel(
local_address=cls.pg0.local_ip4,
- remote_address=cls.mcast_ip4, mcast_sw_if_index=1,
- is_add=is_add, vni=vni)
- if r.sw_if_index == 0xffffffff:
+ remote_address=cls.mcast_ip4,
+ mcast_sw_if_index=1,
+ is_add=is_add,
+ vni=vni,
+ )
+ if r.sw_if_index == 0xFFFFFFFF:
raise ValueError("bad sw_if_index: ~0")
@classmethod
@@ -136,13 +144,15 @@ class TestGeneve(BridgeDomain, VppTestCase):
n_distinct_dst_tunnels = 10
ip_range_start = 10
ip_range_end = ip_range_start + n_distinct_dst_tunnels
- for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start,
- ip_range_end):
- vni = int(dest_ip4.split('.')[3])
- cls.vapi.geneve_add_del_tunnel(local_address=cls.pg0.local_ip4,
- remote_address=dest_ip4,
- mcast_sw_if_index=1, is_add=is_add,
- vni=vni)
+ for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, ip_range_end):
+ vni = int(dest_ip4.split(".")[3])
+ cls.vapi.geneve_add_del_tunnel(
+ local_address=cls.pg0.local_ip4,
+ remote_address=dest_ip4,
+ mcast_sw_if_index=1,
+ is_add=is_add,
+ vni=vni,
+ )
@classmethod
def add_mcast_tunnels_load(cls):
@@ -176,34 +186,41 @@ class TestGeneve(BridgeDomain, VppTestCase):
cls.pg0.resolve_arp()
# Our Multicast address
- cls.mcast_ip4 = '239.1.1.1'
+ cls.mcast_ip4 = "239.1.1.1"
cls.mcast_mac = util.mcast_ip_to_mac(cls.mcast_ip4)
# Create GENEVE VTEP on VPP pg0, and put geneve_tunnel0 and pg1
# into BD.
- cls.single_tunnel_vni = 0xabcde
+ cls.single_tunnel_vni = 0xABCDE
cls.single_tunnel_bd = 1
r = cls.vapi.geneve_add_del_tunnel(
local_address=cls.pg0.local_ip4,
- remote_address=cls.pg0.remote_ip4, vni=cls.single_tunnel_vni)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=cls.single_tunnel_bd)
+ remote_address=cls.pg0.remote_ip4,
+ vni=cls.single_tunnel_vni,
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=r.sw_if_index, bd_id=cls.single_tunnel_bd
+ )
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.single_tunnel_bd)
+ rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.single_tunnel_bd
+ )
# Setup vni 2 to test multicast flooding
cls.n_ucast_tunnels = 10
cls.mcast_flood_bd = 2
- cls.create_geneve_flood_test_bd(cls.mcast_flood_bd,
- cls.n_ucast_tunnels)
+ cls.create_geneve_flood_test_bd(cls.mcast_flood_bd, cls.n_ucast_tunnels)
r = cls.vapi.geneve_add_del_tunnel(
local_address=cls.pg0.local_ip4,
- remote_address=cls.mcast_ip4, mcast_sw_if_index=1,
- vni=cls.mcast_flood_bd)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=cls.mcast_flood_bd)
+ remote_address=cls.mcast_ip4,
+ mcast_sw_if_index=1,
+ vni=cls.mcast_flood_bd,
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=r.sw_if_index, bd_id=cls.mcast_flood_bd
+ )
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg2.sw_if_index, bd_id=cls.mcast_flood_bd)
+ rx_sw_if_index=cls.pg2.sw_if_index, bd_id=cls.mcast_flood_bd
+ )
# Add and delete mcast tunnels to check stability
cls.add_shared_mcast_dst_load()
@@ -213,10 +230,10 @@ class TestGeneve(BridgeDomain, VppTestCase):
# Setup vni 3 to test unicast flooding
cls.ucast_flood_bd = 3
- cls.create_geneve_flood_test_bd(cls.ucast_flood_bd,
- cls.n_ucast_tunnels)
+ cls.create_geneve_flood_test_bd(cls.ucast_flood_bd, cls.n_ucast_tunnels)
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg3.sw_if_index, bd_id=cls.ucast_flood_bd)
+ rx_sw_if_index=cls.pg3.sw_if_index, bd_id=cls.ucast_flood_bd
+ )
except Exception:
super(TestGeneve, cls).tearDownClass()
raise
@@ -235,7 +252,7 @@ class TestGeneve(BridgeDomain, VppTestCase):
class TestGeneveL3(VppTestCase):
- """ GENEVE L3 Test Case """
+ """GENEVE L3 Test Case"""
@classmethod
def setUpClass(cls):
@@ -265,43 +282,55 @@ class TestGeneveL3(VppTestCase):
def test_l3_packet(self):
vni = 1234
- r = self.vapi.add_node_next(node_name="geneve4-input",
- next_name="ethernet-input")
+ r = self.vapi.add_node_next(
+ node_name="geneve4-input", next_name="ethernet-input"
+ )
r = self.vapi.geneve_add_del_tunnel2(
is_add=1,
local_address=self.pg0.local_ip4,
remote_address=self.pg0.remote_ip4,
vni=vni,
l3_mode=1,
- decap_next_index=r.next_index)
+ decap_next_index=r.next_index,
+ )
self.vapi.sw_interface_add_del_address(
- sw_if_index=r.sw_if_index, prefix="10.0.0.1/24")
-
- pkt = (Ether(src=self.pg0.remote_mac, dst="d0:0b:ee:d0:00:00") /
- IP(src='10.0.0.2', dst='10.0.0.1') /
- ICMP())
-
- encap = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=6081, dport=6081, chksum=0) /
- GENEVE(vni=vni))
-
- arp = (Ether(src=self.pg0.remote_mac, dst="d0:0b:ee:d0:00:00") /
- ARP(op="is-at", hwsrc=self.pg0.remote_mac,
- hwdst="d0:0b:ee:d0:00:00", psrc="10.0.0.2",
- pdst="10.0.0.1"))
-
- rx = self.send_and_expect(self.pg0, encap/pkt*1, self.pg0)
- rx = self.send_and_assert_no_replies(self.pg0, encap/arp*1, self.pg0)
- rx = self.send_and_expect(self.pg0, encap/pkt*1, self.pg0)
+ sw_if_index=r.sw_if_index, prefix="10.0.0.1/24"
+ )
+
+ pkt = (
+ Ether(src=self.pg0.remote_mac, dst="d0:0b:ee:d0:00:00")
+ / IP(src="10.0.0.2", dst="10.0.0.1")
+ / ICMP()
+ )
+
+ encap = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=6081, dport=6081, chksum=0)
+ / GENEVE(vni=vni)
+ )
+
+ arp = Ether(src=self.pg0.remote_mac, dst="d0:0b:ee:d0:00:00") / ARP(
+ op="is-at",
+ hwsrc=self.pg0.remote_mac,
+ hwdst="d0:0b:ee:d0:00:00",
+ psrc="10.0.0.2",
+ pdst="10.0.0.1",
+ )
+
+ rx = self.send_and_expect(self.pg0, encap / pkt * 1, self.pg0)
+ rx = self.send_and_assert_no_replies(self.pg0, encap / arp * 1, self.pg0)
+ rx = self.send_and_expect(self.pg0, encap / pkt * 1, self.pg0)
self.assertEqual(rx[0][ICMP].type, 0) # echo reply
r = self.vapi.geneve_add_del_tunnel2(
is_add=0,
local_address=self.pg0.local_ip4,
remote_address=self.pg0.remote_ip4,
- vni=vni)
+ vni=vni,
+ )
+
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_gre.py b/test/test_gre.py
index ba20ba8dec0..a79819ed73c 100644
--- a/test/test_gre.py
+++ b/test/test_gre.py
@@ -15,8 +15,13 @@ from vpp_sub_interface import L2_VTR_OP, VppDot1QSubint
from vpp_gre_interface import VppGreInterface
from vpp_teib import VppTeib
from vpp_ip import DpoProto
-from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpTable, FibPathProto, \
- VppMplsLabel
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ VppIpTable,
+ FibPathProto,
+ VppMplsLabel,
+)
from vpp_mpls_tunnel_interface import VppMPLSTunnelInterface
from util import ppp, ppc
from vpp_papi import VppEnum
@@ -24,7 +29,7 @@ from vpp_papi import VppEnum
@tag_fixme_vpp_workers
class TestGREInputNodes(VppTestCase):
- """ GRE Input Nodes Test Case """
+ """GRE Input Nodes Test Case"""
def setUp(self):
super(TestGREInputNodes, self).setUp()
@@ -43,16 +48,17 @@ class TestGREInputNodes(VppTestCase):
super(TestGREInputNodes, self).tearDown()
def test_gre_input_node(self):
- """ GRE gre input nodes not registerd unless configured """
- pkt = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- GRE())
+ """GRE gre input nodes not registerd unless configured"""
+ pkt = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / GRE()
+ )
self.pg0.add_stream(pkt)
self.pg_start()
# no tunnel created, gre-input not registered
- err = self.statistics.get_counter(
- '/err/ip4-local/unknown ip protocol')[0]
+ err = self.statistics.get_counter("/err/ip4-local/unknown ip protocol")[0]
self.assertEqual(err, 1)
err_count = err
@@ -63,14 +69,13 @@ class TestGREInputNodes(VppTestCase):
self.pg0.add_stream(pkt)
self.pg_start()
# tunnel created, gre-input registered
- err = self.statistics.get_counter(
- '/err/ip4-local/unknown ip protocol')[0]
+ err = self.statistics.get_counter("/err/ip4-local/unknown ip protocol")[0]
# expect no new errors
self.assertEqual(err, err_count)
class TestGRE(VppTestCase):
- """ GRE Test Case """
+ """GRE Test Case"""
@classmethod
def setUpClass(cls):
@@ -118,10 +123,12 @@ class TestGRE(VppTestCase):
for i in range(0, 257):
info = self.create_packet_info(src_if, src_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=src_ip, dst=dst_ip, tos=tos) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=src_ip, dst=dst_ip, tos=tos)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
pkts.append(p)
return pkts
@@ -132,107 +139,107 @@ class TestGRE(VppTestCase):
for i in range(0, 257):
info = self.create_packet_info(src_if, src_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IPv6(src=src_ip, dst=dst_ip, tc=tc) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IPv6(src=src_ip, dst=dst_ip, tc=tc)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
pkts.append(p)
return pkts
- def create_tunnel_stream_4o4(self, src_if,
- tunnel_src, tunnel_dst,
- src_ip, dst_ip):
+ def create_tunnel_stream_4o4(self, src_if, tunnel_src, tunnel_dst, src_ip, dst_ip):
pkts = []
for i in range(0, 257):
info = self.create_packet_info(src_if, src_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=tunnel_src, dst=tunnel_dst) /
- GRE() /
- IP(src=src_ip, dst=dst_ip) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=tunnel_src, dst=tunnel_dst)
+ / GRE()
+ / IP(src=src_ip, dst=dst_ip)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
pkts.append(p)
return pkts
- def create_tunnel_stream_6o4(self, src_if,
- tunnel_src, tunnel_dst,
- src_ip, dst_ip):
+ def create_tunnel_stream_6o4(self, src_if, tunnel_src, tunnel_dst, src_ip, dst_ip):
pkts = []
for i in range(0, 257):
info = self.create_packet_info(src_if, src_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=tunnel_src, dst=tunnel_dst) /
- GRE() /
- IPv6(src=src_ip, dst=dst_ip) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=tunnel_src, dst=tunnel_dst)
+ / GRE()
+ / IPv6(src=src_ip, dst=dst_ip)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
pkts.append(p)
return pkts
- def create_tunnel_stream_6o6(self, src_if,
- tunnel_src, tunnel_dst,
- src_ip, dst_ip):
+ def create_tunnel_stream_6o6(self, src_if, tunnel_src, tunnel_dst, src_ip, dst_ip):
pkts = []
for i in range(0, 257):
info = self.create_packet_info(src_if, src_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IPv6(src=tunnel_src, dst=tunnel_dst) /
- GRE() /
- IPv6(src=src_ip, dst=dst_ip) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IPv6(src=tunnel_src, dst=tunnel_dst)
+ / GRE()
+ / IPv6(src=src_ip, dst=dst_ip)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
pkts.append(p)
return pkts
- def create_tunnel_stream_l2o4(self, src_if,
- tunnel_src, tunnel_dst):
+ def create_tunnel_stream_l2o4(self, src_if, tunnel_src, tunnel_dst):
pkts = []
for i in range(0, 257):
info = self.create_packet_info(src_if, src_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=tunnel_src, dst=tunnel_dst) /
- GRE() /
- Ether(dst=RandMAC('*:*:*:*:*:*'),
- src=RandMAC('*:*:*:*:*:*')) /
- IP(src=scapy.compat.raw(RandIP()),
- dst=scapy.compat.raw(RandIP())) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=tunnel_src, dst=tunnel_dst)
+ / GRE()
+ / Ether(dst=RandMAC("*:*:*:*:*:*"), src=RandMAC("*:*:*:*:*:*"))
+ / IP(src=scapy.compat.raw(RandIP()), dst=scapy.compat.raw(RandIP()))
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
pkts.append(p)
return pkts
- def create_tunnel_stream_vlano4(self, src_if,
- tunnel_src, tunnel_dst, vlan):
+ def create_tunnel_stream_vlano4(self, src_if, tunnel_src, tunnel_dst, vlan):
pkts = []
for i in range(0, 257):
info = self.create_packet_info(src_if, src_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=tunnel_src, dst=tunnel_dst) /
- GRE() /
- Ether(dst=RandMAC('*:*:*:*:*:*'),
- src=RandMAC('*:*:*:*:*:*')) /
- Dot1Q(vlan=vlan) /
- IP(src=scapy.compat.raw(RandIP()),
- dst=scapy.compat.raw(RandIP())) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=tunnel_src, dst=tunnel_dst)
+ / GRE()
+ / Ether(dst=RandMAC("*:*:*:*:*:*"), src=RandMAC("*:*:*:*:*:*"))
+ / Dot1Q(vlan=vlan)
+ / IP(src=scapy.compat.raw(RandIP()), dst=scapy.compat.raw(RandIP()))
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
pkts.append(p)
return pkts
- def verify_tunneled_4o4(self, src_if, capture, sent,
- tunnel_src, tunnel_dst,
- dscp=0, ecn=0):
+ def verify_tunneled_4o4(
+ self, src_if, capture, sent, tunnel_src, tunnel_dst, dscp=0, ecn=0
+ ):
self.assertEqual(len(capture), len(sent))
tos = (dscp << 2) | ecn
@@ -263,9 +270,9 @@ class TestGRE(VppTestCase):
self.logger.error(ppp("Tx:", tx))
raise
- def verify_tunneled_6o6(self, src_if, capture, sent,
- tunnel_src, tunnel_dst,
- dscp=0, ecn=0):
+ def verify_tunneled_6o6(
+ self, src_if, capture, sent, tunnel_src, tunnel_dst, dscp=0, ecn=0
+ ):
self.assertEqual(len(capture), len(sent))
tc = (dscp << 2) | ecn
@@ -296,8 +303,7 @@ class TestGRE(VppTestCase):
self.logger.error(ppp("Tx:", tx))
raise
- def verify_tunneled_4o6(self, src_if, capture, sent,
- tunnel_src, tunnel_dst):
+ def verify_tunneled_4o6(self, src_if, capture, sent, tunnel_src, tunnel_dst):
self.assertEqual(len(capture), len(sent))
@@ -326,8 +332,7 @@ class TestGRE(VppTestCase):
self.logger.error(ppp("Tx:", tx))
raise
- def verify_tunneled_6o4(self, src_if, capture, sent,
- tunnel_src, tunnel_dst):
+ def verify_tunneled_6o4(self, src_if, capture, sent, tunnel_src, tunnel_dst):
self.assertEqual(len(capture), len(sent))
@@ -354,8 +359,7 @@ class TestGRE(VppTestCase):
self.logger.error(ppp("Tx:", tx))
raise
- def verify_tunneled_l2o4(self, src_if, capture, sent,
- tunnel_src, tunnel_dst):
+ def verify_tunneled_l2o4(self, src_if, capture, sent, tunnel_src, tunnel_dst):
self.assertEqual(len(capture), len(sent))
for i in range(len(capture)):
@@ -387,8 +391,9 @@ class TestGRE(VppTestCase):
self.logger.error(ppp("Tx:", tx))
raise
- def verify_tunneled_vlano4(self, src_if, capture, sent,
- tunnel_src, tunnel_dst, vlan):
+ def verify_tunneled_vlano4(
+ self, src_if, capture, sent, tunnel_src, tunnel_dst, vlan
+ ):
try:
self.assertEqual(len(capture), len(sent))
except:
@@ -495,7 +500,7 @@ class TestGRE(VppTestCase):
raise
def test_gre(self):
- """ GRE IPv4 tunnel Tests """
+ """GRE IPv4 tunnel Tests"""
#
# Create an L3 GRE tunnel.
@@ -503,9 +508,7 @@ class TestGRE(VppTestCase):
# - assign an IP Addres
# - Add a route via the tunnel
#
- gre_if = VppGreInterface(self,
- self.pg0.local_ip4,
- "1.1.1.2")
+ gre_if = VppGreInterface(self, self.pg0.local_ip4, "1.1.1.2")
gre_if.add_vpp_config()
#
@@ -522,9 +525,9 @@ class TestGRE(VppTestCase):
gre_if.admin_up()
gre_if.config_ip4()
- route_via_tun = VppIpRoute(self, "4.4.4.4", 32,
- [VppRoutePath("0.0.0.0",
- gre_if.sw_if_index)])
+ route_via_tun = VppIpRoute(
+ self, "4.4.4.4", 32, [VppRoutePath("0.0.0.0", gre_if.sw_if_index)]
+ )
route_via_tun.add_vpp_config()
@@ -541,9 +544,12 @@ class TestGRE(VppTestCase):
#
# Add a route that resolves the tunnel's destination
#
- route_tun_dst = VppIpRoute(self, "1.1.1.2", 32,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index)])
+ route_tun_dst = VppIpRoute(
+ self,
+ "1.1.1.2",
+ 32,
+ [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index)],
+ )
route_tun_dst.add_vpp_config()
#
@@ -552,18 +558,19 @@ class TestGRE(VppTestCase):
#
tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "4.4.4.4")
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_tunneled_4o4(self.pg0, rx, tx,
- self.pg0.local_ip4, "1.1.1.2")
+ self.verify_tunneled_4o4(self.pg0, rx, tx, self.pg0.local_ip4, "1.1.1.2")
#
# Send tunneled packets that match the created tunnel and
# are decapped and forwarded
#
- tx = self.create_tunnel_stream_4o4(self.pg0,
- "1.1.1.2",
- self.pg0.local_ip4,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ tx = self.create_tunnel_stream_4o4(
+ self.pg0,
+ "1.1.1.2",
+ self.pg0.local_ip4,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
self.verify_decapped_4o4(self.pg0, rx, tx)
@@ -571,14 +578,16 @@ class TestGRE(VppTestCase):
# Send tunneled packets that do not match the tunnel's src
#
self.vapi.cli("clear trace")
- tx = self.create_tunnel_stream_4o4(self.pg0,
- "1.1.1.3",
- self.pg0.local_ip4,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ tx = self.create_tunnel_stream_4o4(
+ self.pg0,
+ "1.1.1.3",
+ self.pg0.local_ip4,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ )
self.send_and_assert_no_replies(
- self.pg0, tx,
- remark="GRE packets forwarded despite no SRC address match")
+ self.pg0, tx, remark="GRE packets forwarded despite no SRC address match"
+ )
#
# Configure IPv6 on the PG interface so we can route IPv6
@@ -591,14 +600,18 @@ class TestGRE(VppTestCase):
# Send IPv6 tunnel encapslated packets
# - dropped since IPv6 is not enabled on the tunnel
#
- tx = self.create_tunnel_stream_6o4(self.pg0,
- "1.1.1.2",
- self.pg0.local_ip4,
- self.pg0.local_ip6,
- self.pg0.remote_ip6)
- self.send_and_assert_no_replies(self.pg0, tx,
- "IPv6 GRE packets forwarded "
- "despite IPv6 not enabled on tunnel")
+ tx = self.create_tunnel_stream_6o4(
+ self.pg0,
+ "1.1.1.2",
+ self.pg0.local_ip4,
+ self.pg0.local_ip6,
+ self.pg0.remote_ip6,
+ )
+ self.send_and_assert_no_replies(
+ self.pg0,
+ tx,
+ "IPv6 GRE packets forwarded despite IPv6 not enabled on tunnel",
+ )
#
# Enable IPv6 on the tunnel
@@ -609,11 +622,13 @@ class TestGRE(VppTestCase):
# Send IPv6 tunnel encapslated packets
# - forwarded since IPv6 is enabled on the tunnel
#
- tx = self.create_tunnel_stream_6o4(self.pg0,
- "1.1.1.2",
- self.pg0.local_ip4,
- self.pg0.local_ip6,
- self.pg0.remote_ip6)
+ tx = self.create_tunnel_stream_6o4(
+ self.pg0,
+ "1.1.1.2",
+ self.pg0.local_ip4,
+ self.pg0.local_ip6,
+ self.pg0.remote_ip6,
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
self.verify_decapped_6o4(self.pg0, rx, tx)
@@ -621,31 +636,32 @@ class TestGRE(VppTestCase):
# Send v6 packets for v4 encap
#
route6_via_tun = VppIpRoute(
- self, "2001::1", 128,
- [VppRoutePath("::",
- gre_if.sw_if_index,
- proto=DpoProto.DPO_PROTO_IP6)])
+ self,
+ "2001::1",
+ 128,
+ [VppRoutePath("::", gre_if.sw_if_index, proto=DpoProto.DPO_PROTO_IP6)],
+ )
route6_via_tun.add_vpp_config()
tx = self.create_stream_ip6(self.pg0, "2001::2", "2001::1")
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_tunneled_6o4(self.pg0, rx, tx,
- self.pg0.local_ip4, "1.1.1.2")
+ self.verify_tunneled_6o4(self.pg0, rx, tx, self.pg0.local_ip4, "1.1.1.2")
#
# add a labelled route through the tunnel
#
- label_via_tun = VppIpRoute(self, "5.4.3.2", 32,
- [VppRoutePath("0.0.0.0",
- gre_if.sw_if_index,
- labels=[VppMplsLabel(33)])])
+ label_via_tun = VppIpRoute(
+ self,
+ "5.4.3.2",
+ 32,
+ [VppRoutePath("0.0.0.0", gre_if.sw_if_index, labels=[VppMplsLabel(33)])],
+ )
label_via_tun.add_vpp_config()
tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "5.4.3.2")
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_tunneled_4o4(self.pg0, rx, tx,
- self.pg0.local_ip4, "1.1.1.2")
+ self.verify_tunneled_4o4(self.pg0, rx, tx, self.pg0.local_ip4, "1.1.1.2")
#
# an MPLS tunnel over the GRE tunnel add a route through
@@ -653,31 +669,40 @@ class TestGRE(VppTestCase):
#
mpls_tun = VppMPLSTunnelInterface(
self,
- [VppRoutePath("0.0.0.0",
- gre_if.sw_if_index,
- labels=[VppMplsLabel(44),
- VppMplsLabel(46)])])
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ gre_if.sw_if_index,
+ labels=[VppMplsLabel(44), VppMplsLabel(46)],
+ )
+ ],
+ )
mpls_tun.add_vpp_config()
mpls_tun.admin_up()
- label_via_mpls = VppIpRoute(self, "5.4.3.1", 32,
- [VppRoutePath("0.0.0.0",
- mpls_tun.sw_if_index,
- labels=[VppMplsLabel(33)])])
+ label_via_mpls = VppIpRoute(
+ self,
+ "5.4.3.1",
+ 32,
+ [VppRoutePath("0.0.0.0", mpls_tun.sw_if_index, labels=[VppMplsLabel(33)])],
+ )
label_via_mpls.add_vpp_config()
tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "5.4.3.1")
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_tunneled_4o4(self.pg0, rx, tx,
- self.pg0.local_ip4, "1.1.1.2")
+ self.verify_tunneled_4o4(self.pg0, rx, tx, self.pg0.local_ip4, "1.1.1.2")
mpls_tun_l2 = VppMPLSTunnelInterface(
self,
- [VppRoutePath("0.0.0.0",
- gre_if.sw_if_index,
- labels=[VppMplsLabel(44),
- VppMplsLabel(46)])],
- is_l2=1)
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ gre_if.sw_if_index,
+ labels=[VppMplsLabel(44), VppMplsLabel(46)],
+ )
+ ],
+ is_l2=1,
+ )
mpls_tun_l2.add_vpp_config()
mpls_tun_l2.admin_up()
@@ -696,7 +721,7 @@ class TestGRE(VppTestCase):
self.pg0.unconfig_ip6()
def test_gre6(self):
- """ GRE IPv6 tunnel Tests """
+ """GRE IPv6 tunnel Tests"""
self.pg1.config_ip6()
self.pg1.resolve_ndp()
@@ -707,16 +732,14 @@ class TestGRE(VppTestCase):
# - assign an IP Address
# - Add a route via the tunnel
#
- gre_if = VppGreInterface(self,
- self.pg2.local_ip6,
- "1002::1")
+ gre_if = VppGreInterface(self, self.pg2.local_ip6, "1002::1")
gre_if.add_vpp_config()
gre_if.admin_up()
gre_if.config_ip6()
- route_via_tun = VppIpRoute(self, "4004::1", 128,
- [VppRoutePath("0::0",
- gre_if.sw_if_index)])
+ route_via_tun = VppIpRoute(
+ self, "4004::1", 128, [VppRoutePath("0::0", gre_if.sw_if_index)]
+ )
route_via_tun.add_vpp_config()
@@ -728,15 +751,18 @@ class TestGRE(VppTestCase):
#
tx = self.create_stream_ip6(self.pg2, "5005::1", "4004::1")
self.send_and_assert_no_replies(
- self.pg2, tx,
- "GRE packets forwarded without DIP resolved")
+ self.pg2, tx, "GRE packets forwarded without DIP resolved"
+ )
#
# Add a route that resolves the tunnel's destination
#
- route_tun_dst = VppIpRoute(self, "1002::1", 128,
- [VppRoutePath(self.pg2.remote_ip6,
- self.pg2.sw_if_index)])
+ route_tun_dst = VppIpRoute(
+ self,
+ "1002::1",
+ 128,
+ [VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index)],
+ )
route_tun_dst.add_vpp_config()
#
@@ -745,17 +771,14 @@ class TestGRE(VppTestCase):
#
tx = self.create_stream_ip6(self.pg2, "5005::1", "4004::1")
rx = self.send_and_expect(self.pg2, tx, self.pg2)
- self.verify_tunneled_6o6(self.pg2, rx, tx,
- self.pg2.local_ip6, "1002::1")
+ self.verify_tunneled_6o6(self.pg2, rx, tx, self.pg2.local_ip6, "1002::1")
#
# Test decap. decapped packets go out pg1
#
- tx = self.create_tunnel_stream_6o6(self.pg2,
- "1002::1",
- self.pg2.local_ip6,
- "2001::1",
- self.pg1.remote_ip6)
+ tx = self.create_tunnel_stream_6o6(
+ self.pg2, "1002::1", self.pg2.local_ip6, "2001::1", self.pg1.remote_ip6
+ )
rx = self.send_and_expect(self.pg2, tx, self.pg1)
#
@@ -767,16 +790,15 @@ class TestGRE(VppTestCase):
#
# Send v4 over v6
#
- route4_via_tun = VppIpRoute(self, "1.1.1.1", 32,
- [VppRoutePath("0.0.0.0",
- gre_if.sw_if_index)])
+ route4_via_tun = VppIpRoute(
+ self, "1.1.1.1", 32, [VppRoutePath("0.0.0.0", gre_if.sw_if_index)]
+ )
route4_via_tun.add_vpp_config()
tx = self.create_stream_ip4(self.pg0, "1.1.1.2", "1.1.1.1")
rx = self.send_and_expect(self.pg0, tx, self.pg2)
- self.verify_tunneled_4o6(self.pg0, rx, tx,
- self.pg2.local_ip6, "1002::1")
+ self.verify_tunneled_4o6(self.pg0, rx, tx, self.pg2.local_ip6, "1002::1")
#
# test case cleanup
@@ -790,7 +812,7 @@ class TestGRE(VppTestCase):
self.pg1.unconfig_ip6()
def test_gre_vrf(self):
- """ GRE tunnel VRF Tests """
+ """GRE tunnel VRF Tests"""
e = VppEnum.vl_api_tunnel_encap_decap_flags_t
@@ -802,11 +824,15 @@ class TestGRE(VppTestCase):
# - assign an IP Addres
#
gre_if = VppGreInterface(
- self, self.pg1.local_ip4,
+ self,
+ self.pg1.local_ip4,
"2.2.2.2",
outer_table_id=1,
- flags=(e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP |
- e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN))
+ flags=(
+ e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP
+ | e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN
+ ),
+ )
gre_if.add_vpp_config()
gre_if.admin_up()
@@ -815,18 +841,22 @@ class TestGRE(VppTestCase):
#
# Add a route via the tunnel - in the overlay
#
- route_via_tun = VppIpRoute(self, "9.9.9.9", 32,
- [VppRoutePath("0.0.0.0",
- gre_if.sw_if_index)])
+ route_via_tun = VppIpRoute(
+ self, "9.9.9.9", 32, [VppRoutePath("0.0.0.0", gre_if.sw_if_index)]
+ )
route_via_tun.add_vpp_config()
#
# Add a route that resolves the tunnel's destination - in the
# underlay table
#
- route_tun_dst = VppIpRoute(self, "2.2.2.2", 32, table_id=1,
- paths=[VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_tun_dst = VppIpRoute(
+ self,
+ "2.2.2.2",
+ 32,
+ table_id=1,
+ paths=[VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_tun_dst.add_vpp_config()
#
@@ -835,12 +865,11 @@ class TestGRE(VppTestCase):
# - packets are GRE encapped
#
self.vapi.cli("clear trace")
- tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "9.9.9.9",
- dscp=5, ecn=3)
+ tx = self.create_stream_ip4(self.pg0, "5.5.5.5", "9.9.9.9", dscp=5, ecn=3)
rx = self.send_and_expect(self.pg0, tx, self.pg1)
- self.verify_tunneled_4o4(self.pg1, rx, tx,
- self.pg1.local_ip4, "2.2.2.2",
- dscp=5, ecn=3)
+ self.verify_tunneled_4o4(
+ self.pg1, rx, tx, self.pg1.local_ip4, "2.2.2.2", dscp=5, ecn=3
+ )
#
# Send tunneled packets that match the created tunnel and
@@ -848,11 +877,13 @@ class TestGRE(VppTestCase):
# does not happen in the encap table
#
self.vapi.cli("clear trace")
- tx = self.create_tunnel_stream_4o4(self.pg1,
- "2.2.2.2",
- self.pg1.local_ip4,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ tx = self.create_tunnel_stream_4o4(
+ self.pg1,
+ "2.2.2.2",
+ self.pg1.local_ip4,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ )
rx = self.send_and_expect(self.pg1, tx, self.pg0)
self.verify_decapped_4o4(self.pg0, rx, tx)
@@ -865,14 +896,16 @@ class TestGRE(VppTestCase):
#
self.pg2.config_ip4()
self.vapi.cli("clear trace")
- tx = self.create_tunnel_stream_4o4(self.pg2,
- "2.2.2.2",
- self.pg1.local_ip4,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ tx = self.create_tunnel_stream_4o4(
+ self.pg2,
+ "2.2.2.2",
+ self.pg1.local_ip4,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ )
rx = self.send_and_assert_no_replies(
- self.pg2, tx,
- "GRE decap packets in wrong VRF")
+ self.pg2, tx, "GRE decap packets in wrong VRF"
+ )
self.pg2.unconfig_ip4()
@@ -884,17 +917,23 @@ class TestGRE(VppTestCase):
gre_if.remove_vpp_config()
def test_gre_l2(self):
- """ GRE tunnel L2 Tests """
+ """GRE tunnel L2 Tests"""
#
# Add routes to resolve the tunnel destinations
#
- route_tun1_dst = VppIpRoute(self, "2.2.2.2", 32,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index)])
- route_tun2_dst = VppIpRoute(self, "2.2.2.3", 32,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index)])
+ route_tun1_dst = VppIpRoute(
+ self,
+ "2.2.2.2",
+ 32,
+ [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index)],
+ )
+ route_tun2_dst = VppIpRoute(
+ self,
+ "2.2.2.3",
+ 32,
+ [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index)],
+ )
route_tun1_dst.add_vpp_config()
route_tun2_dst.add_vpp_config()
@@ -902,53 +941,49 @@ class TestGRE(VppTestCase):
#
# Create 2 L2 GRE tunnels and x-connect them
#
- gre_if1 = VppGreInterface(self, self.pg0.local_ip4,
- "2.2.2.2",
- type=(VppEnum.vl_api_gre_tunnel_type_t.
- GRE_API_TUNNEL_TYPE_TEB))
- gre_if2 = VppGreInterface(self, self.pg0.local_ip4,
- "2.2.2.3",
- type=(VppEnum.vl_api_gre_tunnel_type_t.
- GRE_API_TUNNEL_TYPE_TEB))
+ gre_if1 = VppGreInterface(
+ self,
+ self.pg0.local_ip4,
+ "2.2.2.2",
+ type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB),
+ )
+ gre_if2 = VppGreInterface(
+ self,
+ self.pg0.local_ip4,
+ "2.2.2.3",
+ type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB),
+ )
gre_if1.add_vpp_config()
gre_if2.add_vpp_config()
gre_if1.admin_up()
gre_if2.admin_up()
- self.vapi.sw_interface_set_l2_xconnect(gre_if1.sw_if_index,
- gre_if2.sw_if_index,
- enable=1)
- self.vapi.sw_interface_set_l2_xconnect(gre_if2.sw_if_index,
- gre_if1.sw_if_index,
- enable=1)
+ self.vapi.sw_interface_set_l2_xconnect(
+ gre_if1.sw_if_index, gre_if2.sw_if_index, enable=1
+ )
+ self.vapi.sw_interface_set_l2_xconnect(
+ gre_if2.sw_if_index, gre_if1.sw_if_index, enable=1
+ )
#
# Send in tunnel encapped L2. expect out tunnel encapped L2
# in both directions
#
- tx = self.create_tunnel_stream_l2o4(self.pg0,
- "2.2.2.2",
- self.pg0.local_ip4)
+ tx = self.create_tunnel_stream_l2o4(self.pg0, "2.2.2.2", self.pg0.local_ip4)
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_tunneled_l2o4(self.pg0, rx, tx,
- self.pg0.local_ip4,
- "2.2.2.3")
+ self.verify_tunneled_l2o4(self.pg0, rx, tx, self.pg0.local_ip4, "2.2.2.3")
- tx = self.create_tunnel_stream_l2o4(self.pg0,
- "2.2.2.3",
- self.pg0.local_ip4)
+ tx = self.create_tunnel_stream_l2o4(self.pg0, "2.2.2.3", self.pg0.local_ip4)
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_tunneled_l2o4(self.pg0, rx, tx,
- self.pg0.local_ip4,
- "2.2.2.2")
+ self.verify_tunneled_l2o4(self.pg0, rx, tx, self.pg0.local_ip4, "2.2.2.2")
- self.vapi.sw_interface_set_l2_xconnect(gre_if1.sw_if_index,
- gre_if2.sw_if_index,
- enable=0)
- self.vapi.sw_interface_set_l2_xconnect(gre_if2.sw_if_index,
- gre_if1.sw_if_index,
- enable=0)
+ self.vapi.sw_interface_set_l2_xconnect(
+ gre_if1.sw_if_index, gre_if2.sw_if_index, enable=0
+ )
+ self.vapi.sw_interface_set_l2_xconnect(
+ gre_if2.sw_if_index, gre_if1.sw_if_index, enable=0
+ )
#
# Create a VLAN sub-interfaces on the GRE TEB interfaces
@@ -963,47 +998,39 @@ class TestGRE(VppTestCase):
gre_if_11.admin_up()
gre_if_12.admin_up()
- self.vapi.sw_interface_set_l2_xconnect(gre_if_11.sw_if_index,
- gre_if_12.sw_if_index,
- enable=1)
- self.vapi.sw_interface_set_l2_xconnect(gre_if_12.sw_if_index,
- gre_if_11.sw_if_index,
- enable=1)
+ self.vapi.sw_interface_set_l2_xconnect(
+ gre_if_11.sw_if_index, gre_if_12.sw_if_index, enable=1
+ )
+ self.vapi.sw_interface_set_l2_xconnect(
+ gre_if_12.sw_if_index, gre_if_11.sw_if_index, enable=1
+ )
#
# Configure both to pop thier respective VLAN tags,
# so that during the x-coonect they will subsequently push
#
self.vapi.l2_interface_vlan_tag_rewrite(
- sw_if_index=gre_if_12.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1,
- push_dot1q=12)
+ sw_if_index=gre_if_12.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1, push_dot1q=12
+ )
self.vapi.l2_interface_vlan_tag_rewrite(
- sw_if_index=gre_if_11.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1,
- push_dot1q=11)
+ sw_if_index=gre_if_11.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1, push_dot1q=11
+ )
#
# Send traffic in both directiond - expect the VLAN tags to
# be swapped.
#
- tx = self.create_tunnel_stream_vlano4(self.pg0,
- "2.2.2.2",
- self.pg0.local_ip4,
- 11)
+ tx = self.create_tunnel_stream_vlano4(
+ self.pg0, "2.2.2.2", self.pg0.local_ip4, 11
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_tunneled_vlano4(self.pg0, rx, tx,
- self.pg0.local_ip4,
- "2.2.2.3",
- 12)
-
- tx = self.create_tunnel_stream_vlano4(self.pg0,
- "2.2.2.3",
- self.pg0.local_ip4,
- 12)
+ self.verify_tunneled_vlano4(self.pg0, rx, tx, self.pg0.local_ip4, "2.2.2.3", 12)
+
+ tx = self.create_tunnel_stream_vlano4(
+ self.pg0, "2.2.2.3", self.pg0.local_ip4, 12
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_tunneled_vlano4(self.pg0, rx, tx,
- self.pg0.local_ip4,
- "2.2.2.2",
- 11)
+ self.verify_tunneled_vlano4(self.pg0, rx, tx, self.pg0.local_ip4, "2.2.2.2", 11)
#
# Cleanup Test resources
@@ -1016,16 +1043,14 @@ class TestGRE(VppTestCase):
route_tun2_dst.add_vpp_config()
def test_gre_loop(self):
- """ GRE tunnel loop Tests """
+ """GRE tunnel loop Tests"""
#
# Create an L3 GRE tunnel.
# - set it admin up
# - assign an IP Addres
#
- gre_if = VppGreInterface(self,
- self.pg0.local_ip4,
- "1.1.1.2")
+ gre_if = VppGreInterface(self, self.pg0.local_ip4, "1.1.1.2")
gre_if.add_vpp_config()
gre_if.admin_up()
gre_if.config_ip4()
@@ -1035,9 +1060,9 @@ class TestGRE(VppTestCase):
# through the tunnel, hence forming a loop in the forwarding
# graph
#
- route_dst = VppIpRoute(self, "1.1.1.2", 32,
- [VppRoutePath("0.0.0.0",
- gre_if.sw_if_index)])
+ route_dst = VppIpRoute(
+ self, "1.1.1.2", 32, [VppRoutePath("0.0.0.0", gre_if.sw_if_index)]
+ )
route_dst.add_vpp_config()
#
@@ -1051,8 +1076,7 @@ class TestGRE(VppTestCase):
#
# break the loop
#
- route_dst.modify([VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_dst.modify([VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)])
route_dst.add_vpp_config()
rx = self.send_and_expect(self.pg0, tx, self.pg1)
@@ -1060,15 +1084,14 @@ class TestGRE(VppTestCase):
#
# a good route throught the tunnel to check it restacked
#
- route_via_tun_2 = VppIpRoute(self, "2.2.2.2", 32,
- [VppRoutePath("0.0.0.0",
- gre_if.sw_if_index)])
+ route_via_tun_2 = VppIpRoute(
+ self, "2.2.2.2", 32, [VppRoutePath("0.0.0.0", gre_if.sw_if_index)]
+ )
route_via_tun_2.add_vpp_config()
tx = self.create_stream_ip4(self.pg0, "2.2.2.3", "2.2.2.2")
rx = self.send_and_expect(self.pg0, tx, self.pg1)
- self.verify_tunneled_4o4(self.pg1, rx, tx,
- self.pg0.local_ip4, "1.1.1.2")
+ self.verify_tunneled_4o4(self.pg1, rx, tx, self.pg0.local_ip4, "1.1.1.2")
#
# cleanup
@@ -1077,7 +1100,7 @@ class TestGRE(VppTestCase):
gre_if.remove_vpp_config()
def test_mgre(self):
- """ mGRE IPv4 tunnel Tests """
+ """mGRE IPv4 tunnel Tests"""
for itf in self.pg_interfaces[3:]:
#
@@ -1092,11 +1115,12 @@ class TestGRE(VppTestCase):
# - assign an IP Addres
# - Add a route via the tunnel
#
- gre_if = VppGreInterface(self,
- itf.local_ip4,
- "0.0.0.0",
- mode=(VppEnum.vl_api_tunnel_mode_t.
- TUNNEL_API_MODE_MP))
+ gre_if = VppGreInterface(
+ self,
+ itf.local_ip4,
+ "0.0.0.0",
+ mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP),
+ )
gre_if.add_vpp_config()
gre_if.admin_up()
gre_if.config_ip4()
@@ -1109,11 +1133,13 @@ class TestGRE(VppTestCase):
# ensure we don't match to the tunnel if the source address
# is all zeros
#
- tx = self.create_tunnel_stream_4o4(self.pg0,
- "0.0.0.0",
- itf.local_ip4,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ tx = self.create_tunnel_stream_4o4(
+ self.pg0,
+ "0.0.0.0",
+ itf.local_ip4,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ )
self.send_and_assert_no_replies(self.pg0, tx)
#
@@ -1127,9 +1153,11 @@ class TestGRE(VppTestCase):
# route traffic via the peer
#
route_via_tun = VppIpRoute(
- self, route_addr, 32,
- [VppRoutePath(gre_if._remote_hosts[ii].ip4,
- gre_if.sw_if_index)])
+ self,
+ route_addr,
+ 32,
+ [VppRoutePath(gre_if._remote_hosts[ii].ip4, gre_if.sw_if_index)],
+ )
route_via_tun.add_vpp_config()
# all packets dropped at this point
@@ -1142,9 +1170,12 @@ class TestGRE(VppTestCase):
#
# Add a TEIB entry resolves the peer
#
- teib = VppTeib(self, gre_if,
- gre_if._remote_hosts[ii].ip4,
- itf._remote_hosts[ii].ip4)
+ teib = VppTeib(
+ self,
+ gre_if,
+ gre_if._remote_hosts[ii].ip4,
+ itf._remote_hosts[ii].ip4,
+ )
teib.add_vpp_config()
#
@@ -1152,15 +1183,17 @@ class TestGRE(VppTestCase):
# - packets are GRE encapped
#
rx = self.send_and_expect(self.pg0, tx_e, itf)
- self.verify_tunneled_4o4(self.pg0, rx, tx_e,
- itf.local_ip4,
- itf._remote_hosts[ii].ip4)
-
- tx_i = self.create_tunnel_stream_4o4(self.pg0,
- itf._remote_hosts[ii].ip4,
- itf.local_ip4,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ self.verify_tunneled_4o4(
+ self.pg0, rx, tx_e, itf.local_ip4, itf._remote_hosts[ii].ip4
+ )
+
+ tx_i = self.create_tunnel_stream_4o4(
+ self.pg0,
+ itf._remote_hosts[ii].ip4,
+ itf.local_ip4,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ )
rx = self.send_and_expect(self.pg0, tx_i, self.pg0)
self.verify_decapped_4o4(self.pg0, rx, tx_i)
@@ -1173,9 +1206,9 @@ class TestGRE(VppTestCase):
teib.add_vpp_config()
rx = self.send_and_expect(self.pg0, tx_e, itf)
- self.verify_tunneled_4o4(self.pg0, rx, tx_e,
- itf.local_ip4,
- itf._remote_hosts[ii].ip4)
+ self.verify_tunneled_4o4(
+ self.pg0, rx, tx_e, itf.local_ip4, itf._remote_hosts[ii].ip4
+ )
rx = self.send_and_expect(self.pg0, tx_i, self.pg0)
self.verify_decapped_4o4(self.pg0, rx, tx_i)
@@ -1185,9 +1218,9 @@ class TestGRE(VppTestCase):
gre_if.admin_down()
gre_if.admin_up()
rx = self.send_and_expect(self.pg0, tx_e, itf)
- self.verify_tunneled_4o4(self.pg0, rx, tx_e,
- itf.local_ip4,
- itf._remote_hosts[ii].ip4)
+ self.verify_tunneled_4o4(
+ self.pg0, rx, tx_e, itf.local_ip4, itf._remote_hosts[ii].ip4
+ )
rx = self.send_and_expect(self.pg0, tx_i, self.pg0)
self.verify_decapped_4o4(self.pg0, rx, tx_i)
@@ -1195,7 +1228,7 @@ class TestGRE(VppTestCase):
gre_if.unconfig_ip4()
def test_mgre6(self):
- """ mGRE IPv6 tunnel Tests """
+ """mGRE IPv6 tunnel Tests"""
self.pg0.config_ip6()
self.pg0.resolve_ndp()
@@ -1220,9 +1253,9 @@ class TestGRE(VppTestCase):
self,
itf.local_ip6,
"::",
- mode=(VppEnum.vl_api_tunnel_mode_t.
- TUNNEL_API_MODE_MP),
- flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP)
+ mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP),
+ flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP,
+ )
gre_if.add_vpp_config()
gre_if.admin_up()
@@ -1238,36 +1271,43 @@ class TestGRE(VppTestCase):
#
# Add a TEIB entry resolves the peer
#
- teib = VppTeib(self, gre_if,
- gre_if._remote_hosts[ii].ip6,
- itf._remote_hosts[ii].ip6)
+ teib = VppTeib(
+ self,
+ gre_if,
+ gre_if._remote_hosts[ii].ip6,
+ itf._remote_hosts[ii].ip6,
+ )
teib.add_vpp_config()
#
# route traffic via the peer
#
route_via_tun = VppIpRoute(
- self, route_addr, 128,
- [VppRoutePath(gre_if._remote_hosts[ii].ip6,
- gre_if.sw_if_index)])
+ self,
+ route_addr,
+ 128,
+ [VppRoutePath(gre_if._remote_hosts[ii].ip6, gre_if.sw_if_index)],
+ )
route_via_tun.add_vpp_config()
#
# Send a packet stream that is routed into the tunnel
# - packets are GRE encapped
#
- tx_e = self.create_stream_ip6(self.pg0, "5::5", route_addr,
- dscp=2, ecn=1)
+ tx_e = self.create_stream_ip6(
+ self.pg0, "5::5", route_addr, dscp=2, ecn=1
+ )
rx = self.send_and_expect(self.pg0, tx_e, itf)
- self.verify_tunneled_6o6(self.pg0, rx, tx_e,
- itf.local_ip6,
- itf._remote_hosts[ii].ip6,
- dscp=2)
- tx_i = self.create_tunnel_stream_6o6(self.pg0,
- itf._remote_hosts[ii].ip6,
- itf.local_ip6,
- self.pg0.local_ip6,
- self.pg0.remote_ip6)
+ self.verify_tunneled_6o6(
+ self.pg0, rx, tx_e, itf.local_ip6, itf._remote_hosts[ii].ip6, dscp=2
+ )
+ tx_i = self.create_tunnel_stream_6o6(
+ self.pg0,
+ itf._remote_hosts[ii].ip6,
+ itf.local_ip6,
+ self.pg0.local_ip6,
+ self.pg0.remote_ip6,
+ )
rx = self.send_and_expect(self.pg0, tx_i, self.pg0)
self.verify_decapped_6o6(self.pg0, rx, tx_i)
@@ -1279,10 +1319,9 @@ class TestGRE(VppTestCase):
teib.add_vpp_config()
rx = self.send_and_expect(self.pg0, tx_e, itf)
- self.verify_tunneled_6o6(self.pg0, rx, tx_e,
- itf.local_ip6,
- itf._remote_hosts[ii].ip6,
- dscp=2)
+ self.verify_tunneled_6o6(
+ self.pg0, rx, tx_e, itf.local_ip6, itf._remote_hosts[ii].ip6, dscp=2
+ )
rx = self.send_and_expect(self.pg0, tx_i, self.pg0)
self.verify_decapped_6o6(self.pg0, rx, tx_i)
@@ -1292,5 +1331,5 @@ class TestGRE(VppTestCase):
self.pg0.unconfig_ip6()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_gro.py b/test/test_gro.py
index 6c68299d7f4..7e6b03c91d4 100644
--- a/test/test_gro.py
+++ b/test/test_gro.py
@@ -26,7 +26,7 @@ from vpp_interface import VppInterface
class TestGRO(VppTestCase):
- """ GRO Test Case """
+ """GRO Test Case"""
@classmethod
def setUpClass(self):
@@ -63,17 +63,18 @@ class TestGRO(VppTestCase):
i.admin_down()
def test_gro(self):
- """ GRO test """
+ """GRO test"""
n_packets = 124
#
# Send 1500 bytes frame with gro disabled
#
- p4 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4,
- flags='DF') /
- TCP(sport=1234, dport=4321) /
- Raw(b'\xa5' * 1460))
+ p4 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, flags="DF")
+ / TCP(sport=1234, dport=4321)
+ / Raw(b"\xa5" * 1460)
+ )
rxs = self.send_and_expect(self.pg0, n_packets * p4, self.pg1)
for rx in rxs:
@@ -91,11 +92,14 @@ class TestGRO(VppTestCase):
p = []
s = 0
for n in range(0, n_packets):
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4,
- flags='DF') /
- TCP(sport=1234, dport=4321, seq=s, ack=n, flags='A') /
- Raw(b'\xa5' * 1460)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4, flags="DF")
+ / TCP(sport=1234, dport=4321, seq=s, ack=n, flags="A")
+ / Raw(b"\xa5" * 1460)
+ )
+ )
s += 1460
rxs = self.send_and_expect(self.pg0, p, self.pg2, n_rx=2)
@@ -110,14 +114,15 @@ class TestGRO(VppTestCase):
self.assertEqual(rx[IP].len, 64280) # 1460 * 44 + 40 < 65536
self.assertEqual(rx[TCP].sport, 1234)
self.assertEqual(rx[TCP].dport, 4321)
- self.assertEqual(rx[TCP].ack, (44*i - 1))
+ self.assertEqual(rx[TCP].ack, (44 * i - 1))
- p4_temp = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4,
- flags='DF') /
- TCP(sport=1234, dport=4321, flags='F'))
+ p4_temp = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4, flags="DF")
+ / TCP(sport=1234, dport=4321, flags="F")
+ )
- rxs = self.send_and_expect(self.pg2, 100*[p4_temp], self.pg0, n_rx=100)
+ rxs = self.send_and_expect(self.pg2, 100 * [p4_temp], self.pg0, n_rx=100)
rx_coalesce = self.pg2.get_capture(1, timeout=1)
rx0 = rx_coalesce[0]
@@ -144,12 +149,16 @@ class TestGRO(VppTestCase):
p = []
s = 0
for n in range(0, 88):
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg2.remote_ip6) /
- TCP(sport=1234, dport=4321, seq=s, ack=n, flags='A') /
- Raw(b'\xa5' * 1460)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg2.remote_ip6)
+ / TCP(sport=1234, dport=4321, seq=s, ack=n, flags="A")
+ / Raw(b"\xa5" * 1460)
+ )
+ )
s += 1460
- p[-1][TCP].flags = 'AP' # push to flush second packet
+ p[-1][TCP].flags = "AP" # push to flush second packet
rxs = self.send_and_expect(self.pg0, p, self.pg2, n_rx=2)
@@ -163,7 +172,7 @@ class TestGRO(VppTestCase):
self.assertEqual(rx[IPv6].plen, 64260) # 1460 * 44 + 20 < 65536
self.assertEqual(rx[TCP].sport, 1234)
self.assertEqual(rx[TCP].dport, 4321)
- self.assertEqual(rx[TCP].ack, (44*i - 1))
+ self.assertEqual(rx[TCP].ack, (44 * i - 1))
#
# Send a series of 1500 bytes packets each followed by a packet with a
@@ -172,18 +181,23 @@ class TestGRO(VppTestCase):
p = []
s = 0
for n in range(0, n_packets):
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4,
- flags='DF') /
- TCP(sport=1234, dport=4321, seq=s, ack=2*n, flags='A') /
- Raw(b'\xa5' * 1460)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4, flags="DF")
+ / TCP(sport=1234, dport=4321, seq=s, ack=2 * n, flags="A")
+ / Raw(b"\xa5" * 1460)
+ )
+ )
s += 1460
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4,
- flags='DF') /
- TCP(sport=1234, dport=4321, seq=s, ack=2*n+1,
- flags='AP') /
- Raw(b'\xa5' * 1340)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg2.remote_ip4, flags="DF")
+ / TCP(sport=1234, dport=4321, seq=s, ack=2 * n + 1, flags="AP")
+ / Raw(b"\xa5" * 1340)
+ )
+ )
s += 1340
rxs = self.send_and_expect(self.pg0, p, self.pg2, n_rx=n_packets)
@@ -197,7 +211,7 @@ class TestGRO(VppTestCase):
self.assertEqual(rx[IP].len, 40 + 1460 + 1340)
self.assertEqual(rx[TCP].sport, 1234)
self.assertEqual(rx[TCP].dport, 4321)
- self.assertEqual(rx[TCP].ack, (2*i + 1))
+ self.assertEqual(rx[TCP].ack, (2 * i + 1))
i += 1
#
@@ -209,20 +223,24 @@ class TestGRO(VppTestCase):
s = 0
for n in range(0, n_packets):
i = self.pg0
- p.append((Ether(src=i.remote_mac, dst=i.local_mac) /
- IP(src=i.remote_ip4, dst=self.pg2.remote_ip4,
- flags='DF') /
- TCP(sport=1234, dport=4321, seq=s, ack=2*n, flags='A') /
- Raw(b'\xa5' * 1459)))
+ p.append(
+ (
+ Ether(src=i.remote_mac, dst=i.local_mac)
+ / IP(src=i.remote_ip4, dst=self.pg2.remote_ip4, flags="DF")
+ / TCP(sport=1234, dport=4321, seq=s, ack=2 * n, flags="A")
+ / Raw(b"\xa5" * 1459)
+ )
+ )
s += 1459
- p2 = (Ether(src=i.remote_mac, dst=i.local_mac) /
- IP(src=i.remote_ip4, dst=self.pg2.remote_ip4,
- flags='DF', len=41) /
- TCP(sport=1234, dport=4321, seq=s, ack=2*n+1, flags='A') /
- Raw(b'\xa5'))
+ p2 = (
+ Ether(src=i.remote_mac, dst=i.local_mac)
+ / IP(src=i.remote_ip4, dst=self.pg2.remote_ip4, flags="DF", len=41)
+ / TCP(sport=1234, dport=4321, seq=s, ack=2 * n + 1, flags="A")
+ / Raw(b"\xa5")
+ )
# first compute csum of pkt w/o padding to work around scapy bug
p2 = Ether(bytes(p2))
- p.append(p2 / Raw(b'\xa5' * 5)) # 1 byte data + 5 bytes padding
+ p.append(p2 / Raw(b"\xa5" * 5)) # 1 byte data + 5 bytes padding
s += 1
rxs = self.send_and_expect(self.pg0, p, self.pg2, n_rx=n_packets)
@@ -236,9 +254,9 @@ class TestGRO(VppTestCase):
self.assertEqual(rx[IP].len, 40 + 1459 + 1)
self.assertEqual(rx[TCP].sport, 1234)
self.assertEqual(rx[TCP].dport, 4321)
- self.assertEqual(rx[TCP].ack, (2*i + 1))
+ self.assertEqual(rx[TCP].ack, (2 * i + 1))
i += 1
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_gso.py b/test/test_gso.py
index ee676a41c4a..5368531e539 100644
--- a/test/test_gso.py
+++ b/test/test_gso.py
@@ -30,8 +30,12 @@ from socket import AF_INET, AF_INET6, inet_pton
from util import reassemble4
from vpp_ipsec import VppIpsecSA, VppIpsecTunProtect
-from template_ipsec import IPsecIPv4Params, IPsecIPv6Params, \
- mk_scapy_crypt_key, config_tun_params
+from template_ipsec import (
+ IPsecIPv4Params,
+ IPsecIPv6Params,
+ mk_scapy_crypt_key,
+ config_tun_params,
+)
""" Test_gso is a subclass of VPPTestCase classes.
GSO tests.
@@ -39,7 +43,7 @@ from template_ipsec import IPsecIPv4Params, IPsecIPv6Params, \
class TestGSO(VppTestCase):
- """ GSO Test Case """
+ """GSO Test Case"""
def __init__(self, *args):
VppTestCase.__init__(self, *args)
@@ -70,18 +74,26 @@ class TestGSO(VppTestCase):
i.resolve_ndp()
self.single_tunnel_bd = 10
- self.vxlan = VppVxlanTunnel(self, src=self.pg0.local_ip4,
- dst=self.pg0.remote_ip4,
- vni=self.single_tunnel_bd)
-
- self.vxlan2 = VppVxlanTunnel(self, src=self.pg0.local_ip6,
- dst=self.pg0.remote_ip6,
- vni=self.single_tunnel_bd)
-
- self.ipip4 = VppIpIpTunInterface(self, self.pg0, self.pg0.local_ip4,
- self.pg0.remote_ip4)
- self.ipip6 = VppIpIpTunInterface(self, self.pg0, self.pg0.local_ip6,
- self.pg0.remote_ip6)
+ self.vxlan = VppVxlanTunnel(
+ self,
+ src=self.pg0.local_ip4,
+ dst=self.pg0.remote_ip4,
+ vni=self.single_tunnel_bd,
+ )
+
+ self.vxlan2 = VppVxlanTunnel(
+ self,
+ src=self.pg0.local_ip6,
+ dst=self.pg0.remote_ip6,
+ vni=self.single_tunnel_bd,
+ )
+
+ self.ipip4 = VppIpIpTunInterface(
+ self, self.pg0, self.pg0.local_ip4, self.pg0.remote_ip4
+ )
+ self.ipip6 = VppIpIpTunInterface(
+ self, self.pg0, self.pg0.local_ip6, self.pg0.remote_ip6
+ )
def tearDown(self):
super(TestGSO, self).tearDown()
@@ -92,15 +104,16 @@ class TestGSO(VppTestCase):
i.admin_down()
def test_gso(self):
- """ GSO test """
+ """GSO test"""
#
# Send jumbo frame with gso disabled and DF bit is set
#
- p4 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4,
- flags='DF') /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p4 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, flags="DF")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
rxs = self.send_and_expect(self.pg0, [p4], self.pg0)
@@ -115,13 +128,14 @@ class TestGSO(VppTestCase):
#
# Send checksum offload frames
#
- p40 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4,
- flags='DF') /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 1460))
+ p40 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4, flags="DF")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 1460)
+ )
- rxs = self.send_and_expect(self.pg2, 100*[p40], self.pg0)
+ rxs = self.send_and_expect(self.pg2, 100 * [p40], self.pg0)
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -133,12 +147,14 @@ class TestGSO(VppTestCase):
self.assert_tcp_checksum_valid(rx)
self.assertEqual(payload_len, len(rx[Raw]))
- p60 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6) /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 1440))
+ p60 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6)
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 1440)
+ )
- rxs = self.send_and_expect(self.pg2, 100*[p60], self.pg0)
+ rxs = self.send_and_expect(self.pg2, 100 * [p60], self.pg0)
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -153,15 +169,17 @@ class TestGSO(VppTestCase):
# Send jumbo frame with gso enabled and DF bit is set
# input and output interfaces support GSO
#
- self.vapi.feature_gso_enable_disable(sw_if_index=self.pg3.sw_if_index,
- enable_disable=1)
- p41 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4,
- flags='DF') /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ self.vapi.feature_gso_enable_disable(
+ sw_if_index=self.pg3.sw_if_index, enable_disable=1
+ )
+ p41 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4, flags="DF")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 100*[p41], self.pg3, 100)
+ rxs = self.send_and_expect(self.pg2, 100 * [p41], self.pg3, 100)
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg3.local_mac)
@@ -175,12 +193,14 @@ class TestGSO(VppTestCase):
#
# ipv6
#
- p61 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IPv6(src=self.pg2.remote_ip6, dst=self.pg3.remote_ip6) /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p61 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IPv6(src=self.pg2.remote_ip6, dst=self.pg3.remote_ip6)
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 100*[p61], self.pg3, 100)
+ rxs = self.send_and_expect(self.pg2, 100 * [p61], self.pg3, 100)
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg3.local_mac)
@@ -196,15 +216,17 @@ class TestGSO(VppTestCase):
# and DF bit is set. GSO packet will be chunked into gso_size
# data payload
#
- self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index,
- enable_disable=1)
- p42 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4,
- flags='DF') /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
-
- rxs = self.send_and_expect(self.pg2, 5*[p42], self.pg0, 225)
+ self.vapi.feature_gso_enable_disable(
+ sw_if_index=self.pg0.sw_if_index, enable_disable=1
+ )
+ p42 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_ip4, dst=self.pg0.remote_ip4, flags="DF")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
+
+ rxs = self.send_and_expect(self.pg2, 5 * [p42], self.pg0, 225)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -218,17 +240,19 @@ class TestGSO(VppTestCase):
self.assertEqual(rx[TCP].dport, 1234)
self.assertEqual(payload_len, len(rx[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
#
# ipv6
#
- p62 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6) /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p62 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6)
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 5*[p62], self.pg0, 225)
+ rxs = self.send_and_expect(self.pg2, 5 * [p62], self.pg0, 225)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -241,22 +265,25 @@ class TestGSO(VppTestCase):
self.assertEqual(rx[TCP].dport, 1234)
self.assertEqual(payload_len, len(rx[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
#
# Send jumbo frame with gso enabled only on input interface
# and DF bit is unset. GSO packet will be fragmented.
#
self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [576, 0, 0, 0])
- self.vapi.feature_gso_enable_disable(sw_if_index=self.pg1.sw_if_index,
- enable_disable=1)
+ self.vapi.feature_gso_enable_disable(
+ sw_if_index=self.pg1.sw_if_index, enable_disable=1
+ )
- p43 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p43 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 5*[p43], self.pg1, 5*119)
+ rxs = self.send_and_expect(self.pg2, 5 * [p43], self.pg1, 5 * 119)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg1.local_mac)
@@ -265,8 +292,8 @@ class TestGSO(VppTestCase):
self.assertEqual(rx[IP].dst, self.pg1.remote_ip4)
self.assert_ip_checksum_valid(rx)
size += rx[IP].len - 20
- size -= 20*5 # TCP header
- self.assertEqual(size, 65200*5)
+ size -= 20 * 5 # TCP header
+ self.assertEqual(size, 65200 * 5)
#
# IPv6
@@ -274,12 +301,14 @@ class TestGSO(VppTestCase):
# ICMPv6 Packet Too Big will be sent back to sender.
#
self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1280, 0, 0, 0])
- p63 = (Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac) /
- IPv6(src=self.pg2.remote_ip6, dst=self.pg1.remote_ip6) /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
-
- rxs = self.send_and_expect_some(self.pg2, 5*[p63], self.pg2, 5)
+ p63 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IPv6(src=self.pg2.remote_ip6, dst=self.pg1.remote_ip6)
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
+
+ rxs = self.send_and_expect_some(self.pg2, 5 * [p63], self.pg2, 5)
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg2.local_mac)
self.assertEqual(rx[Ether].dst, self.pg2.remote_mac)
@@ -299,12 +328,14 @@ class TestGSO(VppTestCase):
#
self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [9000, 0, 0, 0])
self.vapi.sw_interface_set_mtu(self.pg4.sw_if_index, [9000, 0, 0, 0])
- p44 = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) /
- IP(src=self.pg4.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
-
- rxs = self.send_and_expect(self.pg4, 5*[p44], self.pg1, 165)
+ p44 = (
+ Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac)
+ / IP(src=self.pg4.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
+
+ rxs = self.send_and_expect(self.pg4, 5 * [p44], self.pg1, 165)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg1.local_mac)
@@ -316,17 +347,19 @@ class TestGSO(VppTestCase):
self.assert_tcp_checksum_valid(rx)
self.assertEqual(payload_len, len(rx[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
#
# IPv6
#
- p64 = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) /
- IPv6(src=self.pg4.remote_ip6, dst=self.pg1.remote_ip6) /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p64 = (
+ Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac)
+ / IPv6(src=self.pg4.remote_ip6, dst=self.pg1.remote_ip6)
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg4, 5*[p64], self.pg1, 170)
+ rxs = self.send_and_expect(self.pg4, 5 * [p64], self.pg1, 170)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg1.local_mac)
@@ -337,15 +370,17 @@ class TestGSO(VppTestCase):
self.assert_tcp_checksum_valid(rx)
self.assertEqual(payload_len, len(rx[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
- self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index,
- enable_disable=0)
- self.vapi.feature_gso_enable_disable(sw_if_index=self.pg1.sw_if_index,
- enable_disable=0)
+ self.vapi.feature_gso_enable_disable(
+ sw_if_index=self.pg0.sw_if_index, enable_disable=0
+ )
+ self.vapi.feature_gso_enable_disable(
+ sw_if_index=self.pg1.sw_if_index, enable_disable=0
+ )
def test_gso_vxlan(self):
- """ GSO VXLAN test """
+ """GSO VXLAN test"""
self.logger.info(self.vapi.cli("sh int addr"))
#
# Send jumbo frame with gso enabled only on input interface and
@@ -358,21 +393,26 @@ class TestGSO(VppTestCase):
#
self.vxlan.add_vpp_config()
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.vxlan.sw_if_index, bd_id=self.single_tunnel_bd)
+ rx_sw_if_index=self.vxlan.sw_if_index, bd_id=self.single_tunnel_bd
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.single_tunnel_bd)
- self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index,
- enable_disable=1)
+ rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.single_tunnel_bd
+ )
+ self.vapi.feature_gso_enable_disable(
+ sw_if_index=self.pg0.sw_if_index, enable_disable=1
+ )
#
# IPv4/IPv4 - VXLAN
#
- p45 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IP(src=self.pg2.remote_ip4, dst="172.16.3.3", flags='DF') /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p45 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IP(src=self.pg2.remote_ip4, dst="172.16.3.3", flags="DF")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 5*[p45], self.pg0, 225)
+ rxs = self.send_and_expect(self.pg2, 5 * [p45], self.pg0, 225)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -393,17 +433,19 @@ class TestGSO(VppTestCase):
payload_len = inner[IP].len - 20 - 20
self.assertEqual(payload_len, len(inner[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
#
# IPv4/IPv6 - VXLAN
#
- p65 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IPv6(src=self.pg2.remote_ip6, dst="fd01:3::3") /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p65 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IPv6(src=self.pg2.remote_ip6, dst="fd01:3::3")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 5*[p65], self.pg0, 225)
+ rxs = self.send_and_expect(self.pg2, 5 * [p65], self.pg0, 225)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -423,7 +465,7 @@ class TestGSO(VppTestCase):
payload_len = inner[IPv6].plen - 20
self.assertEqual(payload_len, len(inner[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
#
# disable ipv4/vxlan
@@ -435,18 +477,20 @@ class TestGSO(VppTestCase):
#
self.vxlan2.add_vpp_config()
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.vxlan2.sw_if_index,
- bd_id=self.single_tunnel_bd)
+ rx_sw_if_index=self.vxlan2.sw_if_index, bd_id=self.single_tunnel_bd
+ )
#
# IPv6/IPv4 - VXLAN
#
- p46 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IP(src=self.pg2.remote_ip4, dst="172.16.3.3", flags='DF') /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p46 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IP(src=self.pg2.remote_ip4, dst="172.16.3.3", flags="DF")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 5*[p46], self.pg0, 225)
+ rxs = self.send_and_expect(self.pg2, 5 * [p46], self.pg0, 225)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -466,17 +510,19 @@ class TestGSO(VppTestCase):
payload_len = inner[IP].len - 20 - 20
self.assertEqual(payload_len, len(inner[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
#
# IPv6/IPv6 - VXLAN
#
- p66 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IPv6(src=self.pg2.remote_ip6, dst="fd01:3::3") /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p66 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IPv6(src=self.pg2.remote_ip6, dst="fd01:3::3")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 5*[p66], self.pg0, 225)
+ rxs = self.send_and_expect(self.pg2, 5 * [p66], self.pg0, 225)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -495,25 +541,27 @@ class TestGSO(VppTestCase):
payload_len = inner[IPv6].plen - 20
self.assertEqual(payload_len, len(inner[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
#
# disable ipv4/vxlan
#
self.vxlan2.remove_vpp_config()
- self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index,
- enable_disable=0)
+ self.vapi.feature_gso_enable_disable(
+ sw_if_index=self.pg0.sw_if_index, enable_disable=0
+ )
def test_gso_ipip(self):
- """ GSO IPIP test """
+ """GSO IPIP test"""
self.logger.info(self.vapi.cli("sh int addr"))
#
# Send jumbo frame with gso enabled only on input interface and
# create IPIP tunnel on VPP pg0.
#
- self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index,
- enable_disable=1)
+ self.vapi.feature_gso_enable_disable(
+ sw_if_index=self.pg0.sw_if_index, enable_disable=1
+ )
#
# enable ipip4
@@ -526,21 +574,30 @@ class TestGSO(VppTestCase):
# Add IPv4 routes via tunnel interface
self.ip4_via_ip4_tunnel = VppIpRoute(
- self, "172.16.10.0", 24,
- [VppRoutePath("0.0.0.0",
- self.ipip4.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)])
+ self,
+ "172.16.10.0",
+ 24,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ self.ipip4.sw_if_index,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ )
+ ],
+ )
self.ip4_via_ip4_tunnel.add_vpp_config()
#
# IPv4/IPv4 - IPIP
#
- p47 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags='DF') /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p47 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags="DF")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 5*[p47], self.pg0, 225)
+ rxs = self.send_and_expect(self.pg2, 5 * [p47], self.pg0, 225)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -558,23 +615,32 @@ class TestGSO(VppTestCase):
payload_len = inner[IP].len - 20 - 20
self.assertEqual(payload_len, len(inner[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
self.ip6_via_ip4_tunnel = VppIpRoute(
- self, "fd01:10::", 64,
- [VppRoutePath("::",
- self.ipip4.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ self,
+ "fd01:10::",
+ 64,
+ [
+ VppRoutePath(
+ "::",
+ self.ipip4.sw_if_index,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
+ ],
+ )
self.ip6_via_ip4_tunnel.add_vpp_config()
#
# IPv4/IPv6 - IPIP
#
- p67 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p67 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 5*[p67], self.pg0, 225)
+ rxs = self.send_and_expect(self.pg2, 5 * [p67], self.pg0, 225)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -591,20 +657,21 @@ class TestGSO(VppTestCase):
payload_len = inner[IPv6].plen - 20
self.assertEqual(payload_len, len(inner[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
#
# Send jumbo frame with gso enabled only on input interface and
# create IPIP tunnel on VPP pg0. Enable gso feature node on ipip
# tunnel - IPSec use case
#
- self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index,
- enable_disable=0)
self.vapi.feature_gso_enable_disable(
- sw_if_index=self.ipip4.sw_if_index,
- enable_disable=1)
+ sw_if_index=self.pg0.sw_if_index, enable_disable=0
+ )
+ self.vapi.feature_gso_enable_disable(
+ sw_if_index=self.ipip4.sw_if_index, enable_disable=1
+ )
- rxs = self.send_and_expect(self.pg2, 5*[p47], self.pg0, 225)
+ rxs = self.send_and_expect(self.pg2, 5 * [p47], self.pg0, 225)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -622,14 +689,14 @@ class TestGSO(VppTestCase):
payload_len = inner[IP].len - 20 - 20
self.assertEqual(payload_len, len(inner[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
#
# disable ipip4
#
self.vapi.feature_gso_enable_disable(
- sw_if_index=self.ipip4.sw_if_index,
- enable_disable=0)
+ sw_if_index=self.ipip4.sw_if_index, enable_disable=0
+ )
self.ip4_via_ip4_tunnel.remove_vpp_config()
self.ip6_via_ip4_tunnel.remove_vpp_config()
self.ipip4.remove_vpp_config()
@@ -637,8 +704,9 @@ class TestGSO(VppTestCase):
#
# enable ipip6
#
- self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index,
- enable_disable=1)
+ self.vapi.feature_gso_enable_disable(
+ sw_if_index=self.pg0.sw_if_index, enable_disable=1
+ )
self.ipip6.add_vpp_config()
# Set interface up and enable IP on it
@@ -647,21 +715,30 @@ class TestGSO(VppTestCase):
# Add IPv4 routes via tunnel interface
self.ip4_via_ip6_tunnel = VppIpRoute(
- self, "172.16.10.0", 24,
- [VppRoutePath("0.0.0.0",
- self.ipip6.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)])
+ self,
+ "172.16.10.0",
+ 24,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ self.ipip6.sw_if_index,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ )
+ ],
+ )
self.ip4_via_ip6_tunnel.add_vpp_config()
#
# IPv6/IPv4 - IPIP
#
- p48 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags='DF') /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p48 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags="DF")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 5*[p48], self.pg0, 225)
+ rxs = self.send_and_expect(self.pg2, 5 * [p48], self.pg0, 225)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -678,24 +755,33 @@ class TestGSO(VppTestCase):
payload_len = inner[IP].len - 20 - 20
self.assertEqual(payload_len, len(inner[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
self.ip6_via_ip6_tunnel = VppIpRoute(
- self, "fd01:10::", 64,
- [VppRoutePath("::",
- self.ipip6.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ self,
+ "fd01:10::",
+ 64,
+ [
+ VppRoutePath(
+ "::",
+ self.ipip6.sw_if_index,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
+ ],
+ )
self.ip6_via_ip6_tunnel.add_vpp_config()
#
# IPv6/IPv6 - IPIP
#
- p68 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ p68 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
- rxs = self.send_and_expect(self.pg2, 5*[p68], self.pg0, 225)
+ rxs = self.send_and_expect(self.pg2, 5 * [p68], self.pg0, 225)
size = 0
for rx in rxs:
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
@@ -711,7 +797,7 @@ class TestGSO(VppTestCase):
payload_len = inner[IPv6].plen - 20
self.assertEqual(payload_len, len(inner[Raw]))
size += payload_len
- self.assertEqual(size, 65200*5)
+ self.assertEqual(size, 65200 * 5)
#
# disable ipip6
@@ -720,11 +806,12 @@ class TestGSO(VppTestCase):
self.ip6_via_ip6_tunnel.remove_vpp_config()
self.ipip6.remove_vpp_config()
- self.vapi.feature_gso_enable_disable(sw_if_index=self.pg0.sw_if_index,
- enable_disable=0)
+ self.vapi.feature_gso_enable_disable(
+ sw_if_index=self.pg0.sw_if_index, enable_disable=0
+ )
def test_gso_ipsec(self):
- """ GSO IPSEC test """
+ """GSO IPSEC test"""
#
# Send jumbo frame with gso enabled only on input interface and
# create IPIP tunnel on VPP pg0.
@@ -735,14 +822,22 @@ class TestGSO(VppTestCase):
#
self.ipip4.add_vpp_config()
self.vapi.feature_gso_enable_disable(
- sw_if_index=self.ipip4.sw_if_index, enable_disable=1)
+ sw_if_index=self.ipip4.sw_if_index, enable_disable=1
+ )
# Add IPv4 routes via tunnel interface
self.ip4_via_ip4_tunnel = VppIpRoute(
- self, "172.16.10.0", 24,
- [VppRoutePath("0.0.0.0",
- self.ipip4.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)])
+ self,
+ "172.16.10.0",
+ 24,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ self.ipip4.sw_if_index,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ )
+ ],
+ )
self.ip4_via_ip4_tunnel.add_vpp_config()
# IPSec config
@@ -750,30 +845,33 @@ class TestGSO(VppTestCase):
self.encryption_type = ESP
config_tun_params(self.ipv4_params, self.encryption_type, self.ipip4)
- self.tun_sa_in_v4 = VppIpsecSA(self, self.ipv4_params.vpp_tun_sa_id,
- self.ipv4_params.vpp_tun_spi,
- self.ipv4_params.auth_algo_vpp_id,
- self.ipv4_params.auth_key,
- self.ipv4_params.crypt_algo_vpp_id,
- self.ipv4_params.crypt_key,
- VppEnum.vl_api_ipsec_proto_t.
- IPSEC_API_PROTO_ESP)
+ self.tun_sa_in_v4 = VppIpsecSA(
+ self,
+ self.ipv4_params.vpp_tun_sa_id,
+ self.ipv4_params.vpp_tun_spi,
+ self.ipv4_params.auth_algo_vpp_id,
+ self.ipv4_params.auth_key,
+ self.ipv4_params.crypt_algo_vpp_id,
+ self.ipv4_params.crypt_key,
+ VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP,
+ )
self.tun_sa_in_v4.add_vpp_config()
- self.tun_sa_out_v4 = VppIpsecSA(self, self.ipv4_params.scapy_tun_sa_id,
- self.ipv4_params.scapy_tun_spi,
- self.ipv4_params.auth_algo_vpp_id,
- self.ipv4_params.auth_key,
- self.ipv4_params.crypt_algo_vpp_id,
- self.ipv4_params.crypt_key,
- VppEnum.vl_api_ipsec_proto_t.
- IPSEC_API_PROTO_ESP)
+ self.tun_sa_out_v4 = VppIpsecSA(
+ self,
+ self.ipv4_params.scapy_tun_sa_id,
+ self.ipv4_params.scapy_tun_spi,
+ self.ipv4_params.auth_algo_vpp_id,
+ self.ipv4_params.auth_key,
+ self.ipv4_params.crypt_algo_vpp_id,
+ self.ipv4_params.crypt_key,
+ VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP,
+ )
self.tun_sa_out_v4.add_vpp_config()
- self.tun_protect_v4 = VppIpsecTunProtect(self,
- self.ipip4,
- self.tun_sa_out_v4,
- [self.tun_sa_in_v4])
+ self.tun_protect_v4 = VppIpsecTunProtect(
+ self, self.ipip4, self.tun_sa_out_v4, [self.tun_sa_in_v4]
+ )
self.tun_protect_v4.add_vpp_config()
@@ -784,10 +882,12 @@ class TestGSO(VppTestCase):
#
# IPv4/IPv4 - IPSEC
#
- ipsec44 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags='DF') /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ ipsec44 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags="DF")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
rxs = self.send_and_expect(self.pg2, [ipsec44], self.pg0, 45)
size = 0
@@ -805,18 +905,27 @@ class TestGSO(VppTestCase):
self.assertEqual(size, 65200)
self.ip6_via_ip4_tunnel = VppIpRoute(
- self, "fd01:10::", 64,
- [VppRoutePath("::",
- self.ipip4.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ self,
+ "fd01:10::",
+ 64,
+ [
+ VppRoutePath(
+ "::",
+ self.ipip4.sw_if_index,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
+ ],
+ )
self.ip6_via_ip4_tunnel.add_vpp_config()
#
# IPv4/IPv6 - IPSEC
#
- ipsec46 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ ipsec46 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
rxs = self.send_and_expect(self.pg2, [ipsec46], self.pg0, 45)
size = 0
@@ -841,8 +950,7 @@ class TestGSO(VppTestCase):
#
# disable ipip4
#
- self.vapi.feature_gso_enable_disable(self.ipip4.sw_if_index,
- enable_disable=0)
+ self.vapi.feature_gso_enable_disable(self.ipip4.sw_if_index, enable_disable=0)
self.ip4_via_ip4_tunnel.remove_vpp_config()
self.ip6_via_ip4_tunnel.remove_vpp_config()
self.ipip4.remove_vpp_config()
@@ -851,8 +959,7 @@ class TestGSO(VppTestCase):
# enable ipip6
#
self.ipip6.add_vpp_config()
- self.vapi.feature_gso_enable_disable(self.ipip6.sw_if_index,
- enable_disable=1)
+ self.vapi.feature_gso_enable_disable(self.ipip6.sw_if_index, enable_disable=1)
# Set interface up and enable IP on it
self.ipip6.admin_up()
@@ -860,50 +967,62 @@ class TestGSO(VppTestCase):
# Add IPv4 routes via tunnel interface
self.ip4_via_ip6_tunnel = VppIpRoute(
- self, "172.16.10.0", 24,
- [VppRoutePath("0.0.0.0",
- self.ipip6.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)])
+ self,
+ "172.16.10.0",
+ 24,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ self.ipip6.sw_if_index,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ )
+ ],
+ )
self.ip4_via_ip6_tunnel.add_vpp_config()
# IPSec config
self.ipv6_params = IPsecIPv6Params()
self.encryption_type = ESP
config_tun_params(self.ipv6_params, self.encryption_type, self.ipip6)
- self.tun_sa_in_v6 = VppIpsecSA(self, self.ipv6_params.vpp_tun_sa_id,
- self.ipv6_params.vpp_tun_spi,
- self.ipv6_params.auth_algo_vpp_id,
- self.ipv6_params.auth_key,
- self.ipv6_params.crypt_algo_vpp_id,
- self.ipv6_params.crypt_key,
- VppEnum.vl_api_ipsec_proto_t.
- IPSEC_API_PROTO_ESP)
+ self.tun_sa_in_v6 = VppIpsecSA(
+ self,
+ self.ipv6_params.vpp_tun_sa_id,
+ self.ipv6_params.vpp_tun_spi,
+ self.ipv6_params.auth_algo_vpp_id,
+ self.ipv6_params.auth_key,
+ self.ipv6_params.crypt_algo_vpp_id,
+ self.ipv6_params.crypt_key,
+ VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP,
+ )
self.tun_sa_in_v6.add_vpp_config()
- self.tun_sa_out_v6 = VppIpsecSA(self, self.ipv6_params.scapy_tun_sa_id,
- self.ipv6_params.scapy_tun_spi,
- self.ipv6_params.auth_algo_vpp_id,
- self.ipv6_params.auth_key,
- self.ipv6_params.crypt_algo_vpp_id,
- self.ipv6_params.crypt_key,
- VppEnum.vl_api_ipsec_proto_t.
- IPSEC_API_PROTO_ESP)
+ self.tun_sa_out_v6 = VppIpsecSA(
+ self,
+ self.ipv6_params.scapy_tun_sa_id,
+ self.ipv6_params.scapy_tun_spi,
+ self.ipv6_params.auth_algo_vpp_id,
+ self.ipv6_params.auth_key,
+ self.ipv6_params.crypt_algo_vpp_id,
+ self.ipv6_params.crypt_key,
+ VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP,
+ )
self.tun_sa_out_v6.add_vpp_config()
- self.tun_protect_v6 = VppIpsecTunProtect(self,
- self.ipip6,
- self.tun_sa_out_v6,
- [self.tun_sa_in_v6])
+ self.tun_protect_v6 = VppIpsecTunProtect(
+ self, self.ipip6, self.tun_sa_out_v6, [self.tun_sa_in_v6]
+ )
self.tun_protect_v6.add_vpp_config()
#
# IPv6/IPv4 - IPSEC
#
- ipsec64 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags='DF') /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ ipsec64 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IP(src=self.pg2.remote_ip4, dst="172.16.10.3", flags="DF")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
rxs = self.send_and_expect(self.pg2, [ipsec64], self.pg0, 45)
size = 0
@@ -921,19 +1040,28 @@ class TestGSO(VppTestCase):
self.assertEqual(size, 65200)
self.ip6_via_ip6_tunnel = VppIpRoute(
- self, "fd01:10::", 64,
- [VppRoutePath("::",
- self.ipip6.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ self,
+ "fd01:10::",
+ 64,
+ [
+ VppRoutePath(
+ "::",
+ self.ipip6.sw_if_index,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
+ ],
+ )
self.ip6_via_ip6_tunnel.add_vpp_config()
#
# IPv6/IPv6 - IPSEC
#
- ipsec66 = (Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79") /
- IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3") /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 65200))
+ ipsec66 = (
+ Ether(src=self.pg2.remote_mac, dst="02:fe:60:1e:a2:79")
+ / IPv6(src=self.pg2.remote_ip6, dst="fd01:10::3")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 65200)
+ )
rxs = self.send_and_expect(self.pg2, [ipsec66], self.pg0, 45)
size = 0
@@ -962,8 +1090,8 @@ class TestGSO(VppTestCase):
self.ip6_via_ip6_tunnel.remove_vpp_config()
self.ipip6.remove_vpp_config()
- self.vapi.feature_gso_enable_disable(self.pg0.sw_if_index,
- enable_disable=0)
+ self.vapi.feature_gso_enable_disable(self.pg0.sw_if_index, enable_disable=0)
+
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_gtpu.py b/test/test_gtpu.py
index e4a2bfa3670..a6d54f53357 100644
--- a/test/test_gtpu.py
+++ b/test/test_gtpu.py
@@ -21,7 +21,7 @@ from vpp_ip import INVALID_INDEX
@tag_fixme_vpp_workers
class TestGtpuUDP(VppTestCase):
- """ GTPU UDP ports Test Case """
+ """GTPU UDP ports Test Case"""
def setUp(self):
super(TestGtpuUDP, self).setUp()
@@ -39,15 +39,16 @@ class TestGtpuUDP(VppTestCase):
def _check_udp_port_ip4(self, enabled=True):
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=self.dport, dport=self.dport, chksum=0))
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ )
self.pg0.add_stream(pkt)
self.pg_start()
- err = self.statistics.get_counter(
- '/err/ip4-udp-lookup/no_listener')[0]
+ err = self.statistics.get_counter("/err/ip4-udp-lookup/no_listener")[0]
if enabled:
self.assertEqual(err, self.ip4_err)
@@ -58,15 +59,16 @@ class TestGtpuUDP(VppTestCase):
def _check_udp_port_ip6(self, enabled=True):
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- UDP(sport=self.dport, dport=self.dport, chksum=0))
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ )
self.pg0.add_stream(pkt)
self.pg_start()
- err = self.statistics.get_counter(
- '/err/ip6-udp-lookup/no_listener')[0]
+ err = self.statistics.get_counter("/err/ip6-udp-lookup/no_listener")[0]
if enabled:
self.assertEqual(err, self.ip6_err)
@@ -76,46 +78,54 @@ class TestGtpuUDP(VppTestCase):
self.ip6_err = err
def test_udp_port(self):
- """ test UDP ports
+ """test UDP ports
Check if there are no udp listeners before gtpu is enabled
"""
# UDP ports should be disabled unless a tunnel is configured
self._check_udp_port_ip4(False)
self._check_udp_port_ip6(False)
- r = self.vapi.gtpu_add_del_tunnel(is_add=True,
- mcast_sw_if_index=0xFFFFFFFF,
- decap_next_index=0xFFFFFFFF,
- src_address=self.pg0.local_ip4,
- dst_address=self.pg0.remote_ip4)
+ r = self.vapi.gtpu_add_del_tunnel(
+ is_add=True,
+ mcast_sw_if_index=0xFFFFFFFF,
+ decap_next_index=0xFFFFFFFF,
+ src_address=self.pg0.local_ip4,
+ dst_address=self.pg0.remote_ip4,
+ )
# UDP port 2152 enabled for ip4
self._check_udp_port_ip4()
- r = self.vapi.gtpu_add_del_tunnel(is_add=True,
- mcast_sw_if_index=0xFFFFFFFF,
- decap_next_index=0xFFFFFFFF,
- src_address=self.pg0.local_ip6,
- dst_address=self.pg0.remote_ip6)
+ r = self.vapi.gtpu_add_del_tunnel(
+ is_add=True,
+ mcast_sw_if_index=0xFFFFFFFF,
+ decap_next_index=0xFFFFFFFF,
+ src_address=self.pg0.local_ip6,
+ dst_address=self.pg0.remote_ip6,
+ )
# UDP port 2152 enabled for ip6
self._check_udp_port_ip6()
- r = self.vapi.gtpu_add_del_tunnel(is_add=False,
- mcast_sw_if_index=0xFFFFFFFF,
- decap_next_index=0xFFFFFFFF,
- src_address=self.pg0.local_ip4,
- dst_address=self.pg0.remote_ip4)
+ r = self.vapi.gtpu_add_del_tunnel(
+ is_add=False,
+ mcast_sw_if_index=0xFFFFFFFF,
+ decap_next_index=0xFFFFFFFF,
+ src_address=self.pg0.local_ip4,
+ dst_address=self.pg0.remote_ip4,
+ )
- r = self.vapi.gtpu_add_del_tunnel(is_add=False,
- mcast_sw_if_index=0xFFFFFFFF,
- decap_next_index=0xFFFFFFFF,
- src_address=self.pg0.local_ip6,
- dst_address=self.pg0.remote_ip6)
+ r = self.vapi.gtpu_add_del_tunnel(
+ is_add=False,
+ mcast_sw_if_index=0xFFFFFFFF,
+ decap_next_index=0xFFFFFFFF,
+ src_address=self.pg0.local_ip6,
+ dst_address=self.pg0.remote_ip6,
+ )
class TestGtpu(BridgeDomain, VppTestCase):
- """ GTPU Test Case """
+ """GTPU Test Case"""
def __init__(self, *args):
BridgeDomain.__init__(self)
@@ -126,14 +136,16 @@ class TestGtpu(BridgeDomain, VppTestCase):
Encapsulate the original payload frame by adding GTPU header with its
UDP, IP and Ethernet fields
"""
- return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=self.dport, dport=self.dport, chksum=0) /
- GTP_U_Header(teid=vni, gtp_type=self.gtp_type, length=150) /
- pkt)
+ return (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ / GTP_U_Header(teid=vni, gtp_type=self.gtp_type, length=150)
+ / pkt
+ )
def ip_range(self, start, end):
- """ range of remote ip's """
+ """range of remote ip's"""
return ip4_range(self.pg0.remote_ip4, start, end)
def encap_mcast(self, pkt, src_ip, src_mac, vni):
@@ -141,11 +153,13 @@ class TestGtpu(BridgeDomain, VppTestCase):
Encapsulate the original payload frame by adding GTPU header with its
UDP, IP and Ethernet fields
"""
- return (Ether(src=src_mac, dst=self.mcast_mac) /
- IP(src=src_ip, dst=self.mcast_ip4) /
- UDP(sport=self.dport, dport=self.dport, chksum=0) /
- GTP_U_Header(teid=vni, gtp_type=self.gtp_type, length=150) /
- pkt)
+ return (
+ Ether(src=src_mac, dst=self.mcast_mac)
+ / IP(src=src_ip, dst=self.mcast_ip4)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ / GTP_U_Header(teid=vni, gtp_type=self.gtp_type, length=150)
+ / pkt
+ )
def decapsulate(self, pkt):
"""
@@ -178,7 +192,7 @@ class TestGtpu(BridgeDomain, VppTestCase):
self.assertEqual(pkt[GTP_U_Header].teid, vni)
def test_encap(self):
- """ Encapsulation test
+ """Encapsulation test
Send frames from pg1
Verify receipt of encapsulated frames on pg0
"""
@@ -197,7 +211,7 @@ class TestGtpu(BridgeDomain, VppTestCase):
# self.assert_eq_pkts(payload, self.frame_reply)
def test_ucast_flood(self):
- """ Unicast flood test
+ """Unicast flood test
Send frames from pg3
Verify receipt of encapsulated frames on pg0
"""
@@ -215,7 +229,7 @@ class TestGtpu(BridgeDomain, VppTestCase):
# self.assert_eq_pkts(payload, self.frame_reply)
def test_mcast_flood(self):
- """ Multicast flood test
+ """Multicast flood test
Send frames from pg2
Verify receipt of encapsulated frames on pg0
"""
@@ -228,8 +242,9 @@ class TestGtpu(BridgeDomain, VppTestCase):
# Pick first received frame and check if it's correctly encapsulated.
out = self.pg0.get_capture(1)
pkt = out[0]
- self.check_encapsulation(pkt, self.mcast_flood_bd,
- local_only=False, mcast_pkt=True)
+ self.check_encapsulation(
+ pkt, self.mcast_flood_bd, local_only=False, mcast_pkt=True
+ )
# payload = self.decapsulate(pkt)
# self.assert_eq_pkts(payload, self.frame_reply)
@@ -240,13 +255,15 @@ class TestGtpu(BridgeDomain, VppTestCase):
ip_range_start = 10
ip_range_end = ip_range_start + n_ucast_tunnels
next_hop_address = cls.pg0.remote_ip4
- for dest_ip4 in ip4_range(next_hop_address, ip_range_start,
- ip_range_end):
+ for dest_ip4 in ip4_range(next_hop_address, ip_range_start, ip_range_end):
# add host route so dest_ip4 will not be resolved
- rip = VppIpRoute(cls, dest_ip4, 32,
- [VppRoutePath(next_hop_address,
- INVALID_INDEX)],
- register=False)
+ rip = VppIpRoute(
+ cls,
+ dest_ip4,
+ 32,
+ [VppRoutePath(next_hop_address, INVALID_INDEX)],
+ register=False,
+ )
rip.add_vpp_config()
r = cls.vapi.gtpu_add_del_tunnel(
is_add=True,
@@ -254,9 +271,11 @@ class TestGtpu(BridgeDomain, VppTestCase):
decap_next_index=0xFFFFFFFF,
src_address=cls.pg0.local_ip4,
dst_address=dest_ip4,
- teid=teid)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=teid)
+ teid=teid,
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=r.sw_if_index, bd_id=teid
+ )
@classmethod
def add_del_shared_mcast_dst_load(cls, is_add):
@@ -274,8 +293,9 @@ class TestGtpu(BridgeDomain, VppTestCase):
dst_address=cls.mcast_ip4,
mcast_sw_if_index=1,
teid=teid,
- is_add=is_add)
- if r.sw_if_index == 0xffffffff:
+ is_add=is_add,
+ )
+ if r.sw_if_index == 0xFFFFFFFF:
raise ValueError("bad sw_if_index: ~0")
@classmethod
@@ -294,16 +314,16 @@ class TestGtpu(BridgeDomain, VppTestCase):
n_distinct_dst_tunnels = 20
ip_range_start = 10
ip_range_end = ip_range_start + n_distinct_dst_tunnels
- for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start,
- ip_range_end):
- teid = int(dest_ip4.split('.')[3])
+ for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, ip_range_end):
+ teid = int(dest_ip4.split(".")[3])
cls.vapi.gtpu_add_del_tunnel(
decap_next_index=0xFFFFFFFF,
src_address=cls.pg0.local_ip4,
dst_address=dest_ip4,
mcast_sw_if_index=1,
teid=teid,
- is_add=is_add)
+ is_add=is_add,
+ )
@classmethod
def add_mcast_tunnels_load(cls):
@@ -324,7 +344,7 @@ class TestGtpu(BridgeDomain, VppTestCase):
try:
cls.dport = 2152
- cls.gtp_type = 0xff
+ cls.gtp_type = 0xFF
# Create 2 pg interfaces.
cls.create_pg_interfaces(range(4))
@@ -338,7 +358,7 @@ class TestGtpu(BridgeDomain, VppTestCase):
cls.pg0.resolve_arp()
# Our Multicast address
- cls.mcast_ip4 = '239.1.1.1'
+ cls.mcast_ip4 = "239.1.1.1"
cls.mcast_mac = util.mcast_ip_to_mac(cls.mcast_ip4)
# Create GTPU VTEP on VPP pg0, and put gtpu_tunnel0 and pg1
@@ -351,28 +371,33 @@ class TestGtpu(BridgeDomain, VppTestCase):
decap_next_index=0xFFFFFFFF,
src_address=cls.pg0.local_ip4,
dst_address=cls.pg0.remote_ip4,
- teid=cls.single_tunnel_vni)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=cls.single_tunnel_bd)
+ teid=cls.single_tunnel_vni,
+ )
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.single_tunnel_bd)
+ rx_sw_if_index=r.sw_if_index, bd_id=cls.single_tunnel_bd
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.single_tunnel_bd
+ )
# Setup teid 2 to test multicast flooding
cls.n_ucast_tunnels = 10
cls.mcast_flood_bd = 12
- cls.create_gtpu_flood_test_bd(cls.mcast_flood_bd,
- cls.n_ucast_tunnels)
+ cls.create_gtpu_flood_test_bd(cls.mcast_flood_bd, cls.n_ucast_tunnels)
r = cls.vapi.gtpu_add_del_tunnel(
is_add=True,
src_address=cls.pg0.local_ip4,
dst_address=cls.mcast_ip4,
mcast_sw_if_index=1,
decap_next_index=0xFFFFFFFF,
- teid=cls.mcast_flood_bd)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=cls.mcast_flood_bd)
+ teid=cls.mcast_flood_bd,
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=r.sw_if_index, bd_id=cls.mcast_flood_bd
+ )
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg2.sw_if_index, bd_id=cls.mcast_flood_bd)
+ rx_sw_if_index=cls.pg2.sw_if_index, bd_id=cls.mcast_flood_bd
+ )
# Add and delete mcast tunnels to check stability
cls.add_shared_mcast_dst_load()
@@ -382,10 +407,10 @@ class TestGtpu(BridgeDomain, VppTestCase):
# Setup teid 3 to test unicast flooding
cls.ucast_flood_bd = 13
- cls.create_gtpu_flood_test_bd(cls.ucast_flood_bd,
- cls.n_ucast_tunnels)
+ cls.create_gtpu_flood_test_bd(cls.ucast_flood_bd, cls.n_ucast_tunnels)
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.pg3.sw_if_index, bd_id=cls.ucast_flood_bd)
+ rx_sw_if_index=cls.pg3.sw_if_index, bd_id=cls.ucast_flood_bd
+ )
except Exception:
super(TestGtpu, cls).tearDownClass()
raise
@@ -409,5 +434,5 @@ class TestGtpu(BridgeDomain, VppTestCase):
self.logger.info(self.vapi.cli("show trace"))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_http.py b/test/test_http.py
index 193eb010a10..30fee5b98c5 100644
--- a/test/test_http.py
+++ b/test/test_http.py
@@ -11,7 +11,7 @@ from vpp_devices import VppTAPInterface
@unittest.skip("Requires root")
class TestHttpTps(VppTestCase):
- """ HTTP test class """
+ """HTTP test class"""
@classmethod
def setUpClass(cls):
@@ -22,21 +22,21 @@ class TestHttpTps(VppTestCase):
super(TestHttpTps, cls).tearDownClass()
def setUp(self):
- self.client_ip4 = '172.0.0.2'
- self.server_ip4 = '172.0.0.1'
- self.vapi.cli(f'create tap id 0 host-ip4-addr {self.client_ip4}/24')
- self.vapi.cli(f'set int ip addr tap0 {self.server_ip4}/24')
- self.vapi.cli('set int state tap0 up')
+ self.client_ip4 = "172.0.0.2"
+ self.server_ip4 = "172.0.0.1"
+ self.vapi.cli(f"create tap id 0 host-ip4-addr {self.client_ip4}/24")
+ self.vapi.cli(f"set int ip addr tap0 {self.server_ip4}/24")
+ self.vapi.cli("set int state tap0 up")
self.vapi.session_enable_disable(is_enable=1)
def test_http_tps(self):
- fname = 'test_file_1M'
- self.vapi.cli('http tps uri tcp://0.0.0.0/8080')
+ fname = "test_file_1M"
+ self.vapi.cli("http tps uri tcp://0.0.0.0/8080")
con = http.client.HTTPConnection(f"{self.server_ip4}", 8080)
- con.request('GET', f'/{fname}')
+ con.request("GET", f"/{fname}")
r = con.getresponse()
self.assertEqual(len(r.read()), 1 << 20)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_igmp.py b/test/test_igmp.py
index f99bdb25c8c..6e9defd4c1d 100644
--- a/test/test_igmp.py
+++ b/test/test_igmp.py
@@ -9,8 +9,15 @@ from scapy.contrib.igmpv3 import IGMPv3, IGMPv3gr, IGMPv3mq, IGMPv3mr
from framework import tag_fixme_vpp_workers
from framework import VppTestCase, VppTestRunner
-from vpp_igmp import find_igmp_state, IGMP_FILTER, IgmpRecord, IGMP_MODE, \
- IgmpSG, VppHostState, wait_for_igmp_event
+from vpp_igmp import (
+ find_igmp_state,
+ IGMP_FILTER,
+ IgmpRecord,
+ IGMP_MODE,
+ IgmpSG,
+ VppHostState,
+ wait_for_igmp_event,
+)
from vpp_ip_route import find_mroute, VppIpTable
@@ -21,7 +28,7 @@ class IgmpMode:
@tag_fixme_vpp_workers
class TestIgmp(VppTestCase):
- """ IGMP Test Case """
+ """IGMP Test Case"""
@classmethod
def setUpClass(cls):
@@ -63,16 +70,16 @@ class TestIgmp(VppTestCase):
self.pg_start()
def test_igmp_flush(self):
- """ IGMP Link Up/down and Flush """
+ """IGMP Link Up/down and Flush"""
#
# FIX THIS. Link down.
#
def test_igmp_enable(self):
- """ IGMP enable/disable on an interface
+ """IGMP enable/disable on an interface
- check for the addition/removal of the IGMP mroutes """
+ check for the addition/removal of the IGMP mroutes"""
self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 1, IGMP_MODE.HOST)
self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 1, IGMP_MODE.HOST)
@@ -83,10 +90,8 @@ class TestIgmp(VppTestCase):
self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 1, IGMP_MODE.HOST)
self.vapi.igmp_enable_disable(self.pg3.sw_if_index, 1, IGMP_MODE.HOST)
- self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32,
- table_id=1))
- self.assertTrue(find_mroute(self, "224.0.0.22", "0.0.0.0", 32,
- table_id=1))
+ self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32, table_id=1))
+ self.assertTrue(find_mroute(self, "224.0.0.22", "0.0.0.0", 32, table_id=1))
self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 0, IGMP_MODE.HOST)
self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 0, IGMP_MODE.HOST)
self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 0, IGMP_MODE.HOST)
@@ -94,10 +99,8 @@ class TestIgmp(VppTestCase):
self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32))
self.assertFalse(find_mroute(self, "224.0.0.22", "0.0.0.0", 32))
- self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32,
- table_id=1))
- self.assertFalse(find_mroute(self, "224.0.0.22", "0.0.0.0", 32,
- table_id=1))
+ self.assertTrue(find_mroute(self, "224.0.0.1", "0.0.0.0", 32, table_id=1))
+ self.assertFalse(find_mroute(self, "224.0.0.22", "0.0.0.0", 32, table_id=1))
def verify_general_query(self, p):
ip = p[IP]
@@ -126,8 +129,9 @@ class TestIgmp(VppTestCase):
self.assertEqual(len(ip.options), 1)
self.assertEqual(ip.options[0].option, 20)
self.assertEqual(ip.proto, 2)
- self.assertEqual(IGMPv3.igmpv3types[rx[IGMPv3].type],
- "Version 3 Membership Report")
+ self.assertEqual(
+ IGMPv3.igmpv3types[rx[IGMPv3].type], "Version 3 Membership Report"
+ )
self.assertEqual(rx[IGMPv3mr].numgrp, len(records))
received = rx[IGMPv3mr].records
@@ -140,26 +144,20 @@ class TestIgmp(VppTestCase):
self.assertEqual(gr.maddr, r.sg.gaddr)
self.assertEqual(len(gr.srcaddrs), len(r.sg.saddrs))
- self.assertEqual(sorted(gr.srcaddrs),
- sorted(r.sg.saddrs))
+ self.assertEqual(sorted(gr.srcaddrs), sorted(r.sg.saddrs))
def add_group(self, itf, sg, n_pkts=2):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- hs = VppHostState(self,
- IGMP_FILTER.INCLUDE,
- itf.sw_if_index,
- sg)
+ hs = VppHostState(self, IGMP_FILTER.INCLUDE, itf.sw_if_index, sg)
hs.add_vpp_config()
capture = itf.get_capture(n_pkts, timeout=10)
# reports are transmitted twice due to default rebostness value=2
- self.verify_report(capture[0],
- [IgmpRecord(sg, "Allow New Sources")]),
- self.verify_report(capture[1],
- [IgmpRecord(sg, "Allow New Sources")]),
+ self.verify_report(capture[0], [IgmpRecord(sg, "Allow New Sources")]),
+ self.verify_report(capture[1], [IgmpRecord(sg, "Allow New Sources")]),
return hs
@@ -170,18 +168,15 @@ class TestIgmp(VppTestCase):
capture = self.pg0.get_capture(1, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(hs.sg, "Block Old Sources")])
+ self.verify_report(capture[0], [IgmpRecord(hs.sg, "Block Old Sources")])
def test_igmp_host(self):
- """ IGMP Host functions """
+ """IGMP Host functions"""
#
# Enable interface for host functions
#
- self.vapi.igmp_enable_disable(self.pg0.sw_if_index,
- 1,
- IGMP_MODE.HOST)
+ self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 1, IGMP_MODE.HOST)
#
# Add one S,G of state and expect a state-change event report
@@ -192,8 +187,7 @@ class TestIgmp(VppTestCase):
# search for the corresponding state created in VPP
dump = self.vapi.igmp_dump(self.pg0.sw_if_index)
self.assertEqual(len(dump), 1)
- self.assertTrue(find_igmp_state(dump, self.pg0,
- "239.1.1.1", "1.1.1.1"))
+ self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", "1.1.1.1"))
#
# Send a general query (to the all router's address)
@@ -201,61 +195,81 @@ class TestIgmp(VppTestCase):
# Pad the query with 0 - some devices in the big wild
# internet are prone to this.
#
- p_g = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst='224.0.0.1', tos=0xc0) /
- IGMPv3(type="Membership Query", mrcode=100) /
- IGMPv3mq(gaddr="0.0.0.0") /
- Raw(b'\x00' * 10))
+ p_g = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="224.0.0.1", tos=0xC0)
+ / IGMPv3(type="Membership Query", mrcode=100)
+ / IGMPv3mq(gaddr="0.0.0.0")
+ / Raw(b"\x00" * 10)
+ )
self.send(self.pg0, p_g)
capture = self.pg0.get_capture(1, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(h1.sg, "Mode Is Include")])
+ self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")])
#
# Group specific query
#
- p_gs = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Membership Query", mrcode=100) /
- IGMPv3mq(gaddr="239.1.1.1"))
+ p_gs = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="239.1.1.1",
+ tos=0xC0,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Membership Query", mrcode=100)
+ / IGMPv3mq(gaddr="239.1.1.1")
+ )
self.send(self.pg0, p_gs)
capture = self.pg0.get_capture(1, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(h1.sg, "Mode Is Include")])
+ self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")])
#
# A group and source specific query, with the source matching
# the source VPP has
#
- p_gs1 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Membership Query", mrcode=100) /
- IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.1"]))
+ p_gs1 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="239.1.1.1",
+ tos=0xC0,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Membership Query", mrcode=100)
+ / IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.1"])
+ )
self.send(self.pg0, p_gs1)
capture = self.pg0.get_capture(1, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(h1.sg, "Mode Is Include")])
+ self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")])
#
# A group and source specific query that reports more sources
# than the packet actually has.
#
- p_gs2 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Membership Query", mrcode=100) /
- IGMPv3mq(gaddr="239.1.1.1", numsrc=4, srcaddrs=["1.1.1.1"]))
+ p_gs2 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="239.1.1.1",
+ tos=0xC0,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Membership Query", mrcode=100)
+ / IGMPv3mq(gaddr="239.1.1.1", numsrc=4, srcaddrs=["1.1.1.1"])
+ )
self.send_and_assert_no_replies(self.pg0, p_gs2, timeout=10)
@@ -263,12 +277,19 @@ class TestIgmp(VppTestCase):
# A group and source specific query, with the source NOT matching
# the source VPP has. There should be no response.
#
- p_gs2 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Membership Query", mrcode=100) /
- IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.2"]))
+ p_gs2 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="239.1.1.1",
+ tos=0xC0,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Membership Query", mrcode=100)
+ / IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.2"])
+ )
self.send_and_assert_no_replies(self.pg0, p_gs2, timeout=10)
@@ -277,19 +298,24 @@ class TestIgmp(VppTestCase):
# one of which matches the source VPP has.
# The report should contain only the source VPP has.
#
- p_gs3 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Membership Query", mrcode=100) /
- IGMPv3mq(gaddr="239.1.1.1",
- srcaddrs=["1.1.1.1", "1.1.1.2", "1.1.1.3"]))
+ p_gs3 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="239.1.1.1",
+ tos=0xC0,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Membership Query", mrcode=100)
+ / IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.1", "1.1.1.2", "1.1.1.3"])
+ )
self.send(self.pg0, p_gs3)
capture = self.pg0.get_capture(1, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(h1.sg, "Mode Is Include")])
+ self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")])
#
# Two source and group specific queries in quick succession, the
@@ -297,13 +323,11 @@ class TestIgmp(VppTestCase):
#
self.send(self.pg0, [p_gs2, p_gs1])
capture = self.pg0.get_capture(1, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(h1.sg, "Mode Is Include")])
+ self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")])
self.send(self.pg0, [p_gs1, p_gs2])
capture = self.pg0.get_capture(1, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(h1.sg, "Mode Is Include")])
+ self.verify_report(capture[0], [IgmpRecord(h1.sg, "Mode Is Include")])
#
# remove state, expect the report for the removal
@@ -316,16 +340,15 @@ class TestIgmp(VppTestCase):
#
# A group with multiple sources
#
- h2 = self.add_group(self.pg0,
- IgmpSG("239.1.1.1",
- ["1.1.1.1", "1.1.1.2", "1.1.1.3"]))
+ h2 = self.add_group(
+ self.pg0, IgmpSG("239.1.1.1", ["1.1.1.1", "1.1.1.2", "1.1.1.3"])
+ )
# search for the corresponding state created in VPP
dump = self.vapi.igmp_dump(self.pg0.sw_if_index)
self.assertEqual(len(dump), 3)
for s in h2.sg.saddrs:
- self.assertTrue(find_igmp_state(dump, self.pg0,
- "239.1.1.1", s))
+ self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", s))
#
# Send a general query (to the all router's address)
# expect VPP to respond with a membership report will all sources
@@ -333,53 +356,76 @@ class TestIgmp(VppTestCase):
self.send(self.pg0, p_g)
capture = self.pg0.get_capture(1, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(h2.sg, "Mode Is Include")])
+ self.verify_report(capture[0], [IgmpRecord(h2.sg, "Mode Is Include")])
#
# Group and source specific query; some present some not
#
- p_gs = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst='239.1.1.1', tos=0xc0,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Membership Query", mrcode=100) /
- IGMPv3mq(gaddr="239.1.1.1",
- srcaddrs=["1.1.1.1", "1.1.1.2", "1.1.1.4"]))
+ p_gs = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="239.1.1.1",
+ tos=0xC0,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Membership Query", mrcode=100)
+ / IGMPv3mq(gaddr="239.1.1.1", srcaddrs=["1.1.1.1", "1.1.1.2", "1.1.1.4"])
+ )
self.send(self.pg0, p_gs)
capture = self.pg0.get_capture(1, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(
- IgmpSG('239.1.1.1', ["1.1.1.1", "1.1.1.2"]),
- "Mode Is Include")])
+ self.verify_report(
+ capture[0],
+ [
+ IgmpRecord(
+ IgmpSG("239.1.1.1", ["1.1.1.1", "1.1.1.2"]), "Mode Is Include"
+ )
+ ],
+ )
#
# add loads more groups
#
- h3 = self.add_group(self.pg0,
- IgmpSG("239.1.1.2",
- ["2.1.1.1", "2.1.1.2", "2.1.1.3"]))
- h4 = self.add_group(self.pg0,
- IgmpSG("239.1.1.3",
- ["3.1.1.1", "3.1.1.2", "3.1.1.3"]))
- h5 = self.add_group(self.pg0,
- IgmpSG("239.1.1.4",
- ["4.1.1.1", "4.1.1.2", "4.1.1.3"]))
- h6 = self.add_group(self.pg0,
- IgmpSG("239.1.1.5",
- ["5.1.1.1", "5.1.1.2", "5.1.1.3"]))
- h7 = self.add_group(self.pg0,
- IgmpSG("239.1.1.6",
- ["6.1.1.1", "6.1.1.2",
- "6.1.1.3", "6.1.1.4",
- "6.1.1.5", "6.1.1.6",
- "6.1.1.7", "6.1.1.8",
- "6.1.1.9", "6.1.1.10",
- "6.1.1.11", "6.1.1.12",
- "6.1.1.13", "6.1.1.14",
- "6.1.1.15", "6.1.1.16"]))
+ h3 = self.add_group(
+ self.pg0, IgmpSG("239.1.1.2", ["2.1.1.1", "2.1.1.2", "2.1.1.3"])
+ )
+ h4 = self.add_group(
+ self.pg0, IgmpSG("239.1.1.3", ["3.1.1.1", "3.1.1.2", "3.1.1.3"])
+ )
+ h5 = self.add_group(
+ self.pg0, IgmpSG("239.1.1.4", ["4.1.1.1", "4.1.1.2", "4.1.1.3"])
+ )
+ h6 = self.add_group(
+ self.pg0, IgmpSG("239.1.1.5", ["5.1.1.1", "5.1.1.2", "5.1.1.3"])
+ )
+ h7 = self.add_group(
+ self.pg0,
+ IgmpSG(
+ "239.1.1.6",
+ [
+ "6.1.1.1",
+ "6.1.1.2",
+ "6.1.1.3",
+ "6.1.1.4",
+ "6.1.1.5",
+ "6.1.1.6",
+ "6.1.1.7",
+ "6.1.1.8",
+ "6.1.1.9",
+ "6.1.1.10",
+ "6.1.1.11",
+ "6.1.1.12",
+ "6.1.1.13",
+ "6.1.1.14",
+ "6.1.1.15",
+ "6.1.1.16",
+ ],
+ ),
+ )
#
# general query.
@@ -390,39 +436,59 @@ class TestIgmp(VppTestCase):
capture = self.pg0.get_capture(1, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(h3.sg, "Mode Is Include"),
- IgmpRecord(h2.sg, "Mode Is Include"),
- IgmpRecord(h6.sg, "Mode Is Include"),
- IgmpRecord(h4.sg, "Mode Is Include"),
- IgmpRecord(h5.sg, "Mode Is Include"),
- IgmpRecord(h7.sg, "Mode Is Include")])
+ self.verify_report(
+ capture[0],
+ [
+ IgmpRecord(h3.sg, "Mode Is Include"),
+ IgmpRecord(h2.sg, "Mode Is Include"),
+ IgmpRecord(h6.sg, "Mode Is Include"),
+ IgmpRecord(h4.sg, "Mode Is Include"),
+ IgmpRecord(h5.sg, "Mode Is Include"),
+ IgmpRecord(h7.sg, "Mode Is Include"),
+ ],
+ )
#
# modify a group to add and remove some sources
#
- h7.sg = IgmpSG("239.1.1.6",
- ["6.1.1.1", "6.1.1.2",
- "6.1.1.5", "6.1.1.6",
- "6.1.1.7", "6.1.1.8",
- "6.1.1.9", "6.1.1.10",
- "6.1.1.11", "6.1.1.12",
- "6.1.1.13", "6.1.1.14",
- "6.1.1.15", "6.1.1.16",
- "6.1.1.17", "6.1.1.18"])
+ h7.sg = IgmpSG(
+ "239.1.1.6",
+ [
+ "6.1.1.1",
+ "6.1.1.2",
+ "6.1.1.5",
+ "6.1.1.6",
+ "6.1.1.7",
+ "6.1.1.8",
+ "6.1.1.9",
+ "6.1.1.10",
+ "6.1.1.11",
+ "6.1.1.12",
+ "6.1.1.13",
+ "6.1.1.14",
+ "6.1.1.15",
+ "6.1.1.16",
+ "6.1.1.17",
+ "6.1.1.18",
+ ],
+ )
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
h7.add_vpp_config()
capture = self.pg0.get_capture(1, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(IgmpSG("239.1.1.6",
- ["6.1.1.17", "6.1.1.18"]),
- "Allow New Sources"),
- IgmpRecord(IgmpSG("239.1.1.6",
- ["6.1.1.3", "6.1.1.4"]),
- "Block Old Sources")])
+ self.verify_report(
+ capture[0],
+ [
+ IgmpRecord(
+ IgmpSG("239.1.1.6", ["6.1.1.17", "6.1.1.18"]), "Allow New Sources"
+ ),
+ IgmpRecord(
+ IgmpSG("239.1.1.6", ["6.1.1.3", "6.1.1.4"]), "Block Old Sources"
+ ),
+ ],
+ )
#
# add an additional groups with many sources so that each group
@@ -435,27 +501,26 @@ class TestIgmp(VppTestCase):
for i in range(128):
src_list.append("10.1.1.%d" % i)
- h8 = self.add_group(self.pg0,
- IgmpSG("238.1.1.1", src_list))
- h9 = self.add_group(self.pg0,
- IgmpSG("238.1.1.2", src_list))
+ h8 = self.add_group(self.pg0, IgmpSG("238.1.1.1", src_list))
+ h9 = self.add_group(self.pg0, IgmpSG("238.1.1.2", src_list))
self.send(self.pg0, p_g)
capture = self.pg0.get_capture(4, timeout=10)
- self.verify_report(capture[0],
- [IgmpRecord(h3.sg, "Mode Is Include"),
- IgmpRecord(h2.sg, "Mode Is Include"),
- IgmpRecord(h6.sg, "Mode Is Include"),
- IgmpRecord(h4.sg, "Mode Is Include"),
- IgmpRecord(h5.sg, "Mode Is Include")])
- self.verify_report(capture[1],
- [IgmpRecord(h8.sg, "Mode Is Include")])
- self.verify_report(capture[2],
- [IgmpRecord(h7.sg, "Mode Is Include")])
- self.verify_report(capture[3],
- [IgmpRecord(h9.sg, "Mode Is Include")])
+ self.verify_report(
+ capture[0],
+ [
+ IgmpRecord(h3.sg, "Mode Is Include"),
+ IgmpRecord(h2.sg, "Mode Is Include"),
+ IgmpRecord(h6.sg, "Mode Is Include"),
+ IgmpRecord(h4.sg, "Mode Is Include"),
+ IgmpRecord(h5.sg, "Mode Is Include"),
+ ],
+ )
+ self.verify_report(capture[1], [IgmpRecord(h8.sg, "Mode Is Include")])
+ self.verify_report(capture[2], [IgmpRecord(h7.sg, "Mode Is Include")])
+ self.verify_report(capture[3], [IgmpRecord(h9.sg, "Mode Is Include")])
#
# drop the MTU further (so a 128 sized group won't fit)
@@ -465,10 +530,12 @@ class TestIgmp(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- h10 = VppHostState(self,
- IGMP_FILTER.INCLUDE,
- self.pg0.sw_if_index,
- IgmpSG("238.1.1.3", src_list))
+ h10 = VppHostState(
+ self,
+ IGMP_FILTER.INCLUDE,
+ self.pg0.sw_if_index,
+ IgmpSG("238.1.1.3", src_list),
+ )
h10.add_vpp_config()
capture = self.pg0.get_capture(2, timeout=10)
@@ -498,32 +565,51 @@ class TestIgmp(VppTestCase):
# ADD STATE ON MORE INTERFACES
#
- self.vapi.igmp_enable_disable(self.pg0.sw_if_index,
- 0,
- IGMP_MODE.HOST)
+ self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 0, IGMP_MODE.HOST)
def test_igmp_router(self):
- """ IGMP Router Functions """
+ """IGMP Router Functions"""
#
# Drop reports when not enabled
#
- p_j = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Version 3 Membership Report") /
- IGMPv3mr(numgrp=1) /
- IGMPv3gr(rtype="Allow New Sources",
- maddr="239.1.1.1", srcaddrs=["10.1.1.1", "10.1.1.2"]))
- p_l = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Version 3 Membership Report") /
- IGMPv3mr(numgrp=1) /
- IGMPv3gr(rtype="Block Old Sources",
- maddr="239.1.1.1", srcaddrs=["10.1.1.1", "10.1.1.2"]))
+ p_j = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="224.0.0.22",
+ tos=0xC0,
+ ttl=1,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Version 3 Membership Report")
+ / IGMPv3mr(numgrp=1)
+ / IGMPv3gr(
+ rtype="Allow New Sources",
+ maddr="239.1.1.1",
+ srcaddrs=["10.1.1.1", "10.1.1.2"],
+ )
+ )
+ p_l = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="224.0.0.22",
+ tos=0xC0,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Version 3 Membership Report")
+ / IGMPv3mr(numgrp=1)
+ / IGMPv3gr(
+ rtype="Block Old Sources",
+ maddr="239.1.1.1",
+ srcaddrs=["10.1.1.1", "10.1.1.2"],
+ )
+ )
self.send(self.pg0, p_j)
self.assertFalse(self.vapi.igmp_dump())
@@ -539,9 +625,7 @@ class TestIgmp(VppTestCase):
#
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.vapi.igmp_enable_disable(self.pg0.sw_if_index,
- 1,
- IGMP_MODE.ROUTER)
+ self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 1, IGMP_MODE.ROUTER)
self.vapi.want_igmp_events(1)
#
@@ -559,26 +643,28 @@ class TestIgmp(VppTestCase):
#
self.send(self.pg0, p_j)
- self.assertTrue(wait_for_igmp_event(self, 1, self.pg0,
- "239.1.1.1", "10.1.1.1", 1))
- self.assertTrue(wait_for_igmp_event(self, 1, self.pg0,
- "239.1.1.1", "10.1.1.2", 1))
+ self.assertTrue(
+ wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.1", 1)
+ )
+ self.assertTrue(
+ wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 1)
+ )
dump = self.vapi.igmp_dump(self.pg0.sw_if_index)
self.assertEqual(len(dump), 2)
- self.assertTrue(find_igmp_state(dump, self.pg0,
- "239.1.1.1", "10.1.1.1"))
- self.assertTrue(find_igmp_state(dump, self.pg0,
- "239.1.1.1", "10.1.1.2"))
+ self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", "10.1.1.1"))
+ self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", "10.1.1.2"))
#
# wait for the per-source timer to expire
# the state should be reaped
# VPP sends a notification that the group has been left
#
- self.assertTrue(wait_for_igmp_event(self, 4, self.pg0,
- "239.1.1.1", "10.1.1.1", 0))
- self.assertTrue(wait_for_igmp_event(self, 1, self.pg0,
- "239.1.1.1", "10.1.1.2", 0))
+ self.assertTrue(
+ wait_for_igmp_event(self, 4, self.pg0, "239.1.1.1", "10.1.1.1", 0)
+ )
+ self.assertTrue(
+ wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 0)
+ )
self.assertFalse(self.vapi.igmp_dump())
#
@@ -589,10 +675,12 @@ class TestIgmp(VppTestCase):
# expired in 3 seconds.
#
self.send(self.pg0, p_j)
- self.assertTrue(wait_for_igmp_event(self, 1, self.pg0,
- "239.1.1.1", "10.1.1.1", 1))
- self.assertTrue(wait_for_igmp_event(self, 1, self.pg0,
- "239.1.1.1", "10.1.1.2", 1))
+ self.assertTrue(
+ wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.1", 1)
+ )
+ self.assertTrue(
+ wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 1)
+ )
dump = self.vapi.igmp_dump(self.pg0.sw_if_index)
self.assertEqual(len(dump), 2)
@@ -600,33 +688,43 @@ class TestIgmp(VppTestCase):
self.verify_general_query(capture[0])
self.verify_general_query(capture[1])
- p_cs = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Version 3 Membership Report") /
- IGMPv3mr(numgrp=1) /
- IGMPv3gr(rtype="Mode Is Include",
- maddr="239.1.1.1", srcaddrs=["10.1.1.1", "10.1.1.2"]))
+ p_cs = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="224.0.0.22",
+ tos=0xC0,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Version 3 Membership Report")
+ / IGMPv3mr(numgrp=1)
+ / IGMPv3gr(
+ rtype="Mode Is Include",
+ maddr="239.1.1.1",
+ srcaddrs=["10.1.1.1", "10.1.1.2"],
+ )
+ )
self.send(self.pg0, p_cs)
self.sleep(2)
dump = self.vapi.igmp_dump(self.pg0.sw_if_index)
self.assertEqual(len(dump), 2)
- self.assertTrue(find_igmp_state(dump, self.pg0,
- "239.1.1.1", "10.1.1.1"))
- self.assertTrue(find_igmp_state(dump, self.pg0,
- "239.1.1.1", "10.1.1.2"))
+ self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", "10.1.1.1"))
+ self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.1", "10.1.1.2"))
#
# wait for the per-source timer to expire
# the state should be reaped
#
- self.assertTrue(wait_for_igmp_event(self, 4, self.pg0,
- "239.1.1.1", "10.1.1.1", 0))
- self.assertTrue(wait_for_igmp_event(self, 1, self.pg0,
- "239.1.1.1", "10.1.1.2", 0))
+ self.assertTrue(
+ wait_for_igmp_event(self, 4, self.pg0, "239.1.1.1", "10.1.1.1", 0)
+ )
+ self.assertTrue(
+ wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 0)
+ )
self.assertFalse(self.vapi.igmp_dump())
#
@@ -635,203 +733,261 @@ class TestIgmp(VppTestCase):
#
self.send(self.pg0, p_j)
- self.assertTrue(wait_for_igmp_event(self, 1, self.pg0,
- "239.1.1.1", "10.1.1.1", 1))
- self.assertTrue(wait_for_igmp_event(self, 1, self.pg0,
- "239.1.1.1", "10.1.1.2", 1))
+ self.assertTrue(
+ wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.1", 1)
+ )
+ self.assertTrue(
+ wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 1)
+ )
dump = self.vapi.igmp_dump(self.pg0.sw_if_index)
self.assertEqual(len(dump), 2)
self.send(self.pg0, p_l)
capture = self.pg0.get_capture(1, timeout=3)
- self.verify_group_query(capture[0], "239.1.1.1",
- ["10.1.1.1", "10.1.1.2"])
+ self.verify_group_query(capture[0], "239.1.1.1", ["10.1.1.1", "10.1.1.2"])
#
# the group specific query drops the timeout to leave (=1) seconds
#
- self.assertTrue(wait_for_igmp_event(self, 2, self.pg0,
- "239.1.1.1", "10.1.1.1", 0))
- self.assertTrue(wait_for_igmp_event(self, 1, self.pg0,
- "239.1.1.1", "10.1.1.2", 0))
+ self.assertTrue(
+ wait_for_igmp_event(self, 2, self.pg0, "239.1.1.1", "10.1.1.1", 0)
+ )
+ self.assertTrue(
+ wait_for_igmp_event(self, 1, self.pg0, "239.1.1.1", "10.1.1.2", 0)
+ )
self.assertFalse(self.vapi.igmp_dump())
self.assertFalse(self.vapi.igmp_dump())
#
# a TO_EX({}) / IN_EX({}) is treated like a (*,G) join
#
- p_j = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Version 3 Membership Report") /
- IGMPv3mr(numgrp=1) /
- IGMPv3gr(rtype="Change To Exclude Mode", maddr="239.1.1.2"))
+ p_j = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="224.0.0.22",
+ tos=0xC0,
+ ttl=1,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Version 3 Membership Report")
+ / IGMPv3mr(numgrp=1)
+ / IGMPv3gr(rtype="Change To Exclude Mode", maddr="239.1.1.2")
+ )
self.send(self.pg0, p_j)
- self.assertTrue(wait_for_igmp_event(self, 1, self.pg0,
- "239.1.1.2", "0.0.0.0", 1))
-
- p_j = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Version 3 Membership Report") /
- IGMPv3mr(numgrp=1) /
- IGMPv3gr(rtype="Mode Is Exclude", maddr="239.1.1.3"))
+ self.assertTrue(
+ wait_for_igmp_event(self, 1, self.pg0, "239.1.1.2", "0.0.0.0", 1)
+ )
+
+ p_j = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="224.0.0.22",
+ tos=0xC0,
+ ttl=1,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Version 3 Membership Report")
+ / IGMPv3mr(numgrp=1)
+ / IGMPv3gr(rtype="Mode Is Exclude", maddr="239.1.1.3")
+ )
self.send(self.pg0, p_j)
- self.assertTrue(wait_for_igmp_event(self, 1, self.pg0,
- "239.1.1.3", "0.0.0.0", 1))
+ self.assertTrue(
+ wait_for_igmp_event(self, 1, self.pg0, "239.1.1.3", "0.0.0.0", 1)
+ )
#
# A 'allow sources' for {} should be ignored as it should
# never be sent.
#
- p_j = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Version 3 Membership Report") /
- IGMPv3mr(numgrp=1) /
- IGMPv3gr(rtype="Allow New Sources", maddr="239.1.1.4"))
+ p_j = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="224.0.0.22",
+ tos=0xC0,
+ ttl=1,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Version 3 Membership Report")
+ / IGMPv3mr(numgrp=1)
+ / IGMPv3gr(rtype="Allow New Sources", maddr="239.1.1.4")
+ )
self.send(self.pg0, p_j)
dump = self.vapi.igmp_dump(self.pg0.sw_if_index)
- self.assertTrue(find_igmp_state(dump, self.pg0,
- "239.1.1.2", "0.0.0.0"))
- self.assertTrue(find_igmp_state(dump, self.pg0,
- "239.1.1.3", "0.0.0.0"))
- self.assertFalse(find_igmp_state(dump, self.pg0,
- "239.1.1.4", "0.0.0.0"))
+ self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.2", "0.0.0.0"))
+ self.assertTrue(find_igmp_state(dump, self.pg0, "239.1.1.3", "0.0.0.0"))
+ self.assertFalse(find_igmp_state(dump, self.pg0, "239.1.1.4", "0.0.0.0"))
#
# a TO_IN({}) and IS_IN({}) are treated like a (*,G) leave
#
self.vapi.cli("set logging class igmp level debug")
- p_l = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Version 3 Membership Report") /
- IGMPv3mr(numgrp=1) /
- IGMPv3gr(rtype="Change To Include Mode", maddr="239.1.1.2"))
+ p_l = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="224.0.0.22",
+ tos=0xC0,
+ ttl=1,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Version 3 Membership Report")
+ / IGMPv3mr(numgrp=1)
+ / IGMPv3gr(rtype="Change To Include Mode", maddr="239.1.1.2")
+ )
self.send(self.pg0, p_l)
- self.assertTrue(wait_for_igmp_event(self, 2, self.pg0,
- "239.1.1.2", "0.0.0.0", 0))
-
- p_l = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Version 3 Membership Report") /
- IGMPv3mr(numgrp=1) /
- IGMPv3gr(rtype="Mode Is Include", maddr="239.1.1.3"))
+ self.assertTrue(
+ wait_for_igmp_event(self, 2, self.pg0, "239.1.1.2", "0.0.0.0", 0)
+ )
+
+ p_l = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(
+ src=self.pg0.remote_ip4,
+ dst="224.0.0.22",
+ tos=0xC0,
+ ttl=1,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Version 3 Membership Report")
+ / IGMPv3mr(numgrp=1)
+ / IGMPv3gr(rtype="Mode Is Include", maddr="239.1.1.3")
+ )
self.send(self.pg0, p_l)
- self.assertTrue(wait_for_igmp_event(self, 2, self.pg0,
- "239.1.1.3", "0.0.0.0", 0))
+ self.assertTrue(
+ wait_for_igmp_event(self, 2, self.pg0, "239.1.1.3", "0.0.0.0", 0)
+ )
self.assertFalse(self.vapi.igmp_dump(self.pg0.sw_if_index))
#
# disable router config
#
- self.vapi.igmp_enable_disable(self.pg0.sw_if_index,
- 0,
- IGMP_MODE.ROUTER)
+ self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 0, IGMP_MODE.ROUTER)
def _create_igmpv3_pck(self, itf, rtype, maddr, srcaddrs):
- p = (Ether(dst=itf.local_mac, src=itf.remote_mac) /
- IP(src=itf.remote_ip4, dst="224.0.0.22", tos=0xc0, ttl=1,
- options=[IPOption(copy_flag=1, optclass="control",
- option="router_alert")]) /
- IGMPv3(type="Version 3 Membership Report") /
- IGMPv3mr(numgrp=1) /
- IGMPv3gr(rtype=rtype,
- maddr=maddr, srcaddrs=srcaddrs))
+ p = (
+ Ether(dst=itf.local_mac, src=itf.remote_mac)
+ / IP(
+ src=itf.remote_ip4,
+ dst="224.0.0.22",
+ tos=0xC0,
+ ttl=1,
+ options=[
+ IPOption(copy_flag=1, optclass="control", option="router_alert")
+ ],
+ )
+ / IGMPv3(type="Version 3 Membership Report")
+ / IGMPv3mr(numgrp=1)
+ / IGMPv3gr(rtype=rtype, maddr=maddr, srcaddrs=srcaddrs)
+ )
return p
def test_igmp_proxy_device(self):
- """ IGMP proxy device """
+ """IGMP proxy device"""
self.pg2.admin_down()
self.pg2.unconfig_ip4()
self.pg2.set_table_ip4(0)
self.pg2.config_ip4()
self.pg2.admin_up()
- self.vapi.cli('test igmp timers query 10 src 3 leave 1')
+ self.vapi.cli("test igmp timers query 10 src 3 leave 1")
# enable IGMP
self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 1, IGMP_MODE.HOST)
- self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 1,
- IGMP_MODE.ROUTER)
- self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 1,
- IGMP_MODE.ROUTER)
+ self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 1, IGMP_MODE.ROUTER)
+ self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 1, IGMP_MODE.ROUTER)
# create IGMP proxy device
self.vapi.igmp_proxy_device_add_del(0, self.pg0.sw_if_index, 1)
- self.vapi.igmp_proxy_device_add_del_interface(0,
- self.pg1.sw_if_index, 1)
- self.vapi.igmp_proxy_device_add_del_interface(0,
- self.pg2.sw_if_index, 1)
+ self.vapi.igmp_proxy_device_add_del_interface(0, self.pg1.sw_if_index, 1)
+ self.vapi.igmp_proxy_device_add_del_interface(0, self.pg2.sw_if_index, 1)
# send join on pg1. join should be proxied by pg0
- p_j = self._create_igmpv3_pck(self.pg1, "Allow New Sources",
- "239.1.1.1", ["10.1.1.1", "10.1.1.2"])
+ p_j = self._create_igmpv3_pck(
+ self.pg1, "Allow New Sources", "239.1.1.1", ["10.1.1.1", "10.1.1.2"]
+ )
self.send(self.pg1, p_j)
capture = self.pg0.get_capture(1, timeout=1)
- self.verify_report(capture[0], [IgmpRecord(IgmpSG("239.1.1.1",
- ["10.1.1.1", "10.1.1.2"]), "Allow New Sources")])
+ self.verify_report(
+ capture[0],
+ [
+ IgmpRecord(
+ IgmpSG("239.1.1.1", ["10.1.1.1", "10.1.1.2"]), "Allow New Sources"
+ )
+ ],
+ )
self.assertTrue(find_mroute(self, "239.1.1.1", "0.0.0.0", 32))
# send join on pg2. join should be proxied by pg0.
# the group should contain only 10.1.1.3 as
# 10.1.1.1 was already reported
- p_j = self._create_igmpv3_pck(self.pg2, "Allow New Sources",
- "239.1.1.1", ["10.1.1.1", "10.1.1.3"])
+ p_j = self._create_igmpv3_pck(
+ self.pg2, "Allow New Sources", "239.1.1.1", ["10.1.1.1", "10.1.1.3"]
+ )
self.send(self.pg2, p_j)
capture = self.pg0.get_capture(1, timeout=1)
- self.verify_report(capture[0], [IgmpRecord(IgmpSG("239.1.1.1",
- ["10.1.1.3"]), "Allow New Sources")])
+ self.verify_report(
+ capture[0],
+ [IgmpRecord(IgmpSG("239.1.1.1", ["10.1.1.3"]), "Allow New Sources")],
+ )
self.assertTrue(find_mroute(self, "239.1.1.1", "0.0.0.0", 32))
# send leave on pg2. leave for 10.1.1.3 should be proxyed
# as pg2 was the only interface interested in 10.1.1.3
- p_l = self._create_igmpv3_pck(self.pg2, "Block Old Sources",
- "239.1.1.1", ["10.1.1.3"])
+ p_l = self._create_igmpv3_pck(
+ self.pg2, "Block Old Sources", "239.1.1.1", ["10.1.1.3"]
+ )
self.send(self.pg2, p_l)
capture = self.pg0.get_capture(1, timeout=2)
- self.verify_report(capture[0], [IgmpRecord(IgmpSG("239.1.1.1",
- ["10.1.1.3"]), "Block Old Sources")])
+ self.verify_report(
+ capture[0],
+ [IgmpRecord(IgmpSG("239.1.1.1", ["10.1.1.3"]), "Block Old Sources")],
+ )
self.assertTrue(find_mroute(self, "239.1.1.1", "0.0.0.0", 32))
# disable igmp on pg1 (also removes interface from proxy device)
# proxy leave for 10.1.1.2. pg2 is still interested in 10.1.1.1
self.pg_enable_capture(self.pg_interfaces)
- self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 0,
- IGMP_MODE.ROUTER)
+ self.vapi.igmp_enable_disable(self.pg1.sw_if_index, 0, IGMP_MODE.ROUTER)
capture = self.pg0.get_capture(1, timeout=1)
- self.verify_report(capture[0], [IgmpRecord(IgmpSG("239.1.1.1",
- ["10.1.1.2"]), "Block Old Sources")])
+ self.verify_report(
+ capture[0],
+ [IgmpRecord(IgmpSG("239.1.1.1", ["10.1.1.2"]), "Block Old Sources")],
+ )
self.assertTrue(find_mroute(self, "239.1.1.1", "0.0.0.0", 32))
# disable IGMP on pg0 and pg1.
# disabling IGMP on pg0 (proxy device upstream interface)
# removes this proxy device
self.vapi.igmp_enable_disable(self.pg0.sw_if_index, 0, IGMP_MODE.HOST)
- self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 0,
- IGMP_MODE.ROUTER)
+ self.vapi.igmp_enable_disable(self.pg2.sw_if_index, 0, IGMP_MODE.ROUTER)
self.assertFalse(find_mroute(self, "239.1.1.1", "0.0.0.0", 32))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ikev2.py b/test/test_ikev2.py
index 58a7ec3cd9a..5b699dd0d8d 100644
--- a/test/test_ikev2.py
+++ b/test/test_ikev2.py
@@ -38,7 +38,9 @@ GCM_IV_SIZE = 8
# defined in rfc3526
# tuple structure is (p, g, key_len)
DH = {
- '2048MODPgr': (long_converter("""
+ "2048MODPgr": (
+ long_converter(
+ """
FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1
29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD
EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245
@@ -49,9 +51,14 @@ DH = {
670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B
E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9
DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510
- 15728E5A 8AACAA68 FFFFFFFF FFFFFFFF"""), 2, 256),
-
- '3072MODPgr': (long_converter("""
+ 15728E5A 8AACAA68 FFFFFFFF FFFFFFFF"""
+ ),
+ 2,
+ 256,
+ ),
+ "3072MODPgr": (
+ long_converter(
+ """
FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1
29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD
EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245
@@ -67,7 +74,11 @@ DH = {
ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B
F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C
BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31
- 43DB5BFC E0FD108E 4B82D120 A93AD2CA FFFFFFFF FFFFFFFF"""), 2, 384)
+ 43DB5BFC E0FD108E 4B82D120 A93AD2CA FFFFFFFF FFFFFFFF"""
+ ),
+ 2,
+ 384,
+ ),
}
@@ -79,7 +90,7 @@ class CryptoAlgo(object):
if self.cipher is not None:
self.bs = self.cipher.block_size // 8
- if self.name == 'AES-GCM-16ICV':
+ if self.name == "AES-GCM-16ICV":
self.iv_len = GCM_IV_SIZE
else:
self.iv_len = self.bs
@@ -87,14 +98,16 @@ class CryptoAlgo(object):
def encrypt(self, data, key, aad=None):
iv = os.urandom(self.iv_len)
if aad is None:
- encryptor = Cipher(self.cipher(key), self.mode(iv),
- default_backend()).encryptor()
+ encryptor = Cipher(
+ self.cipher(key), self.mode(iv), default_backend()
+ ).encryptor()
return iv + encryptor.update(data) + encryptor.finalize()
else:
salt = key[-SALT_SIZE:]
nonce = salt + iv
- encryptor = Cipher(self.cipher(key[:-SALT_SIZE]), self.mode(nonce),
- default_backend()).encryptor()
+ encryptor = Cipher(
+ self.cipher(key[:-SALT_SIZE]), self.mode(nonce), default_backend()
+ ).encryptor()
encryptor.authenticate_additional_data(aad)
data = encryptor.update(data) + encryptor.finalize()
data += encryptor.tag[:GCM_ICV_SIZE]
@@ -102,26 +115,26 @@ class CryptoAlgo(object):
def decrypt(self, data, key, aad=None, icv=None):
if aad is None:
- iv = data[:self.iv_len]
- ct = data[self.iv_len:]
- decryptor = Cipher(algorithms.AES(key),
- self.mode(iv),
- default_backend()).decryptor()
+ iv = data[: self.iv_len]
+ ct = data[self.iv_len :]
+ decryptor = Cipher(
+ algorithms.AES(key), self.mode(iv), default_backend()
+ ).decryptor()
return decryptor.update(ct) + decryptor.finalize()
else:
salt = key[-SALT_SIZE:]
nonce = salt + data[:GCM_IV_SIZE]
ct = data[GCM_IV_SIZE:]
key = key[:-SALT_SIZE]
- decryptor = Cipher(algorithms.AES(key),
- self.mode(nonce, icv, len(icv)),
- default_backend()).decryptor()
+ decryptor = Cipher(
+ algorithms.AES(key), self.mode(nonce, icv, len(icv)), default_backend()
+ ).decryptor()
decryptor.authenticate_additional_data(aad)
return decryptor.update(ct) + decryptor.finalize()
def pad(self, data):
pad_len = (len(data) // self.bs + 1) * self.bs - len(data)
- data = data + b'\x00' * (pad_len - 1)
+ data = data + b"\x00" * (pad_len - 1)
return data + bytes([pad_len - 1])
@@ -135,36 +148,34 @@ class AuthAlgo(object):
CRYPTO_ALGOS = {
- 'NULL': CryptoAlgo('NULL', cipher=None, mode=None),
- 'AES-CBC': CryptoAlgo('AES-CBC', cipher=algorithms.AES, mode=modes.CBC),
- 'AES-GCM-16ICV': CryptoAlgo('AES-GCM-16ICV', cipher=algorithms.AES,
- mode=modes.GCM),
+ "NULL": CryptoAlgo("NULL", cipher=None, mode=None),
+ "AES-CBC": CryptoAlgo("AES-CBC", cipher=algorithms.AES, mode=modes.CBC),
+ "AES-GCM-16ICV": CryptoAlgo("AES-GCM-16ICV", cipher=algorithms.AES, mode=modes.GCM),
}
AUTH_ALGOS = {
- 'NULL': AuthAlgo('NULL', mac=None, mod=None, key_len=0, trunc_len=0),
- 'HMAC-SHA1-96': AuthAlgo('HMAC-SHA1-96', hmac.HMAC, hashes.SHA1, 20, 12),
- 'SHA2-256-128': AuthAlgo('SHA2-256-128', hmac.HMAC, hashes.SHA256, 32, 16),
- 'SHA2-384-192': AuthAlgo('SHA2-384-192', hmac.HMAC, hashes.SHA256, 48, 24),
- 'SHA2-512-256': AuthAlgo('SHA2-512-256', hmac.HMAC, hashes.SHA256, 64, 32),
+ "NULL": AuthAlgo("NULL", mac=None, mod=None, key_len=0, trunc_len=0),
+ "HMAC-SHA1-96": AuthAlgo("HMAC-SHA1-96", hmac.HMAC, hashes.SHA1, 20, 12),
+ "SHA2-256-128": AuthAlgo("SHA2-256-128", hmac.HMAC, hashes.SHA256, 32, 16),
+ "SHA2-384-192": AuthAlgo("SHA2-384-192", hmac.HMAC, hashes.SHA256, 48, 24),
+ "SHA2-512-256": AuthAlgo("SHA2-512-256", hmac.HMAC, hashes.SHA256, 64, 32),
}
PRF_ALGOS = {
- 'NULL': AuthAlgo('NULL', mac=None, mod=None, key_len=0, trunc_len=0),
- 'PRF_HMAC_SHA2_256': AuthAlgo('PRF_HMAC_SHA2_256', hmac.HMAC,
- hashes.SHA256, 32),
+ "NULL": AuthAlgo("NULL", mac=None, mod=None, key_len=0, trunc_len=0),
+ "PRF_HMAC_SHA2_256": AuthAlgo("PRF_HMAC_SHA2_256", hmac.HMAC, hashes.SHA256, 32),
}
CRYPTO_IDS = {
- 12: 'AES-CBC',
- 20: 'AES-GCM-16ICV',
+ 12: "AES-CBC",
+ 20: "AES-GCM-16ICV",
}
INTEG_IDS = {
- 2: 'HMAC-SHA1-96',
- 12: 'SHA2-256-128',
- 13: 'SHA2-384-192',
- 14: 'SHA2-512-256',
+ 2: "HMAC-SHA1-96",
+ 12: "SHA2-256-128",
+ 13: "SHA2-384-192",
+ 14: "SHA2-512-256",
}
@@ -182,11 +193,24 @@ class IKEv2ChildSA(object):
class IKEv2SA(object):
- def __init__(self, test, is_initiator=True, i_id=None, r_id=None,
- spi=b'\x01\x02\x03\x04\x05\x06\x07\x08', id_type='fqdn',
- nonce=None, auth_data=None, local_ts=None, remote_ts=None,
- auth_method='shared-key', priv_key=None, i_natt=False,
- r_natt=False, udp_encap=False):
+ def __init__(
+ self,
+ test,
+ is_initiator=True,
+ i_id=None,
+ r_id=None,
+ spi=b"\x01\x02\x03\x04\x05\x06\x07\x08",
+ id_type="fqdn",
+ nonce=None,
+ auth_data=None,
+ local_ts=None,
+ remote_ts=None,
+ auth_method="shared-key",
+ priv_key=None,
+ i_natt=False,
+ r_natt=False,
+ udp_encap=False,
+ ):
self.udp_encap = udp_encap
self.i_natt = i_natt
self.r_natt = r_natt
@@ -211,15 +235,14 @@ class IKEv2SA(object):
self.id_type = id_type
self.auth_method = auth_method
if self.is_initiator:
- self.rspi = 8 * b'\x00'
+ self.rspi = 8 * b"\x00"
self.ispi = spi
self.i_nonce = nonce
else:
self.rspi = spi
- self.ispi = 8 * b'\x00'
+ self.ispi = 8 * b"\x00"
self.r_nonce = nonce
- self.child_sas = [IKEv2ChildSA(local_ts, remote_ts,
- self.is_initiator)]
+ self.child_sas = [IKEv2ChildSA(local_ts, remote_ts, self.is_initiator)]
def new_msg_id(self):
self.msg_id += 1
@@ -245,13 +268,14 @@ class IKEv2SA(object):
priv = self.dh_private_key
peer = self.peer_dh_pub_key
p, g, l = self.ike_group
- return pow(int.from_bytes(peer, 'big'),
- int.from_bytes(priv, 'big'), p).to_bytes(l, 'big')
+ return pow(
+ int.from_bytes(peer, "big"), int.from_bytes(priv, "big"), p
+ ).to_bytes(l, "big")
def generate_dh_data(self):
# generate DH keys
if self.ike_dh not in DH:
- raise NotImplementedError('%s not in DH group' % self.ike_dh)
+ raise NotImplementedError("%s not in DH group" % self.ike_dh)
if self.dh_params is None:
dhg = DH[self.ike_dh]
@@ -261,13 +285,13 @@ class IKEv2SA(object):
priv = self.dh_params.generate_private_key()
pub = priv.public_key()
x = priv.private_numbers().x
- self.dh_private_key = x.to_bytes(priv.key_size // 8, 'big')
+ self.dh_private_key = x.to_bytes(priv.key_size // 8, "big")
y = pub.public_numbers().y
if self.is_initiator:
- self.i_dh_data = y.to_bytes(pub.key_size // 8, 'big')
+ self.i_dh_data = y.to_bytes(pub.key_size // 8, "big")
else:
- self.r_dh_data = y.to_bytes(pub.key_size // 8, 'big')
+ self.r_dh_data = y.to_bytes(pub.key_size // 8, "big")
def complete_dh_data(self):
self.dh_shared_secret = self.compute_secret()
@@ -281,41 +305,39 @@ class IKEv2SA(object):
integ_key_len = self.esp_integ_alg.key_len
salt_len = 0 if integ_key_len else 4
- l = (integ_key_len * 2 +
- encr_key_len * 2 +
- salt_len * 2)
+ l = integ_key_len * 2 + encr_key_len * 2 + salt_len * 2
keymat = self.calc_prfplus(prf, self.sk_d, s, l)
pos = 0
- c.sk_ei = keymat[pos:pos+encr_key_len]
+ c.sk_ei = keymat[pos : pos + encr_key_len]
pos += encr_key_len
if integ_key_len:
- c.sk_ai = keymat[pos:pos+integ_key_len]
+ c.sk_ai = keymat[pos : pos + integ_key_len]
pos += integ_key_len
else:
- c.salt_ei = keymat[pos:pos+salt_len]
+ c.salt_ei = keymat[pos : pos + salt_len]
pos += salt_len
- c.sk_er = keymat[pos:pos+encr_key_len]
+ c.sk_er = keymat[pos : pos + encr_key_len]
pos += encr_key_len
if integ_key_len:
- c.sk_ar = keymat[pos:pos+integ_key_len]
+ c.sk_ar = keymat[pos : pos + integ_key_len]
pos += integ_key_len
else:
- c.salt_er = keymat[pos:pos+salt_len]
+ c.salt_er = keymat[pos : pos + salt_len]
pos += salt_len
def calc_prfplus(self, prf, key, seed, length):
- r = b''
+ r = b""
t = None
x = 1
while len(r) < length and x < 255:
if t is not None:
s = t
else:
- s = b''
+ s = b""
s = s + seed + bytes([x])
t = self.calc_prf(prf, key, s)
r = r + t
@@ -348,30 +370,32 @@ class IKEv2SA(object):
else:
salt_size = 0
- l = (prf_key_trunc +
- integ_key_len * 2 +
- encr_key_len * 2 +
- tr_prf_key_len * 2 +
- salt_size * 2)
+ l = (
+ prf_key_trunc
+ + integ_key_len * 2
+ + encr_key_len * 2
+ + tr_prf_key_len * 2
+ + salt_size * 2
+ )
keymat = self.calc_prfplus(prf, self.skeyseed, s, l)
pos = 0
- self.sk_d = keymat[:pos+prf_key_trunc]
+ self.sk_d = keymat[: pos + prf_key_trunc]
pos += prf_key_trunc
- self.sk_ai = keymat[pos:pos+integ_key_len]
+ self.sk_ai = keymat[pos : pos + integ_key_len]
pos += integ_key_len
- self.sk_ar = keymat[pos:pos+integ_key_len]
+ self.sk_ar = keymat[pos : pos + integ_key_len]
pos += integ_key_len
- self.sk_ei = keymat[pos:pos+encr_key_len + salt_size]
+ self.sk_ei = keymat[pos : pos + encr_key_len + salt_size]
pos += encr_key_len + salt_size
- self.sk_er = keymat[pos:pos+encr_key_len + salt_size]
+ self.sk_er = keymat[pos : pos + encr_key_len + salt_size]
pos += encr_key_len + salt_size
- self.sk_pi = keymat[pos:pos+tr_prf_key_len]
+ self.sk_pi = keymat[pos : pos + tr_prf_key_len]
pos += tr_prf_key_len
- self.sk_pr = keymat[pos:pos+tr_prf_key_len]
+ self.sk_pr = keymat[pos : pos + tr_prf_key_len]
def generate_authmsg(self, prf, packet):
if self.is_initiator:
@@ -393,14 +417,15 @@ class IKEv2SA(object):
else:
packet = self.init_resp_packet
authmsg = self.generate_authmsg(prf, raw(packet))
- if self.auth_method == 'shared-key':
+ if self.auth_method == "shared-key":
psk = self.calc_prf(prf, self.auth_data, KEY_PAD)
self.auth_data = self.calc_prf(prf, psk, authmsg)
- elif self.auth_method == 'rsa-sig':
- self.auth_data = self.priv_key.sign(authmsg, padding.PKCS1v15(),
- hashes.SHA1())
+ elif self.auth_method == "rsa-sig":
+ self.auth_data = self.priv_key.sign(
+ authmsg, padding.PKCS1v15(), hashes.SHA1()
+ )
else:
- raise TypeError('unknown auth method type!')
+ raise TypeError("unknown auth method type!")
def encrypt(self, data, aad=None):
data = self.ike_crypto_alg.pad(data)
@@ -431,7 +456,7 @@ class IKEv2SA(object):
return self.sk_ei
def concat(self, alg, key_len):
- return alg + '-' + str(key_len * 8)
+ return alg + "-" + str(key_len * 8)
@property
def vpp_ike_cypto_alg(self):
@@ -445,8 +470,9 @@ class IKEv2SA(object):
integ_trunc = self.ike_integ_alg.trunc_len
exp_hmac = ikemsg[-integ_trunc:]
data = ikemsg[:-integ_trunc]
- computed_hmac = self.compute_hmac(self.ike_integ_alg.mod(),
- self.peer_authkey, data)
+ computed_hmac = self.compute_hmac(
+ self.ike_integ_alg.mod(), self.peer_authkey, data
+ )
self.test.assertEqual(computed_hmac[:integ_trunc], exp_hmac)
def compute_hmac(self, integ, key, data):
@@ -459,7 +485,7 @@ class IKEv2SA(object):
def hmac_and_decrypt(self, ike):
ep = ike[ikev2.IKEv2_payload_Encrypted]
- if self.ike_crypto == 'AES-GCM-16ICV':
+ if self.ike_crypto == "AES-GCM-16ICV":
aad_len = len(ikev2.IKEv2_payload_Encrypted()) + len(ikev2.IKEv2())
ct = ep.load[:-GCM_ICV_SIZE]
tag = ep.load[-GCM_ICV_SIZE:]
@@ -473,26 +499,26 @@ class IKEv2SA(object):
plain = self.decrypt(ct)
# remove padding
pad_len = plain[-1]
- return plain[:-pad_len - 1]
+ return plain[: -pad_len - 1]
def build_ts_addr(self, ts, version):
- return {'starting_address_v' + version: ts['start_addr'],
- 'ending_address_v' + version: ts['end_addr']}
+ return {
+ "starting_address_v" + version: ts["start_addr"],
+ "ending_address_v" + version: ts["end_addr"],
+ }
def generate_ts(self, is_ip4):
c = self.child_sas[0]
- ts_data = {'IP_protocol_ID': 0,
- 'start_port': 0,
- 'end_port': 0xffff}
+ ts_data = {"IP_protocol_ID": 0, "start_port": 0, "end_port": 0xFFFF}
if is_ip4:
- ts_data.update(self.build_ts_addr(c.local_ts, '4'))
+ ts_data.update(self.build_ts_addr(c.local_ts, "4"))
ts1 = ikev2.IPv4TrafficSelector(**ts_data)
- ts_data.update(self.build_ts_addr(c.remote_ts, '4'))
+ ts_data.update(self.build_ts_addr(c.remote_ts, "4"))
ts2 = ikev2.IPv4TrafficSelector(**ts_data)
else:
- ts_data.update(self.build_ts_addr(c.local_ts, '6'))
+ ts_data.update(self.build_ts_addr(c.local_ts, "6"))
ts1 = ikev2.IPv6TrafficSelector(**ts_data)
- ts_data.update(self.build_ts_addr(c.remote_ts, '6'))
+ ts_data.update(self.build_ts_addr(c.remote_ts, "6"))
ts2 = ikev2.IPv6TrafficSelector(**ts_data)
if self.is_initiator:
@@ -501,18 +527,18 @@ class IKEv2SA(object):
def set_ike_props(self, crypto, crypto_key_len, integ, prf, dh):
if crypto not in CRYPTO_ALGOS:
- raise TypeError('unsupported encryption algo %r' % crypto)
+ raise TypeError("unsupported encryption algo %r" % crypto)
self.ike_crypto = crypto
self.ike_crypto_alg = CRYPTO_ALGOS[crypto]
self.ike_crypto_key_len = crypto_key_len
if integ not in AUTH_ALGOS:
- raise TypeError('unsupported auth algo %r' % integ)
- self.ike_integ = None if integ == 'NULL' else integ
+ raise TypeError("unsupported auth algo %r" % integ)
+ self.ike_integ = None if integ == "NULL" else integ
self.ike_integ_alg = AUTH_ALGOS[integ]
if prf not in PRF_ALGOS:
- raise TypeError('unsupported prf algo %r' % prf)
+ raise TypeError("unsupported prf algo %r" % prf)
self.ike_prf = prf
self.ike_prf_alg = PRF_ALGOS[prf]
self.ike_dh = dh
@@ -521,20 +547,20 @@ class IKEv2SA(object):
def set_esp_props(self, crypto, crypto_key_len, integ):
self.esp_crypto_key_len = crypto_key_len
if crypto not in CRYPTO_ALGOS:
- raise TypeError('unsupported encryption algo %r' % crypto)
+ raise TypeError("unsupported encryption algo %r" % crypto)
self.esp_crypto = crypto
self.esp_crypto_alg = CRYPTO_ALGOS[crypto]
if integ not in AUTH_ALGOS:
- raise TypeError('unsupported auth algo %r' % integ)
- self.esp_integ = None if integ == 'NULL' else integ
+ raise TypeError("unsupported auth algo %r" % integ)
+ self.esp_integ = None if integ == "NULL" else integ
self.esp_integ_alg = AUTH_ALGOS[integ]
def crypto_attr(self, key_len):
- if self.ike_crypto in ['AES-CBC', 'AES-GCM-16ICV']:
- return (0x800e << 16 | key_len << 3, 12)
+ if self.ike_crypto in ["AES-CBC", "AES-GCM-16ICV"]:
+ return (0x800E << 16 | key_len << 3, 12)
else:
- raise Exception('unsupported attribute type')
+ raise Exception("unsupported attribute type")
def ike_crypto_attr(self):
return self.crypto_attr(self.ike_crypto_key_len)
@@ -545,19 +571,20 @@ class IKEv2SA(object):
def compute_nat_sha1(self, ip, port, rspi=None):
if rspi is None:
rspi = self.rspi
- data = self.ispi + rspi + ip + (port).to_bytes(2, 'big')
+ data = self.ispi + rspi + ip + (port).to_bytes(2, "big")
digest = hashes.Hash(hashes.SHA1(), backend=default_backend())
digest.update(data)
return digest.finalize()
class IkePeer(VppTestCase):
- """ common class for initiator and responder """
+ """common class for initiator and responder"""
@classmethod
def setUpClass(cls):
import scapy.contrib.ikev2 as _ikev2
- globals()['ikev2'] = _ikev2
+
+ globals()["ikev2"] = _ikev2
super(IkePeer, cls).setUpClass()
cls.create_pg_interfaces(range(2))
for i in cls.pg_interfaces:
@@ -591,36 +618,46 @@ class IkePeer(VppTestCase):
self.assertIsNotNone(self.p.query_vpp_config())
if self.sa.is_initiator:
self.sa.generate_dh_data()
- self.vapi.cli('ikev2 set logging level 4')
- self.vapi.cli('event-lo clear')
+ self.vapi.cli("ikev2 set logging level 4")
+ self.vapi.cli("event-lo clear")
- def assert_counter(self, count, name, version='ip4'):
- node_name = '/err/ikev2-%s/' % version + name
+ def assert_counter(self, count, name, version="ip4"):
+ node_name = "/err/ikev2-%s/" % version + name
self.assertEqual(count, self.statistics.get_err_counter(node_name))
def create_rekey_request(self):
sa, first_payload = self.generate_auth_payload(is_rekey=True)
header = ikev2.IKEv2(
- init_SPI=self.sa.ispi,
- resp_SPI=self.sa.rspi, id=self.sa.new_msg_id(),
- flags='Initiator', exch_type='CREATE_CHILD_SA')
+ init_SPI=self.sa.ispi,
+ resp_SPI=self.sa.rspi,
+ id=self.sa.new_msg_id(),
+ flags="Initiator",
+ exch_type="CREATE_CHILD_SA",
+ )
ike_msg = self.encrypt_ike_msg(header, sa, first_payload)
- return self.create_packet(self.pg0, ike_msg, self.sa.sport,
- self.sa.dport, self.sa.natt, self.ip6)
+ return self.create_packet(
+ self.pg0, ike_msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6
+ )
def create_empty_request(self):
- header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi,
- id=self.sa.new_msg_id(), flags='Initiator',
- exch_type='INFORMATIONAL',
- next_payload='Encrypted')
-
- msg = self.encrypt_ike_msg(header, b'', None)
- return self.create_packet(self.pg0, msg, self.sa.sport,
- self.sa.dport, self.sa.natt, self.ip6)
-
- def create_packet(self, src_if, msg, sport=500, dport=500, natt=False,
- use_ip6=False):
+ header = ikev2.IKEv2(
+ init_SPI=self.sa.ispi,
+ resp_SPI=self.sa.rspi,
+ id=self.sa.new_msg_id(),
+ flags="Initiator",
+ exch_type="INFORMATIONAL",
+ next_payload="Encrypted",
+ )
+
+ msg = self.encrypt_ike_msg(header, b"", None)
+ return self.create_packet(
+ self.pg0, msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6
+ )
+
+ def create_packet(
+ self, src_if, msg, sport=500, dport=500, natt=False, use_ip6=False
+ ):
if use_ip6:
src_ip = src_if.remote_ip6
dst_ip = src_if.local_ip6
@@ -629,12 +666,14 @@ class IkePeer(VppTestCase):
src_ip = src_if.remote_ip4
dst_ip = src_if.local_ip4
ip_layer = IP
- res = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- ip_layer(src=src_ip, dst=dst_ip) /
- UDP(sport=sport, dport=dport))
+ res = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / ip_layer(src=src_ip, dst=dst_ip)
+ / UDP(sport=sport, dport=dport)
+ )
if natt:
# insert non ESP marker
- res = res / Raw(b'\x00' * 4)
+ res = res / Raw(b"\x00" * 4)
return res / msg
def verify_udp(self, udp):
@@ -651,7 +690,7 @@ class IkePeer(VppTestCase):
esp = packet[ESP]
ih = self.verify_and_remove_non_esp_marker(esp)
self.assertEqual(ih.version, 0x20)
- self.assertNotIn('Version', ih.flags)
+ self.assertNotIn("Version", ih.flags)
return ih
def verify_and_remove_non_esp_marker(self, packet):
@@ -659,26 +698,32 @@ class IkePeer(VppTestCase):
# if we are in nat traversal mode check for non esp marker
# and remove it
data = raw(packet)
- self.assertEqual(data[:4], b'\x00' * 4)
+ self.assertEqual(data[:4], b"\x00" * 4)
return ikev2.IKEv2(data[4:])
else:
return packet
def encrypt_ike_msg(self, header, plain, first_payload):
- if self.sa.ike_crypto == 'AES-GCM-16ICV':
+ if self.sa.ike_crypto == "AES-GCM-16ICV":
data = self.sa.ike_crypto_alg.pad(raw(plain))
- plen = len(data) + GCM_IV_SIZE + GCM_ICV_SIZE +\
- len(ikev2.IKEv2_payload_Encrypted())
+ plen = (
+ len(data)
+ + GCM_IV_SIZE
+ + GCM_ICV_SIZE
+ + len(ikev2.IKEv2_payload_Encrypted())
+ )
tlen = plen + len(ikev2.IKEv2())
# prepare aad data
- sk_p = ikev2.IKEv2_payload_Encrypted(next_payload=first_payload,
- length=plen)
+ sk_p = ikev2.IKEv2_payload_Encrypted(
+ next_payload=first_payload, length=plen
+ )
header.length = tlen
res = header / sk_p
encr = self.sa.encrypt(raw(plain), raw(res))
- sk_p = ikev2.IKEv2_payload_Encrypted(next_payload=first_payload,
- length=plen, load=encr)
+ sk_p = ikev2.IKEv2_payload_Encrypted(
+ next_payload=first_payload, length=plen, load=encr
+ )
res = header / sk_p
else:
encr = self.sa.encrypt(raw(plain))
@@ -686,16 +731,18 @@ class IkePeer(VppTestCase):
plen = len(encr) + len(ikev2.IKEv2_payload_Encrypted()) + trunc_len
tlen = plen + len(ikev2.IKEv2())
- sk_p = ikev2.IKEv2_payload_Encrypted(next_payload=first_payload,
- length=plen, load=encr)
+ sk_p = ikev2.IKEv2_payload_Encrypted(
+ next_payload=first_payload, length=plen, load=encr
+ )
header.length = tlen
res = header / sk_p
integ_data = raw(res)
- hmac_data = self.sa.compute_hmac(self.sa.ike_integ_alg.mod(),
- self.sa.my_authkey, integ_data)
+ hmac_data = self.sa.compute_hmac(
+ self.sa.ike_integ_alg.mod(), self.sa.my_authkey, integ_data
+ )
res = res / Raw(hmac_data[:trunc_len])
- assert(len(res) == tlen)
+ assert len(res) == tlen
return res
def verify_udp_encap(self, ipsec_sa):
@@ -747,37 +794,37 @@ class IkePeer(VppTestCase):
# verify crypto keys
self.assertEqual(sa0.crypto_key.length, len(c.sk_er))
self.assertEqual(sa1.crypto_key.length, len(c.sk_ei))
- self.assertEqual(sa0.crypto_key.data[:len(c.sk_er)], c.sk_er)
- self.assertEqual(sa1.crypto_key.data[:len(c.sk_ei)], c.sk_ei)
+ self.assertEqual(sa0.crypto_key.data[: len(c.sk_er)], c.sk_er)
+ self.assertEqual(sa1.crypto_key.data[: len(c.sk_ei)], c.sk_ei)
# verify integ keys
if vpp_integ_alg:
self.assertEqual(sa0.integrity_key.length, len(c.sk_ar))
self.assertEqual(sa1.integrity_key.length, len(c.sk_ai))
- self.assertEqual(sa0.integrity_key.data[:len(c.sk_ar)], c.sk_ar)
- self.assertEqual(sa1.integrity_key.data[:len(c.sk_ai)], c.sk_ai)
+ self.assertEqual(sa0.integrity_key.data[: len(c.sk_ar)], c.sk_ar)
+ self.assertEqual(sa1.integrity_key.data[: len(c.sk_ai)], c.sk_ai)
else:
- self.assertEqual(sa0.salt.to_bytes(4, 'little'), c.salt_er)
- self.assertEqual(sa1.salt.to_bytes(4, 'little'), c.salt_ei)
+ self.assertEqual(sa0.salt.to_bytes(4, "little"), c.salt_er)
+ self.assertEqual(sa1.salt.to_bytes(4, "little"), c.salt_ei)
def verify_keymat(self, api_keys, keys, name):
km = getattr(keys, name)
api_km = getattr(api_keys, name)
- api_km_len = getattr(api_keys, name + '_len')
+ api_km_len = getattr(api_keys, name + "_len")
self.assertEqual(len(km), api_km_len)
self.assertEqual(km, api_km[:api_km_len])
def verify_id(self, api_id, exp_id):
self.assertEqual(api_id.type, IDType.value(exp_id.type))
self.assertEqual(api_id.data_len, exp_id.data_len)
- self.assertEqual(bytes(api_id.data, 'ascii'), exp_id.type)
+ self.assertEqual(bytes(api_id.data, "ascii"), exp_id.type)
def verify_ike_sas(self):
r = self.vapi.ikev2_sa_dump()
self.assertEqual(len(r), 1)
sa = r[0].sa
- self.assertEqual(self.sa.ispi, (sa.ispi).to_bytes(8, 'big'))
- self.assertEqual(self.sa.rspi, (sa.rspi).to_bytes(8, 'big'))
+ self.assertEqual(self.sa.ispi, (sa.ispi).to_bytes(8, "big"))
+ self.assertEqual(self.sa.rspi, (sa.rspi).to_bytes(8, "big"))
if self.ip6:
if self.sa.is_initiator:
self.assertEqual(sa.iaddr, IPv6Address(self.pg0.remote_ip6))
@@ -792,55 +839,53 @@ class IkePeer(VppTestCase):
else:
self.assertEqual(sa.iaddr, IPv4Address(self.pg0.local_ip4))
self.assertEqual(sa.raddr, IPv4Address(self.pg0.remote_ip4))
- self.verify_keymat(sa.keys, self.sa, 'sk_d')
- self.verify_keymat(sa.keys, self.sa, 'sk_ai')
- self.verify_keymat(sa.keys, self.sa, 'sk_ar')
- self.verify_keymat(sa.keys, self.sa, 'sk_ei')
- self.verify_keymat(sa.keys, self.sa, 'sk_er')
- self.verify_keymat(sa.keys, self.sa, 'sk_pi')
- self.verify_keymat(sa.keys, self.sa, 'sk_pr')
+ self.verify_keymat(sa.keys, self.sa, "sk_d")
+ self.verify_keymat(sa.keys, self.sa, "sk_ai")
+ self.verify_keymat(sa.keys, self.sa, "sk_ar")
+ self.verify_keymat(sa.keys, self.sa, "sk_ei")
+ self.verify_keymat(sa.keys, self.sa, "sk_er")
+ self.verify_keymat(sa.keys, self.sa, "sk_pi")
+ self.verify_keymat(sa.keys, self.sa, "sk_pr")
self.assertEqual(sa.i_id.type, self.sa.id_type)
self.assertEqual(sa.r_id.type, self.sa.id_type)
self.assertEqual(sa.i_id.data_len, len(self.sa.i_id))
self.assertEqual(sa.r_id.data_len, len(self.idr))
- self.assertEqual(bytes(sa.i_id.data, 'ascii'), self.sa.i_id)
- self.assertEqual(bytes(sa.r_id.data, 'ascii'), self.idr)
+ self.assertEqual(bytes(sa.i_id.data, "ascii"), self.sa.i_id)
+ self.assertEqual(bytes(sa.r_id.data, "ascii"), self.idr)
r = self.vapi.ikev2_child_sa_dump(sa_index=sa.sa_index)
self.assertEqual(len(r), 1)
csa = r[0].child_sa
self.assertEqual(csa.sa_index, sa.sa_index)
c = self.sa.child_sas[0]
- if hasattr(c, 'sk_ai'):
- self.verify_keymat(csa.keys, c, 'sk_ai')
- self.verify_keymat(csa.keys, c, 'sk_ar')
- self.verify_keymat(csa.keys, c, 'sk_ei')
- self.verify_keymat(csa.keys, c, 'sk_er')
- self.assertEqual(csa.i_spi.to_bytes(4, 'big'), c.ispi)
- self.assertEqual(csa.r_spi.to_bytes(4, 'big'), c.rspi)
+ if hasattr(c, "sk_ai"):
+ self.verify_keymat(csa.keys, c, "sk_ai")
+ self.verify_keymat(csa.keys, c, "sk_ar")
+ self.verify_keymat(csa.keys, c, "sk_ei")
+ self.verify_keymat(csa.keys, c, "sk_er")
+ self.assertEqual(csa.i_spi.to_bytes(4, "big"), c.ispi)
+ self.assertEqual(csa.r_spi.to_bytes(4, "big"), c.rspi)
tsi, tsr = self.sa.generate_ts(self.p.ts_is_ip4)
tsi = tsi[0]
tsr = tsr[0]
r = self.vapi.ikev2_traffic_selector_dump(
- is_initiator=True, sa_index=sa.sa_index,
- child_sa_index=csa.child_sa_index)
+ is_initiator=True, sa_index=sa.sa_index, child_sa_index=csa.child_sa_index
+ )
self.assertEqual(len(r), 1)
ts = r[0].ts
self.verify_ts(r[0].ts, tsi[0], True)
r = self.vapi.ikev2_traffic_selector_dump(
- is_initiator=False, sa_index=sa.sa_index,
- child_sa_index=csa.child_sa_index)
+ is_initiator=False, sa_index=sa.sa_index, child_sa_index=csa.child_sa_index
+ )
self.assertEqual(len(r), 1)
self.verify_ts(r[0].ts, tsr[0], False)
- n = self.vapi.ikev2_nonce_get(is_initiator=True,
- sa_index=sa.sa_index)
+ n = self.vapi.ikev2_nonce_get(is_initiator=True, sa_index=sa.sa_index)
self.verify_nonce(n, self.sa.i_nonce)
- n = self.vapi.ikev2_nonce_get(is_initiator=False,
- sa_index=sa.sa_index)
+ n = self.vapi.ikev2_nonce_get(is_initiator=False, sa_index=sa.sa_index)
self.verify_nonce(n, self.sa.r_nonce)
def verify_nonce(self, api_nonce, nonce):
@@ -854,61 +899,65 @@ class IkePeer(VppTestCase):
self.assertFalse(api_ts.is_local)
if self.p.ts_is_ip4:
- self.assertEqual(api_ts.start_addr,
- IPv4Address(ts.starting_address_v4))
- self.assertEqual(api_ts.end_addr,
- IPv4Address(ts.ending_address_v4))
+ self.assertEqual(api_ts.start_addr, IPv4Address(ts.starting_address_v4))
+ self.assertEqual(api_ts.end_addr, IPv4Address(ts.ending_address_v4))
else:
- self.assertEqual(api_ts.start_addr,
- IPv6Address(ts.starting_address_v6))
- self.assertEqual(api_ts.end_addr,
- IPv6Address(ts.ending_address_v6))
+ self.assertEqual(api_ts.start_addr, IPv6Address(ts.starting_address_v6))
+ self.assertEqual(api_ts.end_addr, IPv6Address(ts.ending_address_v6))
self.assertEqual(api_ts.start_port, ts.start_port)
self.assertEqual(api_ts.end_port, ts.end_port)
self.assertEqual(api_ts.protocol_id, ts.IP_protocol_ID)
class TemplateInitiator(IkePeer):
- """ initiator test template """
+ """initiator test template"""
def initiate_del_sa_from_initiator(self):
- ispi = int.from_bytes(self.sa.ispi, 'little')
+ ispi = int.from_bytes(self.sa.ispi, "little")
self.pg0.enable_capture()
self.pg_start()
self.vapi.ikev2_initiate_del_ike_sa(ispi=ispi)
capture = self.pg0.get_capture(1)
ih = self.get_ike_header(capture[0])
- self.assertNotIn('Response', ih.flags)
- self.assertIn('Initiator', ih.flags)
+ self.assertNotIn("Response", ih.flags)
+ self.assertIn("Initiator", ih.flags)
self.assertEqual(ih.init_SPI, self.sa.ispi)
self.assertEqual(ih.resp_SPI, self.sa.rspi)
plain = self.sa.hmac_and_decrypt(ih)
d = ikev2.IKEv2_payload_Delete(plain)
self.assertEqual(d.proto, 1) # proto=IKEv2
- header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi,
- flags='Response', exch_type='INFORMATIONAL',
- id=ih.id, next_payload='Encrypted')
- resp = self.encrypt_ike_msg(header, b'', None)
+ header = ikev2.IKEv2(
+ init_SPI=self.sa.ispi,
+ resp_SPI=self.sa.rspi,
+ flags="Response",
+ exch_type="INFORMATIONAL",
+ id=ih.id,
+ next_payload="Encrypted",
+ )
+ resp = self.encrypt_ike_msg(header, b"", None)
self.send_and_assert_no_replies(self.pg0, resp)
def verify_del_sa(self, packet):
ih = self.get_ike_header(packet)
self.assertEqual(ih.id, self.sa.msg_id)
self.assertEqual(ih.exch_type, 37) # exchange informational
- self.assertIn('Response', ih.flags)
- self.assertIn('Initiator', ih.flags)
+ self.assertIn("Response", ih.flags)
+ self.assertIn("Initiator", ih.flags)
plain = self.sa.hmac_and_decrypt(ih)
- self.assertEqual(plain, b'')
+ self.assertEqual(plain, b"")
def initiate_del_sa_from_responder(self):
- header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi,
- exch_type='INFORMATIONAL',
- id=self.sa.new_msg_id())
- del_sa = ikev2.IKEv2_payload_Delete(proto='IKEv2')
- ike_msg = self.encrypt_ike_msg(header, del_sa, 'Delete')
- packet = self.create_packet(self.pg0, ike_msg,
- self.sa.sport, self.sa.dport,
- self.sa.natt, self.ip6)
+ header = ikev2.IKEv2(
+ init_SPI=self.sa.ispi,
+ resp_SPI=self.sa.rspi,
+ exch_type="INFORMATIONAL",
+ id=self.sa.new_msg_id(),
+ )
+ del_sa = ikev2.IKEv2_payload_Delete(proto="IKEv2")
+ ike_msg = self.encrypt_ike_msg(header, del_sa, "Delete")
+ packet = self.create_packet(
+ self.pg0, ike_msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6
+ )
self.pg0.add_stream(packet)
self.pg0.enable_capture()
self.pg_start()
@@ -935,26 +984,28 @@ class TemplateInitiator(IkePeer):
s = self.find_notify_payload(packet, 16388)
self.assertIsNotNone(s)
src_sha = self.sa.compute_nat_sha1(
- inet_pton(socket.AF_INET, iph.src), udp.sport, b'\x00' * 8)
+ inet_pton(socket.AF_INET, iph.src), udp.sport, b"\x00" * 8
+ )
self.assertEqual(s.load, src_sha)
# NAT_DETECTION_DESTINATION_IP
s = self.find_notify_payload(packet, 16389)
self.assertIsNotNone(s)
dst_sha = self.sa.compute_nat_sha1(
- inet_pton(socket.AF_INET, iph.dst), udp.dport, b'\x00' * 8)
+ inet_pton(socket.AF_INET, iph.dst), udp.dport, b"\x00" * 8
+ )
self.assertEqual(s.load, dst_sha)
def verify_sa_init_request(self, packet):
udp = packet[UDP]
self.sa.dport = udp.sport
ih = packet[ikev2.IKEv2]
- self.assertNotEqual(ih.init_SPI, 8 * b'\x00')
+ self.assertNotEqual(ih.init_SPI, 8 * b"\x00")
self.assertEqual(ih.exch_type, 34) # SA_INIT
self.sa.ispi = ih.init_SPI
- self.assertEqual(ih.resp_SPI, 8 * b'\x00')
- self.assertIn('Initiator', ih.flags)
- self.assertNotIn('Response', ih.flags)
+ self.assertEqual(ih.resp_SPI, 8 * b"\x00")
+ self.assertIn("Initiator", ih.flags)
+ self.assertNotIn("Response", ih.flags)
self.sa.i_nonce = ih[ikev2.IKEv2_payload_Nonce].load
self.sa.i_dh_data = ih[ikev2.IKEv2_payload_KE].load
@@ -962,20 +1013,23 @@ class TemplateInitiator(IkePeer):
self.assertEqual(prop.proto, 1) # proto = ikev2
self.assertEqual(prop.proposal, 1)
self.assertEqual(prop.trans[0].transform_type, 1) # encryption
- self.assertEqual(prop.trans[0].transform_id,
- self.p.ike_transforms['crypto_alg'])
+ self.assertEqual(
+ prop.trans[0].transform_id, self.p.ike_transforms["crypto_alg"]
+ )
self.assertEqual(prop.trans[1].transform_type, 2) # prf
self.assertEqual(prop.trans[1].transform_id, 5) # "hmac-sha2-256"
self.assertEqual(prop.trans[2].transform_type, 4) # dh
- self.assertEqual(prop.trans[2].transform_id,
- self.p.ike_transforms['dh_group'])
+ self.assertEqual(prop.trans[2].transform_id, self.p.ike_transforms["dh_group"])
self.verify_nat_detection(packet)
self.sa.set_ike_props(
- crypto='AES-GCM-16ICV', crypto_key_len=32,
- integ='NULL', prf='PRF_HMAC_SHA2_256', dh='3072MODPgr')
- self.sa.set_esp_props(crypto='AES-CBC', crypto_key_len=32,
- integ='SHA2-256-128')
+ crypto="AES-GCM-16ICV",
+ crypto_key_len=32,
+ integ="NULL",
+ prf="PRF_HMAC_SHA2_256",
+ dh="3072MODPgr",
+ )
+ self.sa.set_esp_props(crypto="AES-CBC", crypto_key_len=32, integ="SHA2-256-128")
self.sa.generate_dh_data()
self.sa.complete_dh_data()
self.sa.calc_keys()
@@ -995,8 +1049,8 @@ class TemplateInitiator(IkePeer):
self.assertEqual(ih.resp_SPI, self.sa.rspi)
self.assertEqual(ih.init_SPI, self.sa.ispi)
self.assertEqual(ih.exch_type, 35) # IKE_AUTH
- self.assertIn('Initiator', ih.flags)
- self.assertNotIn('Response', ih.flags)
+ self.assertIn("Initiator", ih.flags)
+ self.assertNotIn("Response", ih.flags)
udp = packet[UDP]
self.verify_udp(udp)
@@ -1013,48 +1067,67 @@ class TemplateInitiator(IkePeer):
prop = idi[ikev2.IKEv2_payload_Proposal]
c = self.sa.child_sas[0]
c.ispi = prop.SPI
- self.update_esp_transforms(
- prop[ikev2.IKEv2_payload_Transform], self.sa)
+ self.update_esp_transforms(prop[ikev2.IKEv2_payload_Transform], self.sa)
def send_init_response(self):
tr_attr = self.sa.ike_crypto_attr()
- trans = (ikev2.IKEv2_payload_Transform(transform_type='Encryption',
- transform_id=self.sa.ike_crypto, length=tr_attr[1],
- key_length=tr_attr[0]) /
- ikev2.IKEv2_payload_Transform(transform_type='Integrity',
- transform_id=self.sa.ike_integ) /
- ikev2.IKEv2_payload_Transform(transform_type='PRF',
- transform_id=self.sa.ike_prf_alg.name) /
- ikev2.IKEv2_payload_Transform(transform_type='GroupDesc',
- transform_id=self.sa.ike_dh))
- props = (ikev2.IKEv2_payload_Proposal(proposal=1, proto='IKEv2',
- trans_nb=4, trans=trans))
+ trans = (
+ ikev2.IKEv2_payload_Transform(
+ transform_type="Encryption",
+ transform_id=self.sa.ike_crypto,
+ length=tr_attr[1],
+ key_length=tr_attr[0],
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="Integrity", transform_id=self.sa.ike_integ
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="PRF", transform_id=self.sa.ike_prf_alg.name
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="GroupDesc", transform_id=self.sa.ike_dh
+ )
+ )
+ props = ikev2.IKEv2_payload_Proposal(
+ proposal=1, proto="IKEv2", trans_nb=4, trans=trans
+ )
src_address = inet_pton(socket.AF_INET, self.pg0.remote_ip4)
if self.sa.natt:
- dst_address = b'\x0a\x0a\x0a\x0a'
+ dst_address = b"\x0a\x0a\x0a\x0a"
else:
dst_address = inet_pton(socket.AF_INET, self.pg0.local_ip4)
src_nat = self.sa.compute_nat_sha1(src_address, self.sa.sport)
dst_nat = self.sa.compute_nat_sha1(dst_address, self.sa.dport)
self.sa.init_resp_packet = (
- ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi,
- exch_type='IKE_SA_INIT', flags='Response') /
- ikev2.IKEv2_payload_SA(next_payload='KE', prop=props) /
- ikev2.IKEv2_payload_KE(next_payload='Nonce',
- group=self.sa.ike_dh,
- load=self.sa.my_dh_pub_key) /
- ikev2.IKEv2_payload_Nonce(load=self.sa.r_nonce,
- next_payload='Notify') /
- ikev2.IKEv2_payload_Notify(
- type='NAT_DETECTION_SOURCE_IP', load=src_nat,
- next_payload='Notify') / ikev2.IKEv2_payload_Notify(
- type='NAT_DETECTION_DESTINATION_IP', load=dst_nat))
-
- ike_msg = self.create_packet(self.pg0, self.sa.init_resp_packet,
- self.sa.sport, self.sa.dport,
- False, self.ip6)
+ ikev2.IKEv2(
+ init_SPI=self.sa.ispi,
+ resp_SPI=self.sa.rspi,
+ exch_type="IKE_SA_INIT",
+ flags="Response",
+ )
+ / ikev2.IKEv2_payload_SA(next_payload="KE", prop=props)
+ / ikev2.IKEv2_payload_KE(
+ next_payload="Nonce", group=self.sa.ike_dh, load=self.sa.my_dh_pub_key
+ )
+ / ikev2.IKEv2_payload_Nonce(load=self.sa.r_nonce, next_payload="Notify")
+ / ikev2.IKEv2_payload_Notify(
+ type="NAT_DETECTION_SOURCE_IP", load=src_nat, next_payload="Notify"
+ )
+ / ikev2.IKEv2_payload_Notify(
+ type="NAT_DETECTION_DESTINATION_IP", load=dst_nat
+ )
+ )
+
+ ike_msg = self.create_packet(
+ self.pg0,
+ self.sa.init_resp_packet,
+ self.sa.sport,
+ self.sa.dport,
+ False,
+ self.ip6,
+ )
self.pg_send(self.pg0, ike_msg)
capture = self.pg0.get_capture(1)
self.verify_sa_auth_req(capture[0])
@@ -1070,47 +1143,64 @@ class TemplateInitiator(IkePeer):
def send_auth_response(self):
tr_attr = self.sa.esp_crypto_attr()
- trans = (ikev2.IKEv2_payload_Transform(transform_type='Encryption',
- transform_id=self.sa.esp_crypto, length=tr_attr[1],
- key_length=tr_attr[0]) /
- ikev2.IKEv2_payload_Transform(transform_type='Integrity',
- transform_id=self.sa.esp_integ) /
- ikev2.IKEv2_payload_Transform(
- transform_type='Extended Sequence Number',
- transform_id='No ESN') /
- ikev2.IKEv2_payload_Transform(
- transform_type='Extended Sequence Number',
- transform_id='ESN'))
+ trans = (
+ ikev2.IKEv2_payload_Transform(
+ transform_type="Encryption",
+ transform_id=self.sa.esp_crypto,
+ length=tr_attr[1],
+ key_length=tr_attr[0],
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="Integrity", transform_id=self.sa.esp_integ
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="Extended Sequence Number", transform_id="No ESN"
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="Extended Sequence Number", transform_id="ESN"
+ )
+ )
c = self.sa.child_sas[0]
- props = (ikev2.IKEv2_payload_Proposal(proposal=1, proto='ESP',
- SPIsize=4, SPI=c.rspi, trans_nb=4, trans=trans))
+ props = ikev2.IKEv2_payload_Proposal(
+ proposal=1, proto="ESP", SPIsize=4, SPI=c.rspi, trans_nb=4, trans=trans
+ )
tsi, tsr = self.sa.generate_ts(self.p.ts_is_ip4)
- plain = (ikev2.IKEv2_payload_IDi(next_payload='IDr',
- IDtype=self.sa.id_type, load=self.sa.i_id) /
- ikev2.IKEv2_payload_IDr(next_payload='AUTH',
- IDtype=self.sa.id_type, load=self.sa.r_id) /
- ikev2.IKEv2_payload_AUTH(next_payload='SA',
- auth_type=AuthMethod.value(self.sa.auth_method),
- load=self.sa.auth_data) /
- ikev2.IKEv2_payload_SA(next_payload='TSi', prop=props) /
- ikev2.IKEv2_payload_TSi(next_payload='TSr',
- number_of_TSs=len(tsi),
- traffic_selector=tsi) /
- ikev2.IKEv2_payload_TSr(next_payload='Notify',
- number_of_TSs=len(tsr),
- traffic_selector=tsr) /
- ikev2.IKEv2_payload_Notify(type='INITIAL_CONTACT'))
+ plain = (
+ ikev2.IKEv2_payload_IDi(
+ next_payload="IDr", IDtype=self.sa.id_type, load=self.sa.i_id
+ )
+ / ikev2.IKEv2_payload_IDr(
+ next_payload="AUTH", IDtype=self.sa.id_type, load=self.sa.r_id
+ )
+ / ikev2.IKEv2_payload_AUTH(
+ next_payload="SA",
+ auth_type=AuthMethod.value(self.sa.auth_method),
+ load=self.sa.auth_data,
+ )
+ / ikev2.IKEv2_payload_SA(next_payload="TSi", prop=props)
+ / ikev2.IKEv2_payload_TSi(
+ next_payload="TSr", number_of_TSs=len(tsi), traffic_selector=tsi
+ )
+ / ikev2.IKEv2_payload_TSr(
+ next_payload="Notify", number_of_TSs=len(tsr), traffic_selector=tsr
+ )
+ / ikev2.IKEv2_payload_Notify(type="INITIAL_CONTACT")
+ )
header = ikev2.IKEv2(
- init_SPI=self.sa.ispi,
- resp_SPI=self.sa.rspi, id=self.sa.new_msg_id(),
- flags='Response', exch_type='IKE_AUTH')
-
- ike_msg = self.encrypt_ike_msg(header, plain, 'IDi')
- packet = self.create_packet(self.pg0, ike_msg, self.sa.sport,
- self.sa.dport, self.sa.natt, self.ip6)
+ init_SPI=self.sa.ispi,
+ resp_SPI=self.sa.rspi,
+ id=self.sa.new_msg_id(),
+ flags="Response",
+ exch_type="IKE_AUTH",
+ )
+
+ ike_msg = self.encrypt_ike_msg(header, plain, "IDi")
+ packet = self.create_packet(
+ self.pg0, ike_msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6
+ )
self.pg_send(self.pg0, packet)
def test_initiator(self):
@@ -1122,51 +1212,58 @@ class TemplateInitiator(IkePeer):
class TemplateResponder(IkePeer):
- """ responder test template """
+ """responder test template"""
def initiate_del_sa_from_responder(self):
self.pg0.enable_capture()
self.pg_start()
- self.vapi.ikev2_initiate_del_ike_sa(
- ispi=int.from_bytes(self.sa.ispi, 'little'))
+ self.vapi.ikev2_initiate_del_ike_sa(ispi=int.from_bytes(self.sa.ispi, "little"))
capture = self.pg0.get_capture(1)
ih = self.get_ike_header(capture[0])
- self.assertNotIn('Response', ih.flags)
- self.assertNotIn('Initiator', ih.flags)
+ self.assertNotIn("Response", ih.flags)
+ self.assertNotIn("Initiator", ih.flags)
self.assertEqual(ih.exch_type, 37) # INFORMATIONAL
plain = self.sa.hmac_and_decrypt(ih)
d = ikev2.IKEv2_payload_Delete(plain)
self.assertEqual(d.proto, 1) # proto=IKEv2
self.assertEqual(ih.init_SPI, self.sa.ispi)
self.assertEqual(ih.resp_SPI, self.sa.rspi)
- header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi,
- flags='Initiator+Response',
- exch_type='INFORMATIONAL',
- id=ih.id, next_payload='Encrypted')
- resp = self.encrypt_ike_msg(header, b'', None)
+ header = ikev2.IKEv2(
+ init_SPI=self.sa.ispi,
+ resp_SPI=self.sa.rspi,
+ flags="Initiator+Response",
+ exch_type="INFORMATIONAL",
+ id=ih.id,
+ next_payload="Encrypted",
+ )
+ resp = self.encrypt_ike_msg(header, b"", None)
self.send_and_assert_no_replies(self.pg0, resp)
def verify_del_sa(self, packet):
ih = self.get_ike_header(packet)
self.assertEqual(ih.id, self.sa.msg_id)
self.assertEqual(ih.exch_type, 37) # exchange informational
- self.assertIn('Response', ih.flags)
- self.assertNotIn('Initiator', ih.flags)
+ self.assertIn("Response", ih.flags)
+ self.assertNotIn("Initiator", ih.flags)
self.assertEqual(ih.next_payload, 46) # Encrypted
self.assertEqual(ih.init_SPI, self.sa.ispi)
self.assertEqual(ih.resp_SPI, self.sa.rspi)
plain = self.sa.hmac_and_decrypt(ih)
- self.assertEqual(plain, b'')
+ self.assertEqual(plain, b"")
def initiate_del_sa_from_initiator(self):
- header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi,
- flags='Initiator', exch_type='INFORMATIONAL',
- id=self.sa.new_msg_id())
- del_sa = ikev2.IKEv2_payload_Delete(proto='IKEv2')
- ike_msg = self.encrypt_ike_msg(header, del_sa, 'Delete')
- packet = self.create_packet(self.pg0, ike_msg,
- self.sa.sport, self.sa.dport,
- self.sa.natt, self.ip6)
+ header = ikev2.IKEv2(
+ init_SPI=self.sa.ispi,
+ resp_SPI=self.sa.rspi,
+ flags="Initiator",
+ exch_type="INFORMATIONAL",
+ id=self.sa.new_msg_id(),
+ )
+ del_sa = ikev2.IKEv2_payload_Delete(proto="IKEv2")
+ ike_msg = self.encrypt_ike_msg(header, del_sa, "Delete")
+ packet = self.create_packet(
+ self.pg0, ike_msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6
+ )
self.pg0.add_stream(packet)
self.pg0.enable_capture()
self.pg_start()
@@ -1175,56 +1272,72 @@ class TemplateResponder(IkePeer):
def send_sa_init_req(self):
tr_attr = self.sa.ike_crypto_attr()
- trans = (ikev2.IKEv2_payload_Transform(transform_type='Encryption',
- transform_id=self.sa.ike_crypto, length=tr_attr[1],
- key_length=tr_attr[0]) /
- ikev2.IKEv2_payload_Transform(transform_type='Integrity',
- transform_id=self.sa.ike_integ) /
- ikev2.IKEv2_payload_Transform(transform_type='PRF',
- transform_id=self.sa.ike_prf_alg.name) /
- ikev2.IKEv2_payload_Transform(transform_type='GroupDesc',
- transform_id=self.sa.ike_dh))
-
- props = (ikev2.IKEv2_payload_Proposal(proposal=1, proto='IKEv2',
- trans_nb=4, trans=trans))
-
- next_payload = None if self.ip6 else 'Notify'
+ trans = (
+ ikev2.IKEv2_payload_Transform(
+ transform_type="Encryption",
+ transform_id=self.sa.ike_crypto,
+ length=tr_attr[1],
+ key_length=tr_attr[0],
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="Integrity", transform_id=self.sa.ike_integ
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="PRF", transform_id=self.sa.ike_prf_alg.name
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="GroupDesc", transform_id=self.sa.ike_dh
+ )
+ )
+
+ props = ikev2.IKEv2_payload_Proposal(
+ proposal=1, proto="IKEv2", trans_nb=4, trans=trans
+ )
+
+ next_payload = None if self.ip6 else "Notify"
self.sa.init_req_packet = (
- ikev2.IKEv2(init_SPI=self.sa.ispi,
- flags='Initiator', exch_type='IKE_SA_INIT') /
- ikev2.IKEv2_payload_SA(next_payload='KE', prop=props) /
- ikev2.IKEv2_payload_KE(next_payload='Nonce',
- group=self.sa.ike_dh,
- load=self.sa.my_dh_pub_key) /
- ikev2.IKEv2_payload_Nonce(next_payload=next_payload,
- load=self.sa.i_nonce))
+ ikev2.IKEv2(
+ init_SPI=self.sa.ispi, flags="Initiator", exch_type="IKE_SA_INIT"
+ )
+ / ikev2.IKEv2_payload_SA(next_payload="KE", prop=props)
+ / ikev2.IKEv2_payload_KE(
+ next_payload="Nonce", group=self.sa.ike_dh, load=self.sa.my_dh_pub_key
+ )
+ / ikev2.IKEv2_payload_Nonce(next_payload=next_payload, load=self.sa.i_nonce)
+ )
if not self.ip6:
if self.sa.i_natt:
- src_address = b'\x0a\x0a\x0a\x01'
+ src_address = b"\x0a\x0a\x0a\x01"
else:
src_address = inet_pton(socket.AF_INET, self.pg0.remote_ip4)
if self.sa.r_natt:
- dst_address = b'\x0a\x0a\x0a\x0a'
+ dst_address = b"\x0a\x0a\x0a\x0a"
else:
dst_address = inet_pton(socket.AF_INET, self.pg0.local_ip4)
src_nat = self.sa.compute_nat_sha1(src_address, self.sa.sport)
dst_nat = self.sa.compute_nat_sha1(dst_address, self.sa.dport)
nat_src_detection = ikev2.IKEv2_payload_Notify(
- type='NAT_DETECTION_SOURCE_IP', load=src_nat,
- next_payload='Notify')
+ type="NAT_DETECTION_SOURCE_IP", load=src_nat, next_payload="Notify"
+ )
nat_dst_detection = ikev2.IKEv2_payload_Notify(
- type='NAT_DETECTION_DESTINATION_IP', load=dst_nat)
- self.sa.init_req_packet = (self.sa.init_req_packet /
- nat_src_detection /
- nat_dst_detection)
-
- ike_msg = self.create_packet(self.pg0, self.sa.init_req_packet,
- self.sa.sport, self.sa.dport,
- self.sa.natt, self.ip6)
+ type="NAT_DETECTION_DESTINATION_IP", load=dst_nat
+ )
+ self.sa.init_req_packet = (
+ self.sa.init_req_packet / nat_src_detection / nat_dst_detection
+ )
+
+ ike_msg = self.create_packet(
+ self.pg0,
+ self.sa.init_req_packet,
+ self.sa.sport,
+ self.sa.dport,
+ self.sa.natt,
+ self.ip6,
+ )
self.pg0.add_stream(ike_msg)
self.pg0.enable_capture()
self.pg_start()
@@ -1233,65 +1346,83 @@ class TemplateResponder(IkePeer):
def generate_auth_payload(self, last_payload=None, is_rekey=False):
tr_attr = self.sa.esp_crypto_attr()
- last_payload = last_payload or 'Notify'
- trans = (ikev2.IKEv2_payload_Transform(transform_type='Encryption',
- transform_id=self.sa.esp_crypto, length=tr_attr[1],
- key_length=tr_attr[0]) /
- ikev2.IKEv2_payload_Transform(transform_type='Integrity',
- transform_id=self.sa.esp_integ) /
- ikev2.IKEv2_payload_Transform(
- transform_type='Extended Sequence Number',
- transform_id='No ESN') /
- ikev2.IKEv2_payload_Transform(
- transform_type='Extended Sequence Number',
- transform_id='ESN'))
+ last_payload = last_payload or "Notify"
+ trans = (
+ ikev2.IKEv2_payload_Transform(
+ transform_type="Encryption",
+ transform_id=self.sa.esp_crypto,
+ length=tr_attr[1],
+ key_length=tr_attr[0],
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="Integrity", transform_id=self.sa.esp_integ
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="Extended Sequence Number", transform_id="No ESN"
+ )
+ / ikev2.IKEv2_payload_Transform(
+ transform_type="Extended Sequence Number", transform_id="ESN"
+ )
+ )
c = self.sa.child_sas[0]
- props = (ikev2.IKEv2_payload_Proposal(proposal=1, proto='ESP',
- SPIsize=4, SPI=c.ispi, trans_nb=4, trans=trans))
+ props = ikev2.IKEv2_payload_Proposal(
+ proposal=1, proto="ESP", SPIsize=4, SPI=c.ispi, trans_nb=4, trans=trans
+ )
tsi, tsr = self.sa.generate_ts(self.p.ts_is_ip4)
- plain = (ikev2.IKEv2_payload_AUTH(next_payload='SA',
- auth_type=AuthMethod.value(self.sa.auth_method),
- load=self.sa.auth_data) /
- ikev2.IKEv2_payload_SA(next_payload='TSi', prop=props) /
- ikev2.IKEv2_payload_TSi(next_payload='TSr',
- number_of_TSs=len(tsi), traffic_selector=tsi) /
- ikev2.IKEv2_payload_TSr(next_payload=last_payload,
- number_of_TSs=len(tsr), traffic_selector=tsr))
+ plain = (
+ ikev2.IKEv2_payload_AUTH(
+ next_payload="SA",
+ auth_type=AuthMethod.value(self.sa.auth_method),
+ load=self.sa.auth_data,
+ )
+ / ikev2.IKEv2_payload_SA(next_payload="TSi", prop=props)
+ / ikev2.IKEv2_payload_TSi(
+ next_payload="TSr", number_of_TSs=len(tsi), traffic_selector=tsi
+ )
+ / ikev2.IKEv2_payload_TSr(
+ next_payload=last_payload, number_of_TSs=len(tsr), traffic_selector=tsr
+ )
+ )
if is_rekey:
- first_payload = 'Nonce'
- plain = (ikev2.IKEv2_payload_Nonce(load=self.sa.i_nonce,
- next_payload='SA') / plain /
- ikev2.IKEv2_payload_Notify(type='REKEY_SA',
- proto='ESP', SPI=c.ispi))
+ first_payload = "Nonce"
+ plain = (
+ ikev2.IKEv2_payload_Nonce(load=self.sa.i_nonce, next_payload="SA")
+ / plain
+ / ikev2.IKEv2_payload_Notify(type="REKEY_SA", proto="ESP", SPI=c.ispi)
+ )
else:
- first_payload = 'IDi'
+ first_payload = "IDi"
if self.no_idr_auth:
- ids = ikev2.IKEv2_payload_IDi(next_payload='AUTH',
- IDtype=self.sa.id_type,
- load=self.sa.i_id)
+ ids = ikev2.IKEv2_payload_IDi(
+ next_payload="AUTH", IDtype=self.sa.id_type, load=self.sa.i_id
+ )
else:
- ids = (ikev2.IKEv2_payload_IDi(next_payload='IDr',
- IDtype=self.sa.id_type, load=self.sa.i_id) /
- ikev2.IKEv2_payload_IDr(next_payload='AUTH',
- IDtype=self.sa.id_type, load=self.sa.r_id))
+ ids = ikev2.IKEv2_payload_IDi(
+ next_payload="IDr", IDtype=self.sa.id_type, load=self.sa.i_id
+ ) / ikev2.IKEv2_payload_IDr(
+ next_payload="AUTH", IDtype=self.sa.id_type, load=self.sa.r_id
+ )
plain = ids / plain
return plain, first_payload
def send_sa_auth(self):
- plain, first_payload = self.generate_auth_payload(
- last_payload='Notify')
- plain = plain / ikev2.IKEv2_payload_Notify(type='INITIAL_CONTACT')
+ plain, first_payload = self.generate_auth_payload(last_payload="Notify")
+ plain = plain / ikev2.IKEv2_payload_Notify(type="INITIAL_CONTACT")
header = ikev2.IKEv2(
- init_SPI=self.sa.ispi,
- resp_SPI=self.sa.rspi, id=self.sa.new_msg_id(),
- flags='Initiator', exch_type='IKE_AUTH')
+ init_SPI=self.sa.ispi,
+ resp_SPI=self.sa.rspi,
+ id=self.sa.new_msg_id(),
+ flags="Initiator",
+ exch_type="IKE_AUTH",
+ )
ike_msg = self.encrypt_ike_msg(header, plain, first_payload)
- packet = self.create_packet(self.pg0, ike_msg, self.sa.sport,
- self.sa.dport, self.sa.natt, self.ip6)
+ packet = self.create_packet(
+ self.pg0, ike_msg, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6
+ )
self.pg0.add_stream(packet)
self.pg0.enable_capture()
self.pg_start()
@@ -1303,7 +1434,7 @@ class TemplateResponder(IkePeer):
self.assertEqual(ih.id, self.sa.msg_id)
self.assertEqual(ih.exch_type, 34)
- self.assertIn('Response', ih.flags)
+ self.assertIn("Response", ih.flags)
self.assertEqual(ih.init_SPI, self.sa.ispi)
self.assertNotEqual(ih.resp_SPI, 0)
self.sa.rspi = ih.resp_SPI
@@ -1331,12 +1462,12 @@ class TemplateResponder(IkePeer):
self.sa.child_sas[0].rspi = prop.SPI
self.sa.calc_child_keys()
- IKE_NODE_SUFFIX = 'ip4'
+ IKE_NODE_SUFFIX = "ip4"
def verify_counters(self):
- self.assert_counter(2, 'processed', self.IKE_NODE_SUFFIX)
- self.assert_counter(1, 'init_sa_req', self.IKE_NODE_SUFFIX)
- self.assert_counter(1, 'ike_auth_req', self.IKE_NODE_SUFFIX)
+ self.assert_counter(2, "processed", self.IKE_NODE_SUFFIX)
+ self.assert_counter(1, "init_sa_req", self.IKE_NODE_SUFFIX)
+ self.assert_counter(1, "ike_auth_req", self.IKE_NODE_SUFFIX)
r = self.vapi.ikev2_sa_dump()
s = r[0].sa.stats
@@ -1356,59 +1487,60 @@ class Ikev2Params(object):
ec = VppEnum.vl_api_ipsec_crypto_alg_t
ei = VppEnum.vl_api_ipsec_integ_alg_t
self.vpp_enums = {
- 'AES-CBC-128': ec.IPSEC_API_CRYPTO_ALG_AES_CBC_128,
- 'AES-CBC-192': ec.IPSEC_API_CRYPTO_ALG_AES_CBC_192,
- 'AES-CBC-256': ec.IPSEC_API_CRYPTO_ALG_AES_CBC_256,
- 'AES-GCM-16ICV-128': ec.IPSEC_API_CRYPTO_ALG_AES_GCM_128,
- 'AES-GCM-16ICV-192': ec.IPSEC_API_CRYPTO_ALG_AES_GCM_192,
- 'AES-GCM-16ICV-256': ec.IPSEC_API_CRYPTO_ALG_AES_GCM_256,
-
- 'HMAC-SHA1-96': ei.IPSEC_API_INTEG_ALG_SHA1_96,
- 'SHA2-256-128': ei.IPSEC_API_INTEG_ALG_SHA_256_128,
- 'SHA2-384-192': ei.IPSEC_API_INTEG_ALG_SHA_384_192,
- 'SHA2-512-256': ei.IPSEC_API_INTEG_ALG_SHA_512_256}
-
- dpd_disabled = True if 'dpd_disabled' not in params else\
- params['dpd_disabled']
+ "AES-CBC-128": ec.IPSEC_API_CRYPTO_ALG_AES_CBC_128,
+ "AES-CBC-192": ec.IPSEC_API_CRYPTO_ALG_AES_CBC_192,
+ "AES-CBC-256": ec.IPSEC_API_CRYPTO_ALG_AES_CBC_256,
+ "AES-GCM-16ICV-128": ec.IPSEC_API_CRYPTO_ALG_AES_GCM_128,
+ "AES-GCM-16ICV-192": ec.IPSEC_API_CRYPTO_ALG_AES_GCM_192,
+ "AES-GCM-16ICV-256": ec.IPSEC_API_CRYPTO_ALG_AES_GCM_256,
+ "HMAC-SHA1-96": ei.IPSEC_API_INTEG_ALG_SHA1_96,
+ "SHA2-256-128": ei.IPSEC_API_INTEG_ALG_SHA_256_128,
+ "SHA2-384-192": ei.IPSEC_API_INTEG_ALG_SHA_384_192,
+ "SHA2-512-256": ei.IPSEC_API_INTEG_ALG_SHA_512_256,
+ }
+
+ dpd_disabled = True if "dpd_disabled" not in params else params["dpd_disabled"]
if dpd_disabled:
- self.vapi.cli('ikev2 dpd disable')
- self.del_sa_from_responder = False if 'del_sa_from_responder'\
- not in params else params['del_sa_from_responder']
- i_natt = False if 'i_natt' not in params else params['i_natt']
- r_natt = False if 'r_natt' not in params else params['r_natt']
- self.p = Profile(self, 'pr1')
- self.ip6 = False if 'ip6' not in params else params['ip6']
-
- if 'auth' in params and params['auth'] == 'rsa-sig':
- auth_method = 'rsa-sig'
+ self.vapi.cli("ikev2 dpd disable")
+ self.del_sa_from_responder = (
+ False
+ if "del_sa_from_responder" not in params
+ else params["del_sa_from_responder"]
+ )
+ i_natt = False if "i_natt" not in params else params["i_natt"]
+ r_natt = False if "r_natt" not in params else params["r_natt"]
+ self.p = Profile(self, "pr1")
+ self.ip6 = False if "ip6" not in params else params["ip6"]
+
+ if "auth" in params and params["auth"] == "rsa-sig":
+ auth_method = "rsa-sig"
work_dir = f"{config.vpp_ws_dir}/src/plugins/ikev2/test/certs/"
- self.vapi.ikev2_set_local_key(
- key_file=work_dir + params['server-key'])
-
- client_file = work_dir + params['client-cert']
- server_pem = open(work_dir + params['server-cert']).read()
- client_priv = open(work_dir + params['client-key']).read()
- client_priv = load_pem_private_key(str.encode(client_priv), None,
- default_backend())
+ self.vapi.ikev2_set_local_key(key_file=work_dir + params["server-key"])
+
+ client_file = work_dir + params["client-cert"]
+ server_pem = open(work_dir + params["server-cert"]).read()
+ client_priv = open(work_dir + params["client-key"]).read()
+ client_priv = load_pem_private_key(
+ str.encode(client_priv), None, default_backend()
+ )
self.peer_cert = x509.load_pem_x509_certificate(
- str.encode(server_pem),
- default_backend())
- self.p.add_auth(method='rsa-sig', data=str.encode(client_file))
+ str.encode(server_pem), default_backend()
+ )
+ self.p.add_auth(method="rsa-sig", data=str.encode(client_file))
auth_data = None
else:
- auth_data = b'$3cr3tpa$$w0rd'
- self.p.add_auth(method='shared-key', data=auth_data)
- auth_method = 'shared-key'
+ auth_data = b"$3cr3tpa$$w0rd"
+ self.p.add_auth(method="shared-key", data=auth_data)
+ auth_method = "shared-key"
client_priv = None
- is_init = True if 'is_initiator' not in params else\
- params['is_initiator']
- self.no_idr_auth = params.get('no_idr_in_auth', False)
+ is_init = True if "is_initiator" not in params else params["is_initiator"]
+ self.no_idr_auth = params.get("no_idr_in_auth", False)
- idr = {'id_type': 'fqdn', 'data': b'vpp.home'}
- idi = {'id_type': 'fqdn', 'data': b'roadwarrior.example.com'}
- r_id = self.idr = idr['data']
- i_id = self.idi = idi['data']
+ idr = {"id_type": "fqdn", "data": b"vpp.home"}
+ idi = {"id_type": "fqdn", "data": b"roadwarrior.example.com"}
+ r_id = self.idr = idr["data"]
+ i_id = self.idi = idi["data"]
if is_init:
# scapy is initiator, VPP is responder
self.p.add_local_id(**idr)
@@ -1421,70 +1553,90 @@ class Ikev2Params(object):
if not self.no_idr_auth:
self.p.add_remote_id(**idr)
- loc_ts = {'start_addr': '10.10.10.0', 'end_addr': '10.10.10.255'} if\
- 'loc_ts' not in params else params['loc_ts']
- rem_ts = {'start_addr': '10.0.0.0', 'end_addr': '10.0.0.255'} if\
- 'rem_ts' not in params else params['rem_ts']
+ loc_ts = (
+ {"start_addr": "10.10.10.0", "end_addr": "10.10.10.255"}
+ if "loc_ts" not in params
+ else params["loc_ts"]
+ )
+ rem_ts = (
+ {"start_addr": "10.0.0.0", "end_addr": "10.0.0.255"}
+ if "rem_ts" not in params
+ else params["rem_ts"]
+ )
self.p.add_local_ts(**loc_ts)
self.p.add_remote_ts(**rem_ts)
- if 'responder' in params:
- self.p.add_responder(params['responder'])
- if 'ike_transforms' in params:
- self.p.add_ike_transforms(params['ike_transforms'])
- if 'esp_transforms' in params:
- self.p.add_esp_transforms(params['esp_transforms'])
-
- udp_encap = False if 'udp_encap' not in params else\
- params['udp_encap']
+ if "responder" in params:
+ self.p.add_responder(params["responder"])
+ if "ike_transforms" in params:
+ self.p.add_ike_transforms(params["ike_transforms"])
+ if "esp_transforms" in params:
+ self.p.add_esp_transforms(params["esp_transforms"])
+
+ udp_encap = False if "udp_encap" not in params else params["udp_encap"]
if udp_encap:
self.p.set_udp_encap(True)
- if 'responder_hostname' in params:
- hn = params['responder_hostname']
+ if "responder_hostname" in params:
+ hn = params["responder_hostname"]
self.p.add_responder_hostname(hn)
# configure static dns record
self.vapi.dns_name_server_add_del(
- is_ip6=0, is_add=1,
- server_address=IPv4Address(u'8.8.8.8').packed)
+ is_ip6=0, is_add=1, server_address=IPv4Address("8.8.8.8").packed
+ )
self.vapi.dns_enable_disable(enable=1)
- cmd = "dns cache add {} {}".format(hn['hostname'],
- self.pg0.remote_ip4)
+ cmd = "dns cache add {} {}".format(hn["hostname"], self.pg0.remote_ip4)
self.vapi.cli(cmd)
- self.sa = IKEv2SA(self, i_id=i_id, r_id=r_id,
- is_initiator=is_init,
- id_type=self.p.local_id['id_type'],
- i_natt=i_natt, r_natt=r_natt,
- priv_key=client_priv, auth_method=auth_method,
- nonce=params.get('nonce'),
- auth_data=auth_data, udp_encap=udp_encap,
- local_ts=self.p.remote_ts, remote_ts=self.p.local_ts)
+ self.sa = IKEv2SA(
+ self,
+ i_id=i_id,
+ r_id=r_id,
+ is_initiator=is_init,
+ id_type=self.p.local_id["id_type"],
+ i_natt=i_natt,
+ r_natt=r_natt,
+ priv_key=client_priv,
+ auth_method=auth_method,
+ nonce=params.get("nonce"),
+ auth_data=auth_data,
+ udp_encap=udp_encap,
+ local_ts=self.p.remote_ts,
+ remote_ts=self.p.local_ts,
+ )
if is_init:
- ike_crypto = ('AES-CBC', 32) if 'ike-crypto' not in params else\
- params['ike-crypto']
- ike_integ = 'HMAC-SHA1-96' if 'ike-integ' not in params else\
- params['ike-integ']
- ike_dh = '2048MODPgr' if 'ike-dh' not in params else\
- params['ike-dh']
-
- esp_crypto = ('AES-CBC', 32) if 'esp-crypto' not in params else\
- params['esp-crypto']
- esp_integ = 'HMAC-SHA1-96' if 'esp-integ' not in params else\
- params['esp-integ']
+ ike_crypto = (
+ ("AES-CBC", 32) if "ike-crypto" not in params else params["ike-crypto"]
+ )
+ ike_integ = (
+ "HMAC-SHA1-96" if "ike-integ" not in params else params["ike-integ"]
+ )
+ ike_dh = "2048MODPgr" if "ike-dh" not in params else params["ike-dh"]
+
+ esp_crypto = (
+ ("AES-CBC", 32) if "esp-crypto" not in params else params["esp-crypto"]
+ )
+ esp_integ = (
+ "HMAC-SHA1-96" if "esp-integ" not in params else params["esp-integ"]
+ )
self.sa.set_ike_props(
- crypto=ike_crypto[0], crypto_key_len=ike_crypto[1],
- integ=ike_integ, prf='PRF_HMAC_SHA2_256', dh=ike_dh)
+ crypto=ike_crypto[0],
+ crypto_key_len=ike_crypto[1],
+ integ=ike_integ,
+ prf="PRF_HMAC_SHA2_256",
+ dh=ike_dh,
+ )
self.sa.set_esp_props(
- crypto=esp_crypto[0], crypto_key_len=esp_crypto[1],
- integ=esp_integ)
+ crypto=esp_crypto[0], crypto_key_len=esp_crypto[1], integ=esp_integ
+ )
class TestApi(VppTestCase):
- """ Test IKEV2 API """
+ """Test IKEV2 API"""
+
@classmethod
def setUpClass(cls):
super(TestApi, cls).setUpClass()
@@ -1501,241 +1653,249 @@ class TestApi(VppTestCase):
self.assertEqual(len(r), 0)
def configure_profile(self, cfg):
- p = Profile(self, cfg['name'])
- p.add_local_id(id_type=cfg['loc_id'][0], data=cfg['loc_id'][1])
- p.add_remote_id(id_type=cfg['rem_id'][0], data=cfg['rem_id'][1])
- p.add_local_ts(**cfg['loc_ts'])
- p.add_remote_ts(**cfg['rem_ts'])
- p.add_responder(cfg['responder'])
- p.add_ike_transforms(cfg['ike_ts'])
- p.add_esp_transforms(cfg['esp_ts'])
- p.add_auth(**cfg['auth'])
- p.set_udp_encap(cfg['udp_encap'])
- p.set_ipsec_over_udp_port(cfg['ipsec_over_udp_port'])
- if 'lifetime_data' in cfg:
- p.set_lifetime_data(cfg['lifetime_data'])
- if 'tun_itf' in cfg:
- p.set_tunnel_interface(cfg['tun_itf'])
- if 'natt_disabled' in cfg and cfg['natt_disabled']:
+ p = Profile(self, cfg["name"])
+ p.add_local_id(id_type=cfg["loc_id"][0], data=cfg["loc_id"][1])
+ p.add_remote_id(id_type=cfg["rem_id"][0], data=cfg["rem_id"][1])
+ p.add_local_ts(**cfg["loc_ts"])
+ p.add_remote_ts(**cfg["rem_ts"])
+ p.add_responder(cfg["responder"])
+ p.add_ike_transforms(cfg["ike_ts"])
+ p.add_esp_transforms(cfg["esp_ts"])
+ p.add_auth(**cfg["auth"])
+ p.set_udp_encap(cfg["udp_encap"])
+ p.set_ipsec_over_udp_port(cfg["ipsec_over_udp_port"])
+ if "lifetime_data" in cfg:
+ p.set_lifetime_data(cfg["lifetime_data"])
+ if "tun_itf" in cfg:
+ p.set_tunnel_interface(cfg["tun_itf"])
+ if "natt_disabled" in cfg and cfg["natt_disabled"]:
p.disable_natt()
p.add_vpp_config()
return p
def test_profile_api(self):
- """ test profile dump API """
+ """test profile dump API"""
loc_ts4 = {
- 'proto': 8,
- 'start_port': 1,
- 'end_port': 19,
- 'start_addr': '3.3.3.2',
- 'end_addr': '3.3.3.3',
- }
+ "proto": 8,
+ "start_port": 1,
+ "end_port": 19,
+ "start_addr": "3.3.3.2",
+ "end_addr": "3.3.3.3",
+ }
rem_ts4 = {
- 'proto': 9,
- 'start_port': 10,
- 'end_port': 119,
- 'start_addr': '4.5.76.80',
- 'end_addr': '2.3.4.6',
- }
+ "proto": 9,
+ "start_port": 10,
+ "end_port": 119,
+ "start_addr": "4.5.76.80",
+ "end_addr": "2.3.4.6",
+ }
loc_ts6 = {
- 'proto': 8,
- 'start_port': 1,
- 'end_port': 19,
- 'start_addr': 'ab::1',
- 'end_addr': 'ab::4',
- }
+ "proto": 8,
+ "start_port": 1,
+ "end_port": 19,
+ "start_addr": "ab::1",
+ "end_addr": "ab::4",
+ }
rem_ts6 = {
- 'proto': 9,
- 'start_port': 10,
- 'end_port': 119,
- 'start_addr': 'cd::12',
- 'end_addr': 'cd::13',
- }
+ "proto": 9,
+ "start_port": 10,
+ "end_port": 119,
+ "start_addr": "cd::12",
+ "end_addr": "cd::13",
+ }
conf = {
- 'p1': {
- 'name': 'p1',
- 'natt_disabled': True,
- 'loc_id': ('fqdn', b'vpp.home'),
- 'rem_id': ('fqdn', b'roadwarrior.example.com'),
- 'loc_ts': loc_ts4,
- 'rem_ts': rem_ts4,
- 'responder': {'sw_if_index': 0, 'addr': '5.6.7.8'},
- 'ike_ts': {
- 'crypto_alg': 20,
- 'crypto_key_size': 32,
- 'integ_alg': 0,
- 'dh_group': 1},
- 'esp_ts': {
- 'crypto_alg': 13,
- 'crypto_key_size': 24,
- 'integ_alg': 2},
- 'auth': {'method': 'shared-key', 'data': b'sharedkeydata'},
- 'udp_encap': True,
- 'ipsec_over_udp_port': 4501,
- 'lifetime_data': {
- 'lifetime': 123,
- 'lifetime_maxdata': 20192,
- 'lifetime_jitter': 9,
- 'handover': 132},
+ "p1": {
+ "name": "p1",
+ "natt_disabled": True,
+ "loc_id": ("fqdn", b"vpp.home"),
+ "rem_id": ("fqdn", b"roadwarrior.example.com"),
+ "loc_ts": loc_ts4,
+ "rem_ts": rem_ts4,
+ "responder": {"sw_if_index": 0, "addr": "5.6.7.8"},
+ "ike_ts": {
+ "crypto_alg": 20,
+ "crypto_key_size": 32,
+ "integ_alg": 0,
+ "dh_group": 1,
+ },
+ "esp_ts": {"crypto_alg": 13, "crypto_key_size": 24, "integ_alg": 2},
+ "auth": {"method": "shared-key", "data": b"sharedkeydata"},
+ "udp_encap": True,
+ "ipsec_over_udp_port": 4501,
+ "lifetime_data": {
+ "lifetime": 123,
+ "lifetime_maxdata": 20192,
+ "lifetime_jitter": 9,
+ "handover": 132,
+ },
+ },
+ "p2": {
+ "name": "p2",
+ "loc_id": ("ip4-addr", b"192.168.2.1"),
+ "rem_id": ("ip6-addr", b"abcd::1"),
+ "loc_ts": loc_ts6,
+ "rem_ts": rem_ts6,
+ "responder": {"sw_if_index": 4, "addr": "def::10"},
+ "ike_ts": {
+ "crypto_alg": 12,
+ "crypto_key_size": 16,
+ "integ_alg": 3,
+ "dh_group": 3,
+ },
+ "esp_ts": {"crypto_alg": 9, "crypto_key_size": 24, "integ_alg": 4},
+ "auth": {"method": "shared-key", "data": b"sharedkeydata"},
+ "udp_encap": False,
+ "ipsec_over_udp_port": 4600,
+ "tun_itf": 0,
},
- 'p2': {
- 'name': 'p2',
- 'loc_id': ('ip4-addr', b'192.168.2.1'),
- 'rem_id': ('ip6-addr', b'abcd::1'),
- 'loc_ts': loc_ts6,
- 'rem_ts': rem_ts6,
- 'responder': {'sw_if_index': 4, 'addr': 'def::10'},
- 'ike_ts': {
- 'crypto_alg': 12,
- 'crypto_key_size': 16,
- 'integ_alg': 3,
- 'dh_group': 3},
- 'esp_ts': {
- 'crypto_alg': 9,
- 'crypto_key_size': 24,
- 'integ_alg': 4},
- 'auth': {'method': 'shared-key', 'data': b'sharedkeydata'},
- 'udp_encap': False,
- 'ipsec_over_udp_port': 4600,
- 'tun_itf': 0}
}
- self.p1 = self.configure_profile(conf['p1'])
- self.p2 = self.configure_profile(conf['p2'])
+ self.p1 = self.configure_profile(conf["p1"])
+ self.p2 = self.configure_profile(conf["p2"])
r = self.vapi.ikev2_profile_dump()
self.assertEqual(len(r), 2)
- self.verify_profile(r[0].profile, conf['p1'])
- self.verify_profile(r[1].profile, conf['p2'])
+ self.verify_profile(r[0].profile, conf["p1"])
+ self.verify_profile(r[1].profile, conf["p2"])
def verify_id(self, api_id, cfg_id):
self.assertEqual(api_id.type, IDType.value(cfg_id[0]))
- self.assertEqual(bytes(api_id.data, 'ascii'), cfg_id[1])
+ self.assertEqual(bytes(api_id.data, "ascii"), cfg_id[1])
def verify_ts(self, api_ts, cfg_ts):
- self.assertEqual(api_ts.protocol_id, cfg_ts['proto'])
- self.assertEqual(api_ts.start_port, cfg_ts['start_port'])
- self.assertEqual(api_ts.end_port, cfg_ts['end_port'])
- self.assertEqual(api_ts.start_addr,
- ip_address(text_type(cfg_ts['start_addr'])))
- self.assertEqual(api_ts.end_addr,
- ip_address(text_type(cfg_ts['end_addr'])))
+ self.assertEqual(api_ts.protocol_id, cfg_ts["proto"])
+ self.assertEqual(api_ts.start_port, cfg_ts["start_port"])
+ self.assertEqual(api_ts.end_port, cfg_ts["end_port"])
+ self.assertEqual(api_ts.start_addr, ip_address(text_type(cfg_ts["start_addr"])))
+ self.assertEqual(api_ts.end_addr, ip_address(text_type(cfg_ts["end_addr"])))
def verify_responder(self, api_r, cfg_r):
- self.assertEqual(api_r.sw_if_index, cfg_r['sw_if_index'])
- self.assertEqual(api_r.addr, ip_address(cfg_r['addr']))
+ self.assertEqual(api_r.sw_if_index, cfg_r["sw_if_index"])
+ self.assertEqual(api_r.addr, ip_address(cfg_r["addr"]))
def verify_transforms(self, api_ts, cfg_ts):
- self.assertEqual(api_ts.crypto_alg, cfg_ts['crypto_alg'])
- self.assertEqual(api_ts.crypto_key_size, cfg_ts['crypto_key_size'])
- self.assertEqual(api_ts.integ_alg, cfg_ts['integ_alg'])
+ self.assertEqual(api_ts.crypto_alg, cfg_ts["crypto_alg"])
+ self.assertEqual(api_ts.crypto_key_size, cfg_ts["crypto_key_size"])
+ self.assertEqual(api_ts.integ_alg, cfg_ts["integ_alg"])
def verify_ike_transforms(self, api_ts, cfg_ts):
self.verify_transforms(api_ts, cfg_ts)
- self.assertEqual(api_ts.dh_group, cfg_ts['dh_group'])
+ self.assertEqual(api_ts.dh_group, cfg_ts["dh_group"])
def verify_esp_transforms(self, api_ts, cfg_ts):
self.verify_transforms(api_ts, cfg_ts)
def verify_auth(self, api_auth, cfg_auth):
- self.assertEqual(api_auth.method, AuthMethod.value(cfg_auth['method']))
- self.assertEqual(api_auth.data, cfg_auth['data'])
- self.assertEqual(api_auth.data_len, len(cfg_auth['data']))
+ self.assertEqual(api_auth.method, AuthMethod.value(cfg_auth["method"]))
+ self.assertEqual(api_auth.data, cfg_auth["data"])
+ self.assertEqual(api_auth.data_len, len(cfg_auth["data"]))
def verify_lifetime_data(self, p, ld):
- self.assertEqual(p.lifetime, ld['lifetime'])
- self.assertEqual(p.lifetime_maxdata, ld['lifetime_maxdata'])
- self.assertEqual(p.lifetime_jitter, ld['lifetime_jitter'])
- self.assertEqual(p.handover, ld['handover'])
+ self.assertEqual(p.lifetime, ld["lifetime"])
+ self.assertEqual(p.lifetime_maxdata, ld["lifetime_maxdata"])
+ self.assertEqual(p.lifetime_jitter, ld["lifetime_jitter"])
+ self.assertEqual(p.handover, ld["handover"])
def verify_profile(self, ap, cp):
- self.assertEqual(ap.name, cp['name'])
- self.assertEqual(ap.udp_encap, cp['udp_encap'])
- self.verify_id(ap.loc_id, cp['loc_id'])
- self.verify_id(ap.rem_id, cp['rem_id'])
- self.verify_ts(ap.loc_ts, cp['loc_ts'])
- self.verify_ts(ap.rem_ts, cp['rem_ts'])
- self.verify_responder(ap.responder, cp['responder'])
- self.verify_ike_transforms(ap.ike_ts, cp['ike_ts'])
- self.verify_esp_transforms(ap.esp_ts, cp['esp_ts'])
- self.verify_auth(ap.auth, cp['auth'])
- natt_dis = False if 'natt_disabled' not in cp else cp['natt_disabled']
+ self.assertEqual(ap.name, cp["name"])
+ self.assertEqual(ap.udp_encap, cp["udp_encap"])
+ self.verify_id(ap.loc_id, cp["loc_id"])
+ self.verify_id(ap.rem_id, cp["rem_id"])
+ self.verify_ts(ap.loc_ts, cp["loc_ts"])
+ self.verify_ts(ap.rem_ts, cp["rem_ts"])
+ self.verify_responder(ap.responder, cp["responder"])
+ self.verify_ike_transforms(ap.ike_ts, cp["ike_ts"])
+ self.verify_esp_transforms(ap.esp_ts, cp["esp_ts"])
+ self.verify_auth(ap.auth, cp["auth"])
+ natt_dis = False if "natt_disabled" not in cp else cp["natt_disabled"]
self.assertTrue(natt_dis == ap.natt_disabled)
- if 'lifetime_data' in cp:
- self.verify_lifetime_data(ap, cp['lifetime_data'])
- self.assertEqual(ap.ipsec_over_udp_port, cp['ipsec_over_udp_port'])
- if 'tun_itf' in cp:
- self.assertEqual(ap.tun_itf, cp['tun_itf'])
+ if "lifetime_data" in cp:
+ self.verify_lifetime_data(ap, cp["lifetime_data"])
+ self.assertEqual(ap.ipsec_over_udp_port, cp["ipsec_over_udp_port"])
+ if "tun_itf" in cp:
+ self.assertEqual(ap.tun_itf, cp["tun_itf"])
else:
- self.assertEqual(ap.tun_itf, 0xffffffff)
+ self.assertEqual(ap.tun_itf, 0xFFFFFFFF)
@tag_fixme_vpp_workers
class TestResponderBehindNAT(TemplateResponder, Ikev2Params):
- """ test responder - responder behind NAT """
+ """test responder - responder behind NAT"""
- IKE_NODE_SUFFIX = 'ip4-natt'
+ IKE_NODE_SUFFIX = "ip4-natt"
def config_tc(self):
- self.config_params({'r_natt': True})
+ self.config_params({"r_natt": True})
@tag_fixme_vpp_workers
class TestInitiatorNATT(TemplateInitiator, Ikev2Params):
- """ test ikev2 initiator - NAT traversal (intitiator behind NAT) """
+ """test ikev2 initiator - NAT traversal (intitiator behind NAT)"""
def config_tc(self):
- self.config_params({
- 'i_natt': True,
- 'is_initiator': False, # seen from test case perspective
- # thus vpp is initiator
- 'responder': {'sw_if_index': self.pg0.sw_if_index,
- 'addr': self.pg0.remote_ip4},
- 'ike-crypto': ('AES-GCM-16ICV', 32),
- 'ike-integ': 'NULL',
- 'ike-dh': '3072MODPgr',
- 'ike_transforms': {
- 'crypto_alg': 20, # "aes-gcm-16"
- 'crypto_key_size': 256,
- 'dh_group': 15, # "modp-3072"
- },
- 'esp_transforms': {
- 'crypto_alg': 12, # "aes-cbc"
- 'crypto_key_size': 256,
- # "hmac-sha2-256-128"
- 'integ_alg': 12}})
+ self.config_params(
+ {
+ "i_natt": True,
+ "is_initiator": False, # seen from test case perspective
+ # thus vpp is initiator
+ "responder": {
+ "sw_if_index": self.pg0.sw_if_index,
+ "addr": self.pg0.remote_ip4,
+ },
+ "ike-crypto": ("AES-GCM-16ICV", 32),
+ "ike-integ": "NULL",
+ "ike-dh": "3072MODPgr",
+ "ike_transforms": {
+ "crypto_alg": 20, # "aes-gcm-16"
+ "crypto_key_size": 256,
+ "dh_group": 15, # "modp-3072"
+ },
+ "esp_transforms": {
+ "crypto_alg": 12, # "aes-cbc"
+ "crypto_key_size": 256,
+ # "hmac-sha2-256-128"
+ "integ_alg": 12,
+ },
+ }
+ )
@tag_fixme_vpp_workers
class TestInitiatorPsk(TemplateInitiator, Ikev2Params):
- """ test ikev2 initiator - pre shared key auth """
+ """test ikev2 initiator - pre shared key auth"""
def config_tc(self):
- self.config_params({
- 'is_initiator': False, # seen from test case perspective
- # thus vpp is initiator
- 'ike-crypto': ('AES-GCM-16ICV', 32),
- 'ike-integ': 'NULL',
- 'ike-dh': '3072MODPgr',
- 'ike_transforms': {
- 'crypto_alg': 20, # "aes-gcm-16"
- 'crypto_key_size': 256,
- 'dh_group': 15, # "modp-3072"
- },
- 'esp_transforms': {
- 'crypto_alg': 12, # "aes-cbc"
- 'crypto_key_size': 256,
- # "hmac-sha2-256-128"
- 'integ_alg': 12},
- 'responder_hostname': {'hostname': 'vpp.responder.org',
- 'sw_if_index': self.pg0.sw_if_index}})
+ self.config_params(
+ {
+ "is_initiator": False, # seen from test case perspective
+ # thus vpp is initiator
+ "ike-crypto": ("AES-GCM-16ICV", 32),
+ "ike-integ": "NULL",
+ "ike-dh": "3072MODPgr",
+ "ike_transforms": {
+ "crypto_alg": 20, # "aes-gcm-16"
+ "crypto_key_size": 256,
+ "dh_group": 15, # "modp-3072"
+ },
+ "esp_transforms": {
+ "crypto_alg": 12, # "aes-cbc"
+ "crypto_key_size": 256,
+ # "hmac-sha2-256-128"
+ "integ_alg": 12,
+ },
+ "responder_hostname": {
+ "hostname": "vpp.responder.org",
+ "sw_if_index": self.pg0.sw_if_index,
+ },
+ }
+ )
@tag_fixme_vpp_workers
class TestInitiatorRequestWindowSize(TestInitiatorPsk):
- """ test initiator - request window size (1) """
+ """test initiator - request window size (1)"""
def rekey_respond(self, req, update_child_sa_data):
ih = self.get_ike_header(req)
@@ -1749,19 +1909,25 @@ class TestInitiatorRequestWindowSize(TestInitiatorPsk):
self.sa.child_sas[0].rspi = prop.SPI
self.sa.calc_child_keys()
- header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi,
- flags='Response', exch_type=36,
- id=ih.id, next_payload='Encrypted')
- resp = self.encrypt_ike_msg(header, sa, 'SA')
- packet = self.create_packet(self.pg0, resp, self.sa.sport,
- self.sa.dport, self.sa.natt, self.ip6)
+ header = ikev2.IKEv2(
+ init_SPI=self.sa.ispi,
+ resp_SPI=self.sa.rspi,
+ flags="Response",
+ exch_type=36,
+ id=ih.id,
+ next_payload="Encrypted",
+ )
+ resp = self.encrypt_ike_msg(header, sa, "SA")
+ packet = self.create_packet(
+ self.pg0, resp, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6
+ )
self.send_and_assert_no_replies(self.pg0, packet)
def test_initiator(self):
super(TestInitiatorRequestWindowSize, self).test_initiator()
self.pg0.enable_capture()
self.pg_start()
- ispi = int.from_bytes(self.sa.child_sas[0].ispi, 'little')
+ ispi = int.from_bytes(self.sa.child_sas[0].ispi, "little")
self.vapi.ikev2_initiate_rekey_child_sa(ispi=ispi)
self.vapi.ikev2_initiate_rekey_child_sa(ispi=ispi)
capture = self.pg0.get_capture(2)
@@ -1777,18 +1943,18 @@ class TestInitiatorRequestWindowSize(TestInitiatorPsk):
@tag_fixme_vpp_workers
class TestInitiatorRekey(TestInitiatorPsk):
- """ test ikev2 initiator - rekey """
+ """test ikev2 initiator - rekey"""
def rekey_from_initiator(self):
- ispi = int.from_bytes(self.sa.child_sas[0].ispi, 'little')
+ ispi = int.from_bytes(self.sa.child_sas[0].ispi, "little")
self.pg0.enable_capture()
self.pg_start()
self.vapi.ikev2_initiate_rekey_child_sa(ispi=ispi)
capture = self.pg0.get_capture(1)
ih = self.get_ike_header(capture[0])
self.assertEqual(ih.exch_type, 36) # CHILD_SA
- self.assertNotIn('Response', ih.flags)
- self.assertIn('Initiator', ih.flags)
+ self.assertNotIn("Response", ih.flags)
+ self.assertIn("Initiator", ih.flags)
plain = self.sa.hmac_and_decrypt(ih)
sa = ikev2.IKEv2_payload_SA(plain)
prop = sa[ikev2.IKEv2_payload_Proposal]
@@ -1798,12 +1964,18 @@ class TestInitiatorRekey(TestInitiatorPsk):
self.sa.child_sas[0].ispi = prop.SPI
self.sa.child_sas[0].rspi = prop.SPI
self.sa.calc_child_keys()
- header = ikev2.IKEv2(init_SPI=self.sa.ispi, resp_SPI=self.sa.rspi,
- flags='Response', exch_type=36,
- id=ih.id, next_payload='Encrypted')
- resp = self.encrypt_ike_msg(header, sa, 'SA')
- packet = self.create_packet(self.pg0, resp, self.sa.sport,
- self.sa.dport, self.sa.natt, self.ip6)
+ header = ikev2.IKEv2(
+ init_SPI=self.sa.ispi,
+ resp_SPI=self.sa.rspi,
+ flags="Response",
+ exch_type=36,
+ id=ih.id,
+ next_payload="Encrypted",
+ )
+ resp = self.encrypt_ike_msg(header, sa, "SA")
+ packet = self.create_packet(
+ self.pg0, resp, self.sa.sport, self.sa.dport, self.sa.natt, self.ip6
+ )
self.send_and_assert_no_replies(self.pg0, packet)
def test_initiator(self):
@@ -1815,45 +1987,51 @@ class TestInitiatorRekey(TestInitiatorPsk):
@tag_fixme_vpp_workers
class TestInitiatorDelSAFromResponder(TemplateInitiator, Ikev2Params):
- """ test ikev2 initiator - delete IKE SA from responder """
+ """test ikev2 initiator - delete IKE SA from responder"""
def config_tc(self):
- self.config_params({
- 'del_sa_from_responder': True,
- 'is_initiator': False, # seen from test case perspective
- # thus vpp is initiator
- 'responder': {'sw_if_index': self.pg0.sw_if_index,
- 'addr': self.pg0.remote_ip4},
- 'ike-crypto': ('AES-GCM-16ICV', 32),
- 'ike-integ': 'NULL',
- 'ike-dh': '3072MODPgr',
- 'ike_transforms': {
- 'crypto_alg': 20, # "aes-gcm-16"
- 'crypto_key_size': 256,
- 'dh_group': 15, # "modp-3072"
- },
- 'esp_transforms': {
- 'crypto_alg': 12, # "aes-cbc"
- 'crypto_key_size': 256,
- # "hmac-sha2-256-128"
- 'integ_alg': 12},
- 'no_idr_in_auth': True})
+ self.config_params(
+ {
+ "del_sa_from_responder": True,
+ "is_initiator": False, # seen from test case perspective
+ # thus vpp is initiator
+ "responder": {
+ "sw_if_index": self.pg0.sw_if_index,
+ "addr": self.pg0.remote_ip4,
+ },
+ "ike-crypto": ("AES-GCM-16ICV", 32),
+ "ike-integ": "NULL",
+ "ike-dh": "3072MODPgr",
+ "ike_transforms": {
+ "crypto_alg": 20, # "aes-gcm-16"
+ "crypto_key_size": 256,
+ "dh_group": 15, # "modp-3072"
+ },
+ "esp_transforms": {
+ "crypto_alg": 12, # "aes-cbc"
+ "crypto_key_size": 256,
+ # "hmac-sha2-256-128"
+ "integ_alg": 12,
+ },
+ "no_idr_in_auth": True,
+ }
+ )
@tag_fixme_vpp_workers
class TestResponderInitBehindNATT(TemplateResponder, Ikev2Params):
- """ test ikev2 responder - initiator behind NAT """
+ """test ikev2 responder - initiator behind NAT"""
- IKE_NODE_SUFFIX = 'ip4-natt'
+ IKE_NODE_SUFFIX = "ip4-natt"
def config_tc(self):
- self.config_params(
- {'i_natt': True})
+ self.config_params({"i_natt": True})
@tag_fixme_vpp_workers
class TestResponderPsk(TemplateResponder, Ikev2Params):
- """ test ikev2 responder - pre shared key auth """
+ """test ikev2 responder - pre shared key auth"""
+
def config_tc(self):
self.config_params()
@@ -1863,8 +2041,9 @@ class TestResponderDpd(TestResponderPsk):
"""
Dead peer detection test
"""
+
def config_tc(self):
- self.config_params({'dpd_disabled': False})
+ self.config_params({"dpd_disabled": False})
def tearDown(self):
pass
@@ -1879,7 +2058,7 @@ class TestResponderDpd(TestResponderPsk):
ih = self.get_ike_header(capture[0])
self.assertEqual(ih.exch_type, 37) # INFORMATIONAL
plain = self.sa.hmac_and_decrypt(ih)
- self.assertEqual(plain, b'')
+ self.assertEqual(plain, b"")
# wait for SA expiration
time.sleep(3)
ike_sas = self.vapi.ikev2_sa_dump()
@@ -1890,7 +2069,7 @@ class TestResponderDpd(TestResponderPsk):
@tag_fixme_vpp_workers
class TestResponderRekey(TestResponderPsk):
- """ test ikev2 responder - rekey """
+ """test ikev2 responder - rekey"""
def rekey_from_initiator(self):
packet = self.create_rekey_request()
@@ -1912,18 +2091,19 @@ class TestResponderRekey(TestResponderPsk):
self.sa.calc_child_keys()
self.verify_ike_sas()
self.verify_ipsec_sas(is_rekey=True)
- self.assert_counter(1, 'rekey_req', 'ip4')
+ self.assert_counter(1, "rekey_req", "ip4")
r = self.vapi.ikev2_sa_dump()
self.assertEqual(r[0].sa.stats.n_rekey_req, 1)
class TestResponderVrf(TestResponderPsk, Ikev2Params):
- """ test ikev2 responder - non-default table id """
+ """test ikev2 responder - non-default table id"""
@classmethod
def setUpClass(cls):
import scapy.contrib.ikev2 as _ikev2
- globals()['ikev2'] = _ikev2
+
+ globals()["ikev2"] = _ikev2
super(IkePeer, cls).setUpClass()
cls.create_pg_interfaces(range(1))
cls.vapi.cli("ip table add 1")
@@ -1936,7 +2116,7 @@ class TestResponderVrf(TestResponderPsk, Ikev2Params):
i.resolve_ndp()
def config_tc(self):
- self.config_params({'dpd_disabled': False})
+ self.config_params({"dpd_disabled": False})
def test_responder(self):
self.vapi.ikev2_profile_set_liveness(period=2, max_retries=1)
@@ -1947,53 +2127,67 @@ class TestResponderVrf(TestResponderPsk, Ikev2Params):
ih = self.get_ike_header(capture[0])
self.assertEqual(ih.exch_type, 37) # INFORMATIONAL
plain = self.sa.hmac_and_decrypt(ih)
- self.assertEqual(plain, b'')
+ self.assertEqual(plain, b"")
@tag_fixme_vpp_workers
class TestResponderRsaSign(TemplateResponder, Ikev2Params):
- """ test ikev2 responder - cert based auth """
+ """test ikev2 responder - cert based auth"""
+
def config_tc(self):
- self.config_params({
- 'udp_encap': True,
- 'auth': 'rsa-sig',
- 'server-key': 'server-key.pem',
- 'client-key': 'client-key.pem',
- 'client-cert': 'client-cert.pem',
- 'server-cert': 'server-cert.pem'})
+ self.config_params(
+ {
+ "udp_encap": True,
+ "auth": "rsa-sig",
+ "server-key": "server-key.pem",
+ "client-key": "client-key.pem",
+ "client-cert": "client-cert.pem",
+ "server-cert": "server-cert.pem",
+ }
+ )
@tag_fixme_vpp_workers
-class Test_IKE_AES_CBC_128_SHA256_128_MODP2048_ESP_AES_CBC_192_SHA_384_192\
- (TemplateResponder, Ikev2Params):
+class Test_IKE_AES_CBC_128_SHA256_128_MODP2048_ESP_AES_CBC_192_SHA_384_192(
+ TemplateResponder, Ikev2Params
+):
"""
IKE:AES_CBC_128_SHA256_128,DH=modp2048 ESP:AES_CBC_192_SHA_384_192
"""
+
def config_tc(self):
- self.config_params({
- 'ike-crypto': ('AES-CBC', 16),
- 'ike-integ': 'SHA2-256-128',
- 'esp-crypto': ('AES-CBC', 24),
- 'esp-integ': 'SHA2-384-192',
- 'ike-dh': '2048MODPgr',
- 'nonce': os.urandom(256),
- 'no_idr_in_auth': True})
+ self.config_params(
+ {
+ "ike-crypto": ("AES-CBC", 16),
+ "ike-integ": "SHA2-256-128",
+ "esp-crypto": ("AES-CBC", 24),
+ "esp-integ": "SHA2-384-192",
+ "ike-dh": "2048MODPgr",
+ "nonce": os.urandom(256),
+ "no_idr_in_auth": True,
+ }
+ )
@tag_fixme_vpp_workers
-class TestAES_CBC_128_SHA256_128_MODP3072_ESP_AES_GCM_16\
- (TemplateResponder, Ikev2Params):
+class TestAES_CBC_128_SHA256_128_MODP3072_ESP_AES_GCM_16(
+ TemplateResponder, Ikev2Params
+):
"""
IKE:AES_CBC_128_SHA256_128,DH=modp3072 ESP:AES_GCM_16
"""
+
def config_tc(self):
- self.config_params({
- 'ike-crypto': ('AES-CBC', 32),
- 'ike-integ': 'SHA2-256-128',
- 'esp-crypto': ('AES-GCM-16ICV', 32),
- 'esp-integ': 'NULL',
- 'ike-dh': '3072MODPgr'})
+ self.config_params(
+ {
+ "ike-crypto": ("AES-CBC", 32),
+ "ike-integ": "SHA2-256-128",
+ "esp-crypto": ("AES-GCM-16ICV", 32),
+ "esp-integ": "NULL",
+ "ike-dh": "3072MODPgr",
+ }
+ )
@tag_fixme_vpp_workers
@@ -2002,20 +2196,21 @@ class Test_IKE_AES_GCM_16_256(TemplateResponder, Ikev2Params):
IKE:AES_GCM_16_256
"""
- IKE_NODE_SUFFIX = 'ip6'
+ IKE_NODE_SUFFIX = "ip6"
def config_tc(self):
- self.config_params({
- 'del_sa_from_responder': True,
- 'ip6': True,
- 'natt': True,
- 'ike-crypto': ('AES-GCM-16ICV', 32),
- 'ike-integ': 'NULL',
- 'ike-dh': '2048MODPgr',
- 'loc_ts': {'start_addr': 'ab:cd::0',
- 'end_addr': 'ab:cd::10'},
- 'rem_ts': {'start_addr': '11::0',
- 'end_addr': '11::100'}})
+ self.config_params(
+ {
+ "del_sa_from_responder": True,
+ "ip6": True,
+ "natt": True,
+ "ike-crypto": ("AES-GCM-16ICV", 32),
+ "ike-integ": "NULL",
+ "ike-dh": "2048MODPgr",
+ "loc_ts": {"start_addr": "ab:cd::0", "end_addr": "ab:cd::10"},
+ "rem_ts": {"start_addr": "11::0", "end_addr": "11::100"},
+ }
+ )
@tag_fixme_vpp_workers
@@ -2033,8 +2228,8 @@ class TestInitiatorKeepaliveMsg(TestInitiatorPsk):
ih = self.get_ike_header(capture[0])
self.assertEqual(ih.id, self.sa.msg_id)
plain = self.sa.hmac_and_decrypt(ih)
- self.assertEqual(plain, b'')
- self.assert_counter(1, 'keepalive', 'ip4')
+ self.assertEqual(plain, b"")
+ self.assert_counter(1, "keepalive", "ip4")
r = self.vapi.ikev2_sa_dump()
self.assertEqual(1, r[0].sa.stats.n_keepalives)
@@ -2044,7 +2239,7 @@ class TestInitiatorKeepaliveMsg(TestInitiatorPsk):
class TestMalformedMessages(TemplateResponder, Ikev2Params):
- """ malformed packet test """
+ """malformed packet test"""
def tearDown(self):
pass
@@ -2053,23 +2248,26 @@ class TestMalformedMessages(TemplateResponder, Ikev2Params):
self.config_params()
def create_ike_init_msg(self, length=None, payload=None):
- msg = ikev2.IKEv2(length=length, init_SPI='\x11' * 8,
- flags='Initiator', exch_type='IKE_SA_INIT')
+ msg = ikev2.IKEv2(
+ length=length,
+ init_SPI="\x11" * 8,
+ flags="Initiator",
+ exch_type="IKE_SA_INIT",
+ )
if payload is not None:
msg /= payload
- return self.create_packet(self.pg0, msg, self.sa.sport,
- self.sa.dport)
+ return self.create_packet(self.pg0, msg, self.sa.sport, self.sa.dport)
def verify_bad_packet_length(self):
- ike_msg = self.create_ike_init_msg(length=0xdead)
+ ike_msg = self.create_ike_init_msg(length=0xDEAD)
self.send_and_assert_no_replies(self.pg0, ike_msg * self.pkt_count)
- self.assert_counter(self.pkt_count, 'bad_length')
+ self.assert_counter(self.pkt_count, "bad_length")
def verify_bad_sa_payload_length(self):
- p = ikev2.IKEv2_payload_SA(length=0xdead)
+ p = ikev2.IKEv2_payload_SA(length=0xDEAD)
ike_msg = self.create_ike_init_msg(payload=p)
self.send_and_assert_no_replies(self.pg0, ike_msg * self.pkt_count)
- self.assert_counter(self.pkt_count, 'malformed_packet')
+ self.assert_counter(self.pkt_count, "malformed_packet")
def test_responder(self):
self.pkt_count = 254
@@ -2077,5 +2275,5 @@ class TestMalformedMessages(TemplateResponder, Ikev2Params):
self.verify_bad_sa_payload_length()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_interface_crud.py b/test/test_interface_crud.py
index 2f08f33c704..c79999b5bc5 100644
--- a/test/test_interface_crud.py
+++ b/test/test_interface_crud.py
@@ -20,9 +20,7 @@ from framework import VppTestCase, VppTestRunner
class TestLoopbackInterfaceCRUD(VppTestCase):
- """CRUD Loopback
-
- """
+ """CRUD Loopback"""
@classmethod
def setUpClass(cls):
@@ -51,9 +49,11 @@ class TestLoopbackInterfaceCRUD(VppTestCase):
"""
pkts = []
for i in dst_ifs:
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=src_if.remote_ip4, dst=i.local_ip4) /
- ICMP(id=i.sw_if_index, type='echo-request'))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=src_if.remote_ip4, dst=i.local_ip4)
+ / ICMP(id=i.sw_if_index, type="echo-request")
+ )
pkts.append(p)
return pkts
@@ -88,15 +88,17 @@ class TestLoopbackInterfaceCRUD(VppTestCase):
i.config_ip4().admin_up()
# read (check sw if dump, ip4 fib, ip6 fib)
- if_dump = self.vapi.sw_interface_dump(name_filter_valid=True,
- name_filter='loop')
+ if_dump = self.vapi.sw_interface_dump(
+ name_filter_valid=True, name_filter="loop"
+ )
fib4_dump = self.vapi.ip_route_dump(0)
for i in loopbacks:
self.assertTrue(i.is_interface_config_in_dump(if_dump))
self.assertTrue(i.is_ip4_entry_in_fib_dump(fib4_dump))
- if_dump = self.vapi.sw_interface_dump(name_filter_valid=True,
- name_filter='loopXYZ')
+ if_dump = self.vapi.sw_interface_dump(
+ name_filter_valid=True, name_filter="loopXYZ"
+ )
self.assertEqual(len(if_dump), 0)
# check ping
@@ -160,31 +162,29 @@ class TestInterfaceDumpApiLocalOnly(VppTestCase):
self.assertEqual(rv[0].sw_if_index, 0)
def test_sw_if_index_twiddle0(self):
- rv = self.vapi.sw_interface_dump(sw_if_index=0xffffffff)
+ rv = self.vapi.sw_interface_dump(sw_if_index=0xFFFFFFFF)
self.assertEqual(rv[0].sw_if_index, 0)
def test_sw_if_index_1_not_existing(self):
rv = self.vapi.sw_interface_dump(sw_if_index=1)
- self.assertEqual(len(rv), 0, 'expected no records.')
+ self.assertEqual(len(rv), 0, "expected no records.")
class TestInterfaceDumpApi(VppTestCase):
"""test_interface_crud.TestInterfaceDumpApi"""
def test_sw_if_index_1(self):
- self.vapi.create_loopback_instance(is_specified=1,
- user_instance=10)
- self.vapi.create_loopback_instance(is_specified=1,
- user_instance=5)
+ self.vapi.create_loopback_instance(is_specified=1, user_instance=10)
+ self.vapi.create_loopback_instance(is_specified=1, user_instance=5)
# Can I get back the specified record?
rv = self.vapi.sw_interface_dump(sw_if_index=1)
self.assertEqual(rv[0].sw_if_index, 1, rv)
# verify 3 interfaces
- rv = self.vapi.sw_interface_dump(sw_if_index=0xffffffff)
- self.assertEqual(len(rv), 3, 'Expected 3 interfaces.')
+ rv = self.vapi.sw_interface_dump(sw_if_index=0xFFFFFFFF)
+ self.assertEqual(len(rv), 3, "Expected 3 interfaces.")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ip4.py b/test/test_ip4.py
index 3a48274691a..9079e54366a 100644
--- a/test/test_ip4.py
+++ b/test/test_ip4.py
@@ -15,10 +15,20 @@ from six import moves
from framework import tag_fixme_vpp_workers
from framework import VppTestCase, VppTestRunner
from util import ppp
-from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpMRoute, \
- VppMRoutePath, VppMplsIpBind, \
- VppMplsTable, VppIpTable, FibPathType, find_route, \
- VppIpInterfaceAddress, find_route_in_dump, find_mroute_in_dump
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ VppIpMRoute,
+ VppMRoutePath,
+ VppMplsIpBind,
+ VppMplsTable,
+ VppIpTable,
+ FibPathType,
+ find_route,
+ VppIpInterfaceAddress,
+ find_route_in_dump,
+ find_mroute_in_dump,
+)
from vpp_ip import VppIpPuntPolicer, VppIpPuntRedirect, VppIpPathMtu
from vpp_sub_interface import VppSubInterface, VppDot1QSubint, VppDot1ADSubint
from vpp_papi import vpp_papi, VppEnum
@@ -30,7 +40,7 @@ NUM_PKTS = 67
class TestIPv4(VppTestCase):
- """ IPv4 Test Case """
+ """IPv4 Test Case"""
@classmethod
def setUpClass(cls):
@@ -66,7 +76,8 @@ class TestIPv4(VppTestCase):
# create 2 subinterfaces for pg1 and pg2
self.sub_interfaces = [
VppDot1QSubint(self, self.pg1, 100),
- VppDot1ADSubint(self, self.pg2, 200, 300, 400)]
+ VppDot1ADSubint(self, self.pg2, 200, 300, 400),
+ ]
# packet flows mapping pg0 -> pg1.sub, pg2.sub, etc.
self.flows = dict()
@@ -108,7 +119,7 @@ class TestIPv4(VppTestCase):
dst_if = self.flows[src_if][dst_if_idx]
info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(info)
- p = pkt/Raw(payload)
+ p = pkt / Raw(payload)
p[IP].dst = dst_if.remote_ip4
info.data = p.copy()
if isinstance(src_if, VppSubInterface):
@@ -123,17 +134,26 @@ class TestIPv4(VppTestCase):
:param VppInterface src_if: Interface to create packet stream for.
"""
hdr_ext = 4 if isinstance(src_if, VppSubInterface) else 0
- pkt_tmpl = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=src_if.remote_ip4) /
- UDP(sport=1234, dport=1234))
-
- pkts = [self.modify_packet(src_if, i, pkt_tmpl)
- for i in moves.range(self.pg_if_packet_sizes[0],
- self.pg_if_packet_sizes[1], 10)]
- pkts_b = [self.modify_packet(src_if, i, pkt_tmpl)
- for i in moves.range(self.pg_if_packet_sizes[1] + hdr_ext,
- self.pg_if_packet_sizes[2] + hdr_ext,
- 50)]
+ pkt_tmpl = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=src_if.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ )
+
+ pkts = [
+ self.modify_packet(src_if, i, pkt_tmpl)
+ for i in moves.range(
+ self.pg_if_packet_sizes[0], self.pg_if_packet_sizes[1], 10
+ )
+ ]
+ pkts_b = [
+ self.modify_packet(src_if, i, pkt_tmpl)
+ for i in moves.range(
+ self.pg_if_packet_sizes[1] + hdr_ext,
+ self.pg_if_packet_sizes[2] + hdr_ext,
+ 50,
+ )
+ ]
pkts.extend(pkts_b)
return pkts
@@ -151,7 +171,7 @@ class TestIPv4(VppTestCase):
last_info[i.sw_if_index] = None
is_sub_if = False
dst_sw_if_index = dst_if.sw_if_index
- if hasattr(dst_if, 'parent'):
+ if hasattr(dst_if, "parent"):
is_sub_if = True
for packet in capture:
if is_sub_if:
@@ -165,11 +185,12 @@ class TestIPv4(VppTestCase):
packet_index = payload_info.index
self.assertEqual(payload_info.dst, dst_sw_if_index)
self.logger.debug(
- "Got packet on port %s: src=%u (id=%u)" %
- (dst_if.name, payload_info.src, packet_index))
+ "Got packet on port %s: src=%u (id=%u)"
+ % (dst_if.name, payload_info.src, packet_index)
+ )
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
self.assertEqual(packet_index, next_info.index)
@@ -184,13 +205,16 @@ class TestIPv4(VppTestCase):
raise
for i in self.interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index])
- self.assertTrue(remaining_packet is None,
- "Interface %s: Packet expected from interface %s "
- "didn't arrive" % (dst_if.name, i.name))
+ i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]
+ )
+ self.assertTrue(
+ remaining_packet is None,
+ "Interface %s: Packet expected from interface %s "
+ "didn't arrive" % (dst_if.name, i.name),
+ )
def test_fib(self):
- """ IPv4 FIB test
+ """IPv4 FIB test
Test scenario:
@@ -218,16 +242,19 @@ class TestIPv4(VppTestCase):
class TestIPv4RouteLookup(VppTestCase):
- """ IPv4 Route Lookup Test Case """
+ """IPv4 Route Lookup Test Case"""
+
routes = []
def route_lookup(self, prefix, exact):
- return self.vapi.api(self.vapi.papi.ip_route_lookup,
- {
- 'table_id': 0,
- 'exact': exact,
- 'prefix': prefix,
- })
+ return self.vapi.api(
+ self.vapi.papi.ip_route_lookup,
+ {
+ "table_id": 0,
+ "exact": exact,
+ "prefix": prefix,
+ },
+ )
@classmethod
def setUpClass(cls):
@@ -240,8 +267,9 @@ class TestIPv4RouteLookup(VppTestCase):
def setUp(self):
super(TestIPv4RouteLookup, self).setUp()
- drop_nh = VppRoutePath("127.0.0.1", 0xffffffff,
- type=FibPathType.FIB_PATH_TYPE_DROP)
+ drop_nh = VppRoutePath(
+ "127.0.0.1", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_DROP
+ )
# Add 3 routes
r = VppIpRoute(self, "1.1.0.0", 16, [drop_nh])
@@ -267,12 +295,12 @@ class TestIPv4RouteLookup(VppTestCase):
# Verify we find the host route
prefix = "1.1.1.1/32"
result = self.route_lookup(prefix, True)
- assert (prefix == str(result.route.prefix))
+ assert prefix == str(result.route.prefix)
# Verify we find a middle prefix route
prefix = "1.1.1.0/24"
result = self.route_lookup(prefix, True)
- assert (prefix == str(result.route.prefix))
+ assert prefix == str(result.route.prefix)
# Verify we do not find an available LPM.
with self.vapi.assert_negative_api_retval():
@@ -282,17 +310,17 @@ class TestIPv4RouteLookup(VppTestCase):
# verify we find lpm
lpm_prefix = "1.1.1.0/24"
result = self.route_lookup("1.1.1.2/32", False)
- assert (lpm_prefix == str(result.route.prefix))
+ assert lpm_prefix == str(result.route.prefix)
# Verify we find the exact when not requested
result = self.route_lookup(lpm_prefix, False)
- assert (lpm_prefix == str(result.route.prefix))
+ assert lpm_prefix == str(result.route.prefix)
# Can't seem to delete the default route so no negative LPM test.
class TestIPv4IfAddrRoute(VppTestCase):
- """ IPv4 Interface Addr Route Test Case """
+ """IPv4 Interface Addr Route Test Case"""
@classmethod
def setUpClass(cls):
@@ -320,7 +348,7 @@ class TestIPv4IfAddrRoute(VppTestCase):
i.admin_down()
def test_ipv4_ifaddrs_same_prefix(self):
- """ IPv4 Interface Addresses Same Prefix test
+ """IPv4 Interface Addresses Same Prefix test
Test scenario:
@@ -370,7 +398,7 @@ class TestIPv4IfAddrRoute(VppTestCase):
self.assertFalse(find_route(self, "10.10.10.0", 32))
def test_ipv4_ifaddr_route(self):
- """ IPv4 Interface Address Route test
+ """IPv4 Interface Address Route test
Test scenario:
@@ -415,7 +443,7 @@ class TestIPv4IfAddrRoute(VppTestCase):
self.assertTrue(lo_if.is_ip4_entry_in_fib_dump(fib4_dump))
def test_ipv4_ifaddr_del(self):
- """ Delete an interface address that does not exist """
+ """Delete an interface address that does not exist"""
loopbacks = self.create_loopback_interfaces(1)
lo = self.lo_interfaces[0]
@@ -428,13 +456,12 @@ class TestIPv4IfAddrRoute(VppTestCase):
#
with self.vapi.assert_negative_api_retval():
self.vapi.sw_interface_add_del_address(
- sw_if_index=lo.sw_if_index,
- prefix=self.pg0.local_ip4_prefix,
- is_add=0)
+ sw_if_index=lo.sw_if_index, prefix=self.pg0.local_ip4_prefix, is_add=0
+ )
class TestICMPEcho(VppTestCase):
- """ ICMP Echo Test Case """
+ """ICMP Echo Test Case"""
@classmethod
def setUpClass(cls):
@@ -462,7 +489,7 @@ class TestICMPEcho(VppTestCase):
i.admin_down()
def test_icmp_echo(self):
- """ VPP replies to ICMP Echo Request
+ """VPP replies to ICMP Echo Request
Test scenario:
@@ -470,14 +497,15 @@ class TestICMPEcho(VppTestCase):
- Check outgoing ICMP Echo Reply message on pg0 interface.
"""
- icmp_id = 0xb
+ icmp_id = 0xB
icmp_seq = 5
- icmp_load = b'\x0a' * 18
- p_echo_request = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- ICMP(id=icmp_id, seq=icmp_seq) /
- Raw(load=icmp_load))
+ icmp_load = b"\x0a" * 18
+ p_echo_request = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / ICMP(id=icmp_id, seq=icmp_seq)
+ / Raw(load=icmp_load)
+ )
self.pg0.add_stream(p_echo_request)
self.pg_enable_capture(self.pg_interfaces)
@@ -502,7 +530,7 @@ class TestICMPEcho(VppTestCase):
class TestIPv4FibCrud(VppTestCase):
- """ FIB - add/update/delete - ip4 routes
+ """FIB - add/update/delete - ip4 routes
Test scenario:
- add 1k,
@@ -513,8 +541,7 @@ class TestIPv4FibCrud(VppTestCase):
..note:: Python API is too slow to add many routes, needs replacement.
"""
- def config_fib_many_to_one(self, start_dest_addr, next_hop_addr,
- count, start=0):
+ def config_fib_many_to_one(self, start_dest_addr, next_hop_addr, count, start=0):
"""
:param start_dest_addr:
@@ -524,19 +551,26 @@ class TestIPv4FibCrud(VppTestCase):
"""
routes = []
for i in range(count):
- r = VppIpRoute(self, start_dest_addr % (i + start), 32,
- [VppRoutePath(next_hop_addr, 0xffffffff)])
+ r = VppIpRoute(
+ self,
+ start_dest_addr % (i + start),
+ 32,
+ [VppRoutePath(next_hop_addr, 0xFFFFFFFF)],
+ )
r.add_vpp_config()
routes.append(r)
return routes
- def unconfig_fib_many_to_one(self, start_dest_addr, next_hop_addr,
- count, start=0):
+ def unconfig_fib_many_to_one(self, start_dest_addr, next_hop_addr, count, start=0):
routes = []
for i in range(count):
- r = VppIpRoute(self, start_dest_addr % (i + start), 32,
- [VppRoutePath(next_hop_addr, 0xffffffff)])
+ r = VppIpRoute(
+ self,
+ start_dest_addr % (i + start),
+ 32,
+ [VppRoutePath(next_hop_addr, 0xFFFFFFFF)],
+ )
r.remove_vpp_config()
routes.append(r)
return routes
@@ -548,10 +582,12 @@ class TestIPv4FibCrud(VppTestCase):
dst_addr = random.choice(routes).prefix.network_address
info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=src_if.remote_ip4, dst=str(dst_addr)) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=src_if.remote_ip4, dst=str(dst_addr))
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
self.extend_packet(p, random.choice(self.pg_if_packet_sizes))
pkts.append(p)
@@ -560,8 +596,7 @@ class TestIPv4FibCrud(VppTestCase):
def _find_ip_match(self, find_in, pkt):
for p in find_in:
- if self.payload_to_info(p[Raw]) == \
- self.payload_to_info(pkt[Raw]):
+ if self.payload_to_info(p[Raw]) == self.payload_to_info(pkt[Raw]):
if p[IP].src != pkt[IP].src:
break
if p[IP].dst != pkt[IP].dst:
@@ -585,15 +620,15 @@ class TestIPv4FibCrud(VppTestCase):
def verify_route_dump(self, routes):
for r in routes:
- self.assertTrue(find_route(self,
- r.prefix.network_address,
- r.prefix.prefixlen))
+ self.assertTrue(
+ find_route(self, r.prefix.network_address, r.prefix.prefixlen)
+ )
def verify_not_in_route_dump(self, routes):
for r in routes:
- self.assertFalse(find_route(self,
- r.prefix.network_address,
- r.prefix.prefixlen))
+ self.assertFalse(
+ find_route(self, r.prefix.network_address, r.prefix.prefixlen)
+ )
@classmethod
def setUpClass(cls):
@@ -636,18 +671,21 @@ class TestIPv4FibCrud(VppTestCase):
self.deleted_routes = []
def test_1_add_routes(self):
- """ Add 1k routes """
+ """Add 1k routes"""
# add 100 routes check with traffic script.
- self.configured_routes.extend(self.config_fib_many_to_one(
- "10.0.0.%d", self.pg0.remote_ip4, 100))
+ self.configured_routes.extend(
+ self.config_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 100)
+ )
self.verify_route_dump(self.configured_routes)
self.stream_1 = self.create_stream(
- self.pg1, self.pg0, self.configured_routes, 100)
+ self.pg1, self.pg0, self.configured_routes, 100
+ )
self.stream_2 = self.create_stream(
- self.pg2, self.pg0, self.configured_routes, 100)
+ self.pg2, self.pg0, self.configured_routes, 100
+ )
self.pg1.add_stream(self.stream_1)
self.pg2.add_stream(self.stream_2)
@@ -658,28 +696,32 @@ class TestIPv4FibCrud(VppTestCase):
self.verify_capture(self.pg0, pkts, self.stream_1 + self.stream_2)
def test_2_del_routes(self):
- """ Delete 100 routes
+ """Delete 100 routes
- delete 10 routes check with traffic script.
"""
# config 1M FIB entries
- self.configured_routes.extend(self.config_fib_many_to_one(
- "10.0.0.%d", self.pg0.remote_ip4, 100))
- self.deleted_routes.extend(self.unconfig_fib_many_to_one(
- "10.0.0.%d", self.pg0.remote_ip4, 10, start=10))
+ self.configured_routes.extend(
+ self.config_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 100)
+ )
+ self.deleted_routes.extend(
+ self.unconfig_fib_many_to_one(
+ "10.0.0.%d", self.pg0.remote_ip4, 10, start=10
+ )
+ )
for x in self.deleted_routes:
self.configured_routes.remove(x)
self.verify_route_dump(self.configured_routes)
self.stream_1 = self.create_stream(
- self.pg1, self.pg0, self.configured_routes, 100)
+ self.pg1, self.pg0, self.configured_routes, 100
+ )
self.stream_2 = self.create_stream(
- self.pg2, self.pg0, self.configured_routes, 100)
- self.stream_3 = self.create_stream(
- self.pg1, self.pg0, self.deleted_routes, 100)
- self.stream_4 = self.create_stream(
- self.pg2, self.pg0, self.deleted_routes, 100)
+ self.pg2, self.pg0, self.configured_routes, 100
+ )
+ self.stream_3 = self.create_stream(self.pg1, self.pg0, self.deleted_routes, 100)
+ self.stream_4 = self.create_stream(self.pg2, self.pg0, self.deleted_routes, 100)
self.pg1.add_stream(self.stream_1 + self.stream_3)
self.pg2.add_stream(self.stream_2 + self.stream_4)
self.pg_enable_capture(self.pg_interfaces)
@@ -689,38 +731,42 @@ class TestIPv4FibCrud(VppTestCase):
self.verify_capture(self.pg0, pkts, self.stream_1 + self.stream_2)
def test_3_add_new_routes(self):
- """ Add 1k routes
+ """Add 1k routes
- re-add 5 routes check with traffic script.
- add 100 routes check with traffic script.
"""
# config 1M FIB entries
- self.configured_routes.extend(self.config_fib_many_to_one(
- "10.0.0.%d", self.pg0.remote_ip4, 100))
- self.deleted_routes.extend(self.unconfig_fib_many_to_one(
- "10.0.0.%d", self.pg0.remote_ip4, 10, start=10))
+ self.configured_routes.extend(
+ self.config_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 100)
+ )
+ self.deleted_routes.extend(
+ self.unconfig_fib_many_to_one(
+ "10.0.0.%d", self.pg0.remote_ip4, 10, start=10
+ )
+ )
for x in self.deleted_routes:
self.configured_routes.remove(x)
- tmp = self.config_fib_many_to_one(
- "10.0.0.%d", self.pg0.remote_ip4, 5, start=10)
+ tmp = self.config_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 5, start=10)
self.configured_routes.extend(tmp)
for x in tmp:
self.deleted_routes.remove(x)
- self.configured_routes.extend(self.config_fib_many_to_one(
- "10.0.1.%d", self.pg0.remote_ip4, 100))
+ self.configured_routes.extend(
+ self.config_fib_many_to_one("10.0.1.%d", self.pg0.remote_ip4, 100)
+ )
self.verify_route_dump(self.configured_routes)
self.stream_1 = self.create_stream(
- self.pg1, self.pg0, self.configured_routes, 300)
+ self.pg1, self.pg0, self.configured_routes, 300
+ )
self.stream_2 = self.create_stream(
- self.pg2, self.pg0, self.configured_routes, 300)
- self.stream_3 = self.create_stream(
- self.pg1, self.pg0, self.deleted_routes, 100)
- self.stream_4 = self.create_stream(
- self.pg2, self.pg0, self.deleted_routes, 100)
+ self.pg2, self.pg0, self.configured_routes, 300
+ )
+ self.stream_3 = self.create_stream(self.pg1, self.pg0, self.deleted_routes, 100)
+ self.stream_4 = self.create_stream(self.pg2, self.pg0, self.deleted_routes, 100)
self.pg1.add_stream(self.stream_1 + self.stream_3)
self.pg2.add_stream(self.stream_2 + self.stream_4)
@@ -732,17 +778,20 @@ class TestIPv4FibCrud(VppTestCase):
# delete 5 routes check with traffic script.
# add 100 routes check with traffic script.
- self.deleted_routes.extend(self.unconfig_fib_many_to_one(
- "10.0.0.%d", self.pg0.remote_ip4, 15))
- self.deleted_routes.extend(self.unconfig_fib_many_to_one(
- "10.0.0.%d", self.pg0.remote_ip4, 85))
- self.deleted_routes.extend(self.unconfig_fib_many_to_one(
- "10.0.1.%d", self.pg0.remote_ip4, 100))
+ self.deleted_routes.extend(
+ self.unconfig_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 15)
+ )
+ self.deleted_routes.extend(
+ self.unconfig_fib_many_to_one("10.0.0.%d", self.pg0.remote_ip4, 85)
+ )
+ self.deleted_routes.extend(
+ self.unconfig_fib_many_to_one("10.0.1.%d", self.pg0.remote_ip4, 100)
+ )
self.verify_not_in_route_dump(self.deleted_routes)
class TestIPNull(VppTestCase):
- """ IPv4 routes via NULL """
+ """IPv4 routes via NULL"""
@classmethod
def setUpClass(cls):
@@ -770,23 +819,29 @@ class TestIPNull(VppTestCase):
i.admin_down()
def test_ip_null(self):
- """ IP NULL route """
+ """IP NULL route"""
#
# A route via IP NULL that will reply with ICMP unreachables
#
ip_unreach = VppIpRoute(
- self, "10.0.0.1", 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- type=FibPathType.FIB_PATH_TYPE_ICMP_UNREACH)])
+ self,
+ "10.0.0.1",
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_ICMP_UNREACH
+ )
+ ],
+ )
ip_unreach.add_vpp_config()
- p_unreach = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.0.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_unreach = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.0.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.pg0.add_stream(p_unreach)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -809,17 +864,23 @@ class TestIPNull(VppTestCase):
# A route via IP NULL that will reply with ICMP prohibited
#
ip_prohibit = VppIpRoute(
- self, "10.0.0.2", 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- type=FibPathType.FIB_PATH_TYPE_ICMP_PROHIBIT)])
+ self,
+ "10.0.0.2",
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_ICMP_PROHIBIT
+ )
+ ],
+ )
ip_prohibit.add_vpp_config()
- p_prohibit = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.0.0.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_prohibit = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.0.0.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.pg0.add_stream(p_prohibit)
self.pg_enable_capture(self.pg_interfaces)
@@ -836,17 +897,21 @@ class TestIPNull(VppTestCase):
self.assertEqual(icmp.dst, "10.0.0.2")
def test_ip_drop(self):
- """ IP Drop Routes """
+ """IP Drop Routes"""
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst="1.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst="1.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- r1 = VppIpRoute(self, "1.1.1.0", 24,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ r1 = VppIpRoute(
+ self,
+ "1.1.1.0",
+ 24,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
r1.add_vpp_config()
rx = self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1)
@@ -854,10 +919,12 @@ class TestIPNull(VppTestCase):
#
# insert a more specific as a drop
#
- r2 = VppIpRoute(self, "1.1.1.1", 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- type=FibPathType.FIB_PATH_TYPE_DROP)])
+ r2 = VppIpRoute(
+ self,
+ "1.1.1.1",
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_DROP)],
+ )
r2.add_vpp_config()
self.send_and_assert_no_replies(self.pg0, p * NUM_PKTS, "Drop Route")
@@ -866,7 +933,7 @@ class TestIPNull(VppTestCase):
class TestIPDisabled(VppTestCase):
- """ IPv4 disabled """
+ """IPv4 disabled"""
@classmethod
def setUpClass(cls):
@@ -897,7 +964,7 @@ class TestIPDisabled(VppTestCase):
i.admin_down()
def test_ip_disabled(self):
- """ IP Disabled """
+ """IP Disabled"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -909,24 +976,32 @@ class TestIPDisabled(VppTestCase):
route_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_232_1_1_1.add_vpp_config()
- pu = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IP(src="10.10.10.10", dst=self.pg0.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- pm = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IP(src="10.10.10.10", dst="232.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pu = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src="10.10.10.10", dst=self.pg0.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ pm = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src="10.10.10.10", dst="232.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# PG1 does not forward IP traffic
@@ -965,7 +1040,7 @@ class TestIPDisabled(VppTestCase):
class TestIPSubNets(VppTestCase):
- """ IPv4 Subnets """
+ """IPv4 Subnets"""
@classmethod
def setUpClass(cls):
@@ -995,22 +1070,26 @@ class TestIPSubNets(VppTestCase):
i.admin_down()
def test_ip_sub_nets(self):
- """ IP Sub Nets """
+ """IP Sub Nets"""
#
# Configure a covering route to forward so we know
# when we are dropping
#
- cover_route = VppIpRoute(self, "10.0.0.0", 8,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ cover_route = VppIpRoute(
+ self,
+ "10.0.0.0",
+ 8,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
cover_route.add_vpp_config()
- p = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IP(dst="10.10.10.10", src=self.pg0.local_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(dst="10.10.10.10", src=self.pg0.local_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
@@ -1023,28 +1102,29 @@ class TestIPSubNets(VppTestCase):
ip_addr_n = socket.inet_pton(socket.AF_INET, "10.10.10.10")
self.vapi.sw_interface_add_del_address(
- sw_if_index=self.pg0.sw_if_index,
- prefix="10.10.10.10/16")
-
- pn = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IP(dst="10.10.0.0", src=self.pg0.local_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- pb = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IP(dst="10.10.255.255", src=self.pg0.local_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ sw_if_index=self.pg0.sw_if_index, prefix="10.10.10.10/16"
+ )
+
+ pn = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(dst="10.10.0.0", src=self.pg0.local_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ pb = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(dst="10.10.255.255", src=self.pg0.local_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_assert_no_replies(self.pg1, pn, "IP Network address")
self.send_and_assert_no_replies(self.pg1, pb, "IP Broadcast address")
# remove the sub-net and we are forwarding via the cover again
self.vapi.sw_interface_add_del_address(
- sw_if_index=self.pg0.sw_if_index,
- prefix="10.10.10.10/16",
- is_add=0)
+ sw_if_index=self.pg0.sw_if_index, prefix="10.10.10.10/16", is_add=0
+ )
self.pg1.add_stream(pn)
self.pg_enable_capture(self.pg_interfaces)
@@ -1062,14 +1142,15 @@ class TestIPSubNets(VppTestCase):
ip_addr_n = socket.inet_pton(socket.AF_INET, "10.10.10.10")
self.vapi.sw_interface_add_del_address(
- sw_if_index=self.pg0.sw_if_index,
- prefix="10.10.10.10/31")
+ sw_if_index=self.pg0.sw_if_index, prefix="10.10.10.10/31"
+ )
- pn = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IP(dst="10.10.10.11", src=self.pg0.local_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pn = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(dst="10.10.10.11", src=self.pg0.local_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.pg1.add_stream(pn)
self.pg_enable_capture(self.pg_interfaces)
@@ -1079,8 +1160,8 @@ class TestIPSubNets(VppTestCase):
# remove the sub-net and we are forwarding via the cover again
self.vapi.sw_interface_add_del_address(
- sw_if_index=self.pg0.sw_if_index,
- prefix="10.10.10.10/31", is_add=0)
+ sw_if_index=self.pg0.sw_if_index, prefix="10.10.10.10/31", is_add=0
+ )
self.pg1.add_stream(pn)
self.pg_enable_capture(self.pg_interfaces)
@@ -1089,7 +1170,7 @@ class TestIPSubNets(VppTestCase):
class TestIPLoadBalance(VppTestCase):
- """ IPv4 Load-Balancing """
+ """IPv4 Load-Balancing"""
@classmethod
def setUpClass(cls):
@@ -1126,7 +1207,7 @@ class TestIPLoadBalance(VppTestCase):
return n
def test_ip_load_balance(self):
- """ IP Load-Balancing """
+ """IP Load-Balancing"""
fhc = VppEnum.vl_api_ip_flow_hash_config_t
af = VppEnum.vl_api_address_family_t
@@ -1144,33 +1225,47 @@ class TestIPLoadBalance(VppTestCase):
src_mpls_pkts = []
for ii in range(NUM_PKTS):
- port_ip_hdr = (IP(dst="10.0.0.1", src="20.0.0.1") /
- UDP(sport=1234, dport=1234 + ii) /
- Raw(b'\xa5' * 100))
- port_ip_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- port_ip_hdr))
- port_mpls_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- MPLS(label=66, ttl=2) /
- port_ip_hdr))
-
- src_ip_hdr = (IP(dst="10.0.0.1", src="20.0.0.%d" % ii) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- src_ip_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- src_ip_hdr))
- src_mpls_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- MPLS(label=66, ttl=2) /
- src_ip_hdr))
-
- route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index),
- VppRoutePath(self.pg2.remote_ip4,
- self.pg2.sw_if_index)])
+ port_ip_hdr = (
+ IP(dst="10.0.0.1", src="20.0.0.1")
+ / UDP(sport=1234, dport=1234 + ii)
+ / Raw(b"\xa5" * 100)
+ )
+ port_ip_pkts.append(
+ (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / port_ip_hdr)
+ )
+ port_mpls_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / MPLS(label=66, ttl=2)
+ / port_ip_hdr
+ )
+ )
+
+ src_ip_hdr = (
+ IP(dst="10.0.0.1", src="20.0.0.%d" % ii)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ src_ip_pkts.append(
+ (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / src_ip_hdr)
+ )
+ src_mpls_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / MPLS(label=66, ttl=2)
+ / src_ip_hdr
+ )
+ )
+
+ route_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ [
+ VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index),
+ VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index),
+ ],
+ )
route_10_0_0_1.add_vpp_config()
binding = VppMplsIpBind(self, 66, "10.0.0.1", 32)
@@ -1185,15 +1280,17 @@ class TestIPLoadBalance(VppTestCase):
# be guaranteed. But with 64 different packets we do expect some
# balancing. So instead just ensure there is traffic on each link.
#
- rx = self.send_and_expect_load_balancing(self.pg0, port_ip_pkts,
- [self.pg1, self.pg2])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, port_ip_pkts, [self.pg1, self.pg2]
+ )
n_ip_pg0 = len(rx[0])
- self.send_and_expect_load_balancing(self.pg0, src_ip_pkts,
- [self.pg1, self.pg2])
- self.send_and_expect_load_balancing(self.pg0, port_mpls_pkts,
- [self.pg1, self.pg2])
- rx = self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
- [self.pg1, self.pg2])
+ self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, [self.pg1, self.pg2])
+ self.send_and_expect_load_balancing(
+ self.pg0, port_mpls_pkts, [self.pg1, self.pg2]
+ )
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, src_mpls_pkts, [self.pg1, self.pg2]
+ )
n_mpls_pg0 = len(rx[0])
#
@@ -1201,12 +1298,14 @@ class TestIPLoadBalance(VppTestCase):
#
self.vapi.set_ip_flow_hash_router_id(router_id=0x11111111)
- rx = self.send_and_expect_load_balancing(self.pg0, port_ip_pkts,
- [self.pg1, self.pg2])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, port_ip_pkts, [self.pg1, self.pg2]
+ )
self.assertNotEqual(n_ip_pg0, len(rx[0]))
- rx = self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
- [self.pg1, self.pg2])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, src_mpls_pkts, [self.pg1, self.pg2]
+ )
self.assertNotEqual(n_mpls_pg0, len(rx[0]))
#
@@ -1217,22 +1316,24 @@ class TestIPLoadBalance(VppTestCase):
self.vapi.set_ip_flow_hash_v2(
af=af.ADDRESS_IP4,
table_id=0,
- flow_hash_config=(fhc.IP_API_FLOW_HASH_SRC_IP |
- fhc.IP_API_FLOW_HASH_DST_IP |
- fhc.IP_API_FLOW_HASH_PROTO))
-
- self.send_and_expect_load_balancing(self.pg0, src_ip_pkts,
- [self.pg1, self.pg2])
- self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
- [self.pg1, self.pg2])
+ flow_hash_config=(
+ fhc.IP_API_FLOW_HASH_SRC_IP
+ | fhc.IP_API_FLOW_HASH_DST_IP
+ | fhc.IP_API_FLOW_HASH_PROTO
+ ),
+ )
+
+ self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, [self.pg1, self.pg2])
+ self.send_and_expect_load_balancing(
+ self.pg0, src_mpls_pkts, [self.pg1, self.pg2]
+ )
self.send_and_expect_only(self.pg0, port_ip_pkts, self.pg2)
#
# change the flow hash config back to defaults
#
- self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1,
- proto=1, sport=1, dport=1)
+ self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, proto=1, sport=1, dport=1)
#
# Recursive prefixes
@@ -1243,48 +1344,64 @@ class TestIPLoadBalance(VppTestCase):
src_pkts = []
for ii in range(257):
- port_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(dst="1.1.1.1", src="20.0.0.1") /
- UDP(sport=1234, dport=1234 + ii) /
- Raw(b'\xa5' * 100)))
- src_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(dst="1.1.1.1", src="20.0.0.%d" % ii) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)))
-
- route_10_0_0_2 = VppIpRoute(self, "10.0.0.2", 32,
- [VppRoutePath(self.pg3.remote_ip4,
- self.pg3.sw_if_index),
- VppRoutePath(self.pg4.remote_ip4,
- self.pg4.sw_if_index)])
+ port_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(dst="1.1.1.1", src="20.0.0.1")
+ / UDP(sport=1234, dport=1234 + ii)
+ / Raw(b"\xa5" * 100)
+ )
+ )
+ src_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(dst="1.1.1.1", src="20.0.0.%d" % ii)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ )
+
+ route_10_0_0_2 = VppIpRoute(
+ self,
+ "10.0.0.2",
+ 32,
+ [
+ VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index),
+ VppRoutePath(self.pg4.remote_ip4, self.pg4.sw_if_index),
+ ],
+ )
route_10_0_0_2.add_vpp_config()
- route_1_1_1_1 = VppIpRoute(self, "1.1.1.1", 32,
- [VppRoutePath("10.0.0.2", 0xffffffff),
- VppRoutePath("10.0.0.1", 0xffffffff)])
+ route_1_1_1_1 = VppIpRoute(
+ self,
+ "1.1.1.1",
+ 32,
+ [
+ VppRoutePath("10.0.0.2", 0xFFFFFFFF),
+ VppRoutePath("10.0.0.1", 0xFFFFFFFF),
+ ],
+ )
route_1_1_1_1.add_vpp_config()
#
# inject the packet on pg0 - expect load-balancing across all 4 paths
#
self.vapi.cli("clear trace")
- self.send_and_expect_load_balancing(self.pg0, port_pkts,
- [self.pg1, self.pg2,
- self.pg3, self.pg4])
- self.send_and_expect_load_balancing(self.pg0, src_pkts,
- [self.pg1, self.pg2,
- self.pg3, self.pg4])
+ self.send_and_expect_load_balancing(
+ self.pg0, port_pkts, [self.pg1, self.pg2, self.pg3, self.pg4]
+ )
+ self.send_and_expect_load_balancing(
+ self.pg0, src_pkts, [self.pg1, self.pg2, self.pg3, self.pg4]
+ )
#
# bring down pg1 expect LB to adjust to use only those that are up
#
self.pg1.link_down()
- rx = self.send_and_expect_load_balancing(self.pg0, src_pkts,
- [self.pg2, self.pg3,
- self.pg4])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, src_pkts, [self.pg2, self.pg3, self.pg4]
+ )
self.assertEqual(len(src_pkts), self.total_len(rx))
#
@@ -1292,8 +1409,9 @@ class TestIPLoadBalance(VppTestCase):
#
self.pg2.link_down()
- rx = self.send_and_expect_load_balancing(self.pg0, src_pkts,
- [self.pg3, self.pg4])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, src_pkts, [self.pg3, self.pg4]
+ )
self.assertEqual(len(src_pkts), self.total_len(rx))
#
@@ -1302,9 +1420,9 @@ class TestIPLoadBalance(VppTestCase):
self.pg1.link_up()
self.pg2.link_up()
- rx = self.send_and_expect_load_balancing(self.pg0, src_pkts,
- [self.pg1, self.pg2,
- self.pg3, self.pg4])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, src_pkts, [self.pg1, self.pg2, self.pg3, self.pg4]
+ )
self.assertEqual(len(src_pkts), self.total_len(rx))
#
@@ -1312,16 +1430,17 @@ class TestIPLoadBalance(VppTestCase):
#
self.pg1.admin_down()
self.pg2.admin_down()
- rx = self.send_and_expect_load_balancing(self.pg0, src_pkts,
- [self.pg3, self.pg4])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, src_pkts, [self.pg3, self.pg4]
+ )
self.assertEqual(len(src_pkts), self.total_len(rx))
self.pg1.admin_up()
self.pg2.admin_up()
self.pg1.resolve_arp()
self.pg2.resolve_arp()
- rx = self.send_and_expect_load_balancing(self.pg0, src_pkts,
- [self.pg1, self.pg2,
- self.pg3, self.pg4])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, src_pkts, [self.pg1, self.pg2, self.pg3, self.pg4]
+ )
self.assertEqual(len(src_pkts), self.total_len(rx))
#
@@ -1331,19 +1450,26 @@ class TestIPLoadBalance(VppTestCase):
port_pkts = []
for ii in range(257):
- port_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(dst="1.1.1.2", src="20.0.0.2") /
- UDP(sport=1234, dport=1234 + ii) /
- Raw(b'\xa5' * 100)))
-
- route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32,
- [VppRoutePath(self.pg3.remote_ip4,
- self.pg3.sw_if_index)])
+ port_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(dst="1.1.1.2", src="20.0.0.2")
+ / UDP(sport=1234, dport=1234 + ii)
+ / Raw(b"\xa5" * 100)
+ )
+ )
+
+ route_10_0_0_3 = VppIpRoute(
+ self,
+ "10.0.0.3",
+ 32,
+ [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)],
+ )
route_10_0_0_3.add_vpp_config()
- route_1_1_1_2 = VppIpRoute(self, "1.1.1.2", 32,
- [VppRoutePath("10.0.0.3", 0xffffffff)])
+ route_1_1_1_2 = VppIpRoute(
+ self, "1.1.1.2", 32, [VppRoutePath("10.0.0.3", 0xFFFFFFFF)]
+ )
route_1_1_1_2.add_vpp_config()
#
@@ -1358,33 +1484,39 @@ class TestIPLoadBalance(VppTestCase):
#
self.pg3.link_down()
- route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32,
- [VppRoutePath(self.pg3.remote_ip4,
- self.pg3.sw_if_index),
- VppRoutePath(self.pg4.remote_ip4,
- self.pg4.sw_if_index)])
+ route_10_0_0_3 = VppIpRoute(
+ self,
+ "10.0.0.3",
+ 32,
+ [
+ VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index),
+ VppRoutePath(self.pg4.remote_ip4, self.pg4.sw_if_index),
+ ],
+ )
route_10_0_0_3.add_vpp_config()
port_pkts = []
for ii in range(257):
- port_pkts.append(Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(dst="10.0.0.3", src="20.0.0.2") /
- UDP(sport=1234, dport=1234 + ii) /
- Raw(b'\xa5' * 100))
+ port_pkts.append(
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(dst="10.0.0.3", src="20.0.0.2")
+ / UDP(sport=1234, dport=1234 + ii)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect_only(self.pg0, port_pkts, self.pg4)
# bring the link back up
self.pg3.link_up()
- rx = self.send_and_expect_load_balancing(self.pg0, port_pkts,
- [self.pg3, self.pg4])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, port_pkts, [self.pg3, self.pg4]
+ )
self.assertEqual(len(src_pkts), self.total_len(rx))
class TestIPVlan0(VppTestCase):
- """ IPv4 VLAN-0 """
+ """IPv4 VLAN-0"""
@classmethod
def setUpClass(cls):
@@ -1415,15 +1547,15 @@ class TestIPVlan0(VppTestCase):
super(TestIPVlan0, self).tearDown()
def test_ip_vlan_0(self):
- """ IP VLAN-0 """
+ """IP VLAN-0"""
- pkts = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- Dot1Q(vlan=0) /
- IP(dst=self.pg1.remote_ip4,
- src=self.pg0.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)) * NUM_PKTS
+ pkts = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / Dot1Q(vlan=0)
+ / IP(dst=self.pg1.remote_ip4, src=self.pg0.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ) * NUM_PKTS
#
# Expect that packets sent on VLAN-0 are forwarded on the
@@ -1433,7 +1565,7 @@ class TestIPVlan0(VppTestCase):
class IPPuntSetup(object):
- """ Setup for IPv4 Punt Police/Redirect """
+ """Setup for IPv4 Punt Police/Redirect"""
def punt_setup(self):
self.create_pg_interfaces(range(4))
@@ -1449,37 +1581,38 @@ class IPPuntSetup(object):
af_ip4 = VppEnum.vl_api_address_family_t.ADDRESS_IP4
udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP
punt_udp = {
- 'type': pt_l4,
- 'punt': {
- 'l4': {
- 'af': af_ip4,
- 'protocol': udp_proto,
- 'port': 1234,
+ "type": pt_l4,
+ "punt": {
+ "l4": {
+ "af": af_ip4,
+ "protocol": udp_proto,
+ "port": 1234,
}
- }
+ },
}
self.vapi.set_punt(is_add=1, punt=punt_udp)
af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6
punt_udp = {
- 'type': pt_l4,
- 'punt': {
- 'l4': {
- 'af': af_ip6,
- 'protocol': udp_proto,
- 'port': 1236,
+ "type": pt_l4,
+ "punt": {
+ "l4": {
+ "af": af_ip6,
+ "protocol": udp_proto,
+ "port": 1236,
}
- }
+ },
}
self.vapi.set_punt(is_add=1, punt=punt_udp)
- self.pkt = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ self.pkt = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
def punt_teardown(self):
for i in self.pg_interfaces:
@@ -1488,7 +1621,7 @@ class IPPuntSetup(object):
class TestIPPunt(IPPuntSetup, VppTestCase):
- """ IPv4 Punt Police/Redirect """
+ """IPv4 Punt Police/Redirect"""
def setUp(self):
super().setUp()
@@ -1499,26 +1632,30 @@ class TestIPPunt(IPPuntSetup, VppTestCase):
super().tearDown()
def test_ip_punt_api_validation(self):
- """ IP punt API parameter validation """
+ """IP punt API parameter validation"""
nh_addr = self.pg1.remote_ip4
- punt = {"rx_sw_if_index": self.pg0.sw_if_index,
- "af": VppEnum.vl_api_address_family_t.ADDRESS_IP4,
- "n_paths": 1000000,
- "paths": []}
+ punt = {
+ "rx_sw_if_index": self.pg0.sw_if_index,
+ "af": VppEnum.vl_api_address_family_t.ADDRESS_IP4,
+ "n_paths": 1000000,
+ "paths": [],
+ }
with self.assertRaises(vpp_papi.VPPIOError):
self.vapi.add_del_ip_punt_redirect_v2(punt=punt, is_add=True)
- punt = {"rx_sw_if_index": self.pg0.sw_if_index,
- "af": VppEnum.vl_api_address_family_t.ADDRESS_IP4,
- "n_paths": 0,
- "paths": []}
+ punt = {
+ "rx_sw_if_index": self.pg0.sw_if_index,
+ "af": VppEnum.vl_api_address_family_t.ADDRESS_IP4,
+ "n_paths": 0,
+ "paths": [],
+ }
self.vapi.add_del_ip_punt_redirect_v2(punt=punt, is_add=True)
def test_ip_punt(self):
- """ IP punt police and redirect """
+ """IP punt police and redirect"""
pkts = self.pkt * 1025
@@ -1526,8 +1663,9 @@ class TestIPPunt(IPPuntSetup, VppTestCase):
# Configure a punt redirect via pg1.
#
nh_addr = self.pg1.remote_ip4
- ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index,
- self.pg1.sw_if_index, nh_addr)
+ ip_punt_redirect = VppIpPuntRedirect(
+ self, self.pg0.sw_if_index, self.pg1.sw_if_index, nh_addr
+ )
ip_punt_redirect.add_vpp_config()
self.send_and_expect(self.pg0, pkts, self.pg1)
@@ -1554,9 +1692,9 @@ class TestIPPunt(IPPuntSetup, VppTestCase):
stats = policer.get_stats()
# Single rate policer - expect conform, violate but no exceed
- self.assertGreater(stats['conform_packets'], 0)
- self.assertEqual(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ self.assertGreater(stats["conform_packets"], 0)
+ self.assertEqual(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
self.assertGreater(len(rx), 0)
self.assertLess(len(rx), len(pkts))
@@ -1572,32 +1710,28 @@ class TestIPPunt(IPPuntSetup, VppTestCase):
# remove the redirect. expect full drop.
#
ip_punt_redirect.remove_vpp_config()
- self.send_and_assert_no_replies(self.pg0, pkts,
- "IP no punt config")
+ self.send_and_assert_no_replies(self.pg0, pkts, "IP no punt config")
#
# Add a redirect that is not input port selective
#
- ip_punt_redirect = VppIpPuntRedirect(self, 0xffffffff,
- self.pg1.sw_if_index, nh_addr)
+ ip_punt_redirect = VppIpPuntRedirect(
+ self, 0xFFFFFFFF, self.pg1.sw_if_index, nh_addr
+ )
ip_punt_redirect.add_vpp_config()
self.send_and_expect(self.pg0, pkts, self.pg1)
ip_punt_redirect.remove_vpp_config()
def test_ip_punt_vrf(self):
- """ IP punt/local with VRFs """
+ """IP punt/local with VRFs"""
# use a punt redirect to test if for-us packets are accepted
pkts = self.pkt * 1025
- vlans_pg0 = [VppDot1QSubint(self, self.pg0, v)
- for v in range(100, 104)]
- vlans_pg1 = [VppDot1QSubint(self, self.pg1, v)
- for v in range(100, 104)]
- tbl4 = [VppIpTable(self, v).add_vpp_config()
- for v in range(100, 104)]
- tbl6 = [VppIpTable(self, v, True).add_vpp_config()
- for v in range(100, 104)]
+ vlans_pg0 = [VppDot1QSubint(self, self.pg0, v) for v in range(100, 104)]
+ vlans_pg1 = [VppDot1QSubint(self, self.pg1, v) for v in range(100, 104)]
+ tbl4 = [VppIpTable(self, v).add_vpp_config() for v in range(100, 104)]
+ tbl6 = [VppIpTable(self, v, True).add_vpp_config() for v in range(100, 104)]
for v in vlans_pg0 + vlans_pg1:
v.admin_up()
@@ -1608,27 +1742,35 @@ class TestIPPunt(IPPuntSetup, VppTestCase):
v.resolve_arp()
v.resolve_ndp()
- [VppIpPuntRedirect
- (self,
- vlans_pg0[i].sw_if_index,
- vlans_pg1[i].sw_if_index,
- vlans_pg1[i].remote_ip4).add_vpp_config()
- for i in range(4)]
- [VppIpPuntRedirect
- (self,
- vlans_pg0[i].sw_if_index,
- vlans_pg1[i].sw_if_index,
- vlans_pg1[i].remote_ip6).add_vpp_config()
- for i in range(4)]
-
- pkts = [(Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- Dot1Q(vlan=i.vlan) /
- IP(src=i.remote_ip4,
- dst=i.local_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- for i in vlans_pg0]
+ [
+ VppIpPuntRedirect(
+ self,
+ vlans_pg0[i].sw_if_index,
+ vlans_pg1[i].sw_if_index,
+ vlans_pg1[i].remote_ip4,
+ ).add_vpp_config()
+ for i in range(4)
+ ]
+ [
+ VppIpPuntRedirect(
+ self,
+ vlans_pg0[i].sw_if_index,
+ vlans_pg1[i].sw_if_index,
+ vlans_pg1[i].remote_ip6,
+ ).add_vpp_config()
+ for i in range(4)
+ ]
+
+ pkts = [
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / Dot1Q(vlan=i.vlan)
+ / IP(src=i.remote_ip4, dst=i.local_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ for i in vlans_pg0
+ ]
self.send_and_expect(self.pg0, pkts, self.pg1)
@@ -1637,33 +1779,37 @@ class TestIPPunt(IPPuntSetup, VppTestCase):
#
# we reject packets for source addresses in the wrong vlan/VRF
- pkts = [(Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- Dot1Q(vlan=i.vlan) /
- IP(src="1.1.1.1",
- dst=i.local_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- for i in vlans_pg0]
+ pkts = [
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / Dot1Q(vlan=i.vlan)
+ / IP(src="1.1.1.1", dst=i.local_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ for i in vlans_pg0
+ ]
# single and dual loop
self.send_and_assert_no_replies(self.pg0, [pkts[0]])
self.send_and_assert_no_replies(self.pg0, pkts)
self.assert_error_counter_equal(
- "/err/ip4-local/ip4 source lookup miss",
- len(pkts) + 1)
+ "/err/ip4-local/ip4 source lookup miss", len(pkts) + 1
+ )
# using the same source in different tables, should reject
# for the table that the source is not present in
# the first packet in the stream is drop
- pkts = [(Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- Dot1Q(vlan=i.vlan) /
- IP(src=vlans_pg0[0].remote_ip4,
- dst=i.local_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- for i in vlans_pg0]
+ pkts = [
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / Dot1Q(vlan=i.vlan)
+ / IP(src=vlans_pg0[0].remote_ip4, dst=i.local_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ for i in vlans_pg0
+ ]
# single loop accept and drop
# followed by both in the same frame/loop
self.send_and_expect(self.pg0, [pkts[0]], self.pg1)
@@ -1673,14 +1819,16 @@ class TestIPPunt(IPPuntSetup, VppTestCase):
# using the same source in different tables, should reject
# for the table that the source is not present in
# the first packet in the stream is accept
- pkts = [(Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- Dot1Q(vlan=i.vlan) /
- IP(src=vlans_pg0[3].remote_ip4,
- dst=i.local_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- for i in vlans_pg0]
+ pkts = [
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / Dot1Q(vlan=i.vlan)
+ / IP(src=vlans_pg0[3].remote_ip4, dst=i.local_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ for i in vlans_pg0
+ ]
# single loop accept and drop
# followed by both in the same frame/loop
@@ -1693,33 +1841,37 @@ class TestIPPunt(IPPuntSetup, VppTestCase):
#
# we reject packets for source addresses in the wrong vlan/VRF
- pkts = [(Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- Dot1Q(vlan=i.vlan) /
- IPv6(src="1::1",
- dst=i.local_ip6) /
- UDP(sport=1236, dport=1236) /
- Raw(b'\xa5' * 100))
- for i in vlans_pg0]
+ pkts = [
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / Dot1Q(vlan=i.vlan)
+ / IPv6(src="1::1", dst=i.local_ip6)
+ / UDP(sport=1236, dport=1236)
+ / Raw(b"\xa5" * 100)
+ )
+ for i in vlans_pg0
+ ]
# single and dual loop
self.send_and_assert_no_replies(self.pg0, [pkts[0]])
self.send_and_assert_no_replies(self.pg0, pkts)
self.assert_error_counter_equal(
- "/err/ip6-input/ip6 source lookup miss",
- len(pkts) + 1)
+ "/err/ip6-input/ip6 source lookup miss", len(pkts) + 1
+ )
# using the same source in different tables, should reject
# for the table that the source is not present in
# the first packet in the stream is drop
- pkts = [(Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- Dot1Q(vlan=i.vlan) /
- IPv6(src=vlans_pg0[0].remote_ip6,
- dst=i.local_ip6) /
- UDP(sport=1236, dport=1236) /
- Raw(b'\xa5' * 100))
- for i in vlans_pg0]
+ pkts = [
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / Dot1Q(vlan=i.vlan)
+ / IPv6(src=vlans_pg0[0].remote_ip6, dst=i.local_ip6)
+ / UDP(sport=1236, dport=1236)
+ / Raw(b"\xa5" * 100)
+ )
+ for i in vlans_pg0
+ ]
# single loop accept and drop
# followed by both in the same frame/loop
self.send_and_expect(self.pg0, [pkts[0]], self.pg1)
@@ -1729,14 +1881,16 @@ class TestIPPunt(IPPuntSetup, VppTestCase):
# using the same source in different tables, should reject
# for the table that the source is not present in
# the first packet in the stream is accept
- pkts = [(Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- Dot1Q(vlan=i.vlan) /
- IPv6(src=vlans_pg0[3].remote_ip6,
- dst=i.local_ip6) /
- UDP(sport=1236, dport=1236) /
- Raw(b'\xa5' * 100))
- for i in vlans_pg0]
+ pkts = [
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / Dot1Q(vlan=i.vlan)
+ / IPv6(src=vlans_pg0[3].remote_ip6, dst=i.local_ip6)
+ / UDP(sport=1236, dport=1236)
+ / Raw(b"\xa5" * 100)
+ )
+ for i in vlans_pg0
+ ]
# single loop accept and drop
# followed by both in the same frame/loop
@@ -1751,18 +1905,21 @@ class TestIPPunt(IPPuntSetup, VppTestCase):
v.set_table_ip6(0)
def test_ip_punt_dump(self):
- """ IP4 punt redirect dump"""
+ """IP4 punt redirect dump"""
#
# Configure a punt redirects
#
nh_address = self.pg3.remote_ip4
- ipr_03 = VppIpPuntRedirect(self, self.pg0.sw_if_index,
- self.pg3.sw_if_index, nh_address)
- ipr_13 = VppIpPuntRedirect(self, self.pg1.sw_if_index,
- self.pg3.sw_if_index, nh_address)
- ipr_23 = VppIpPuntRedirect(self, self.pg2.sw_if_index,
- self.pg3.sw_if_index, "0.0.0.0")
+ ipr_03 = VppIpPuntRedirect(
+ self, self.pg0.sw_if_index, self.pg3.sw_if_index, nh_address
+ )
+ ipr_13 = VppIpPuntRedirect(
+ self, self.pg1.sw_if_index, self.pg3.sw_if_index, nh_address
+ )
+ ipr_23 = VppIpPuntRedirect(
+ self, self.pg2.sw_if_index, self.pg3.sw_if_index, "0.0.0.0"
+ )
ipr_03.add_vpp_config()
ipr_13.add_vpp_config()
ipr_23.add_vpp_config()
@@ -1777,16 +1934,17 @@ class TestIPPunt(IPPuntSetup, VppTestCase):
#
# Dump punt redirects for all interfaces
#
- punts = self.vapi.ip_punt_redirect_dump(0xffffffff)
+ punts = self.vapi.ip_punt_redirect_dump(0xFFFFFFFF)
self.assertEqual(len(punts), 3)
for p in punts:
self.assertEqual(p.punt.tx_sw_if_index, self.pg3.sw_if_index)
self.assertNotEqual(punts[1].punt.nh, self.pg3.remote_ip4)
- self.assertEqual(str(punts[2].punt.nh), '0.0.0.0')
+ self.assertEqual(str(punts[2].punt.nh), "0.0.0.0")
class TestIPPuntHandoff(IPPuntSetup, VppTestCase):
- """ IPv4 Punt Policer thread handoff """
+ """IPv4 Punt Policer thread handoff"""
+
vpp_worker_count = 2
def setUp(self):
@@ -1798,26 +1956,40 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase):
super(TestIPPuntHandoff, self).tearDown()
def test_ip_punt_policer_handoff(self):
- """ IP4 punt policer thread handoff """
+ """IP4 punt policer thread handoff"""
pkts = self.pkt * NUM_PKTS
#
# Configure a punt redirect via pg1.
#
nh_addr = self.pg1.remote_ip4
- ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index,
- self.pg1.sw_if_index, nh_addr)
+ ip_punt_redirect = VppIpPuntRedirect(
+ self, self.pg0.sw_if_index, self.pg1.sw_if_index, nh_addr
+ )
ip_punt_redirect.add_vpp_config()
action_tx = PolicerAction(
- VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT,
- 0)
+ VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0
+ )
#
# This policer drops no packets, we are just
# testing that they get to the right thread.
#
- policer = VppPolicer(self, "ip4-punt", 400, 0, 10, 0, 1,
- 0, 0, False, action_tx, action_tx, action_tx)
+ policer = VppPolicer(
+ self,
+ "ip4-punt",
+ 400,
+ 0,
+ 10,
+ 0,
+ 1,
+ 0,
+ 0,
+ False,
+ action_tx,
+ action_tx,
+ action_tx,
+ )
policer.add_vpp_config()
ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index)
ip_punt_policer.add_vpp_config()
@@ -1830,9 +2002,9 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase):
stats = policer.get_stats()
# Single rate policer - expect conform, violate but no exceed
- self.assertGreater(stats['conform_packets'], 0)
- self.assertEqual(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ self.assertGreater(stats["conform_packets"], 0)
+ self.assertEqual(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
# Worker 0, should have done all the policing
stats0 = policer.get_stats(worker=0)
@@ -1840,9 +2012,9 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase):
# Worker 1, should have handed everything off
stats1 = policer.get_stats(worker=1)
- self.assertEqual(stats1['conform_packets'], 0)
- self.assertEqual(stats1['exceed_packets'], 0)
- self.assertEqual(stats1['violate_packets'], 0)
+ self.assertEqual(stats1["conform_packets"], 0)
+ self.assertEqual(stats1["exceed_packets"], 0)
+ self.assertEqual(stats1["violate_packets"], 0)
# Bind the policer to worker 1 and repeat
policer.bind_vpp_config(1, True)
@@ -1855,19 +2027,23 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase):
stats0 = policer.get_stats(worker=0)
stats1 = policer.get_stats(worker=1)
- self.assertGreater(stats0['conform_packets'], 0)
- self.assertEqual(stats0['exceed_packets'], 0)
- self.assertGreater(stats0['violate_packets'], 0)
+ self.assertGreater(stats0["conform_packets"], 0)
+ self.assertEqual(stats0["exceed_packets"], 0)
+ self.assertGreater(stats0["violate_packets"], 0)
- self.assertGreater(stats1['conform_packets'], 0)
- self.assertEqual(stats1['exceed_packets'], 0)
- self.assertGreater(stats1['violate_packets'], 0)
+ self.assertGreater(stats1["conform_packets"], 0)
+ self.assertEqual(stats1["exceed_packets"], 0)
+ self.assertGreater(stats1["violate_packets"], 0)
- self.assertEqual(stats0['conform_packets'] + stats1['conform_packets'],
- stats['conform_packets'])
+ self.assertEqual(
+ stats0["conform_packets"] + stats1["conform_packets"],
+ stats["conform_packets"],
+ )
- self.assertEqual(stats0['violate_packets'] + stats1['violate_packets'],
- stats['violate_packets'])
+ self.assertEqual(
+ stats0["violate_packets"] + stats1["violate_packets"],
+ stats["violate_packets"],
+ )
# Unbind the policer and repeat
policer.bind_vpp_config(1, False)
@@ -1880,11 +2056,9 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase):
stats0new = policer.get_stats(worker=0)
stats1new = policer.get_stats(worker=1)
- self.assertGreater(stats0new['conform_packets'],
- stats0['conform_packets'])
- self.assertEqual(stats0new['exceed_packets'], 0)
- self.assertGreater(stats0new['violate_packets'],
- stats0['violate_packets'])
+ self.assertGreater(stats0new["conform_packets"], stats0["conform_packets"])
+ self.assertEqual(stats0new["exceed_packets"], 0)
+ self.assertGreater(stats0new["violate_packets"], stats0["violate_packets"])
self.assertEqual(stats1, stats1new)
@@ -1897,7 +2071,7 @@ class TestIPPuntHandoff(IPPuntSetup, VppTestCase):
class TestIPDeag(VppTestCase):
- """ IPv4 Deaggregate Routes """
+ """IPv4 Deaggregate Routes"""
@classmethod
def setUpClass(cls):
@@ -1924,7 +2098,7 @@ class TestIPDeag(VppTestCase):
i.admin_down()
def test_ip_deag(self):
- """ IP Deag Routes """
+ """IP Deag Routes"""
#
# Create a table to be used for:
@@ -1940,16 +2114,22 @@ class TestIPDeag(VppTestCase):
# Add a route in the default table to point to a deag/
# second lookup in each of these tables
#
- route_to_dst = VppIpRoute(self, "1.1.1.1", 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=1)])
+ route_to_dst = VppIpRoute(
+ self, "1.1.1.1", 32, [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)]
+ )
route_to_src = VppIpRoute(
- self, "1.1.1.2", 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=2,
- type=FibPathType.FIB_PATH_TYPE_SOURCE_LOOKUP)])
+ self,
+ "1.1.1.2",
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ nh_table_id=2,
+ type=FibPathType.FIB_PATH_TYPE_SOURCE_LOOKUP,
+ )
+ ],
+ )
route_to_dst.add_vpp_config()
route_to_src.add_vpp_config()
@@ -1957,31 +2137,34 @@ class TestIPDeag(VppTestCase):
# packets to these destination are dropped, since they'll
# hit the respective default routes in the second table
#
- p_dst = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="5.5.5.5", dst="1.1.1.1") /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- p_src = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="2.2.2.2", dst="1.1.1.2") /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_dst = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="5.5.5.5", dst="1.1.1.1")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ p_src = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="2.2.2.2", dst="1.1.1.2")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
pkts_dst = p_dst * 257
pkts_src = p_src * 257
- self.send_and_assert_no_replies(self.pg0, pkts_dst,
- "IP in dst table")
- self.send_and_assert_no_replies(self.pg0, pkts_src,
- "IP in src table")
+ self.send_and_assert_no_replies(self.pg0, pkts_dst, "IP in dst table")
+ self.send_and_assert_no_replies(self.pg0, pkts_src, "IP in src table")
#
# add a route in the dst table to forward via pg1
#
- route_in_dst = VppIpRoute(self, "1.1.1.1", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)],
- table_id=1)
+ route_in_dst = VppIpRoute(
+ self,
+ "1.1.1.1",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ table_id=1,
+ )
route_in_dst.add_vpp_config()
self.send_and_expect(self.pg0, pkts_dst, self.pg1)
@@ -1989,34 +2172,36 @@ class TestIPDeag(VppTestCase):
#
# add a route in the src table to forward via pg2
#
- route_in_src = VppIpRoute(self, "2.2.2.2", 32,
- [VppRoutePath(self.pg2.remote_ip4,
- self.pg2.sw_if_index)],
- table_id=2)
+ route_in_src = VppIpRoute(
+ self,
+ "2.2.2.2",
+ 32,
+ [VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index)],
+ table_id=2,
+ )
route_in_src.add_vpp_config()
self.send_and_expect(self.pg0, pkts_src, self.pg2)
#
# loop in the lookup DP
#
- route_loop = VppIpRoute(self, "2.2.2.3", 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=0)])
+ route_loop = VppIpRoute(
+ self, "2.2.2.3", 32, [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)]
+ )
route_loop.add_vpp_config()
- p_l = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="2.2.2.4", dst="2.2.2.3") /
- TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_l = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="2.2.2.4", dst="2.2.2.3")
+ / TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- self.send_and_assert_no_replies(self.pg0, p_l * 257,
- "IP lookup loop")
+ self.send_and_assert_no_replies(self.pg0, p_l * 257, "IP lookup loop")
class TestIPInput(VppTestCase):
- """ IPv4 Input Exceptions """
+ """IPv4 Input Exceptions"""
@classmethod
def setUpClass(cls):
@@ -2043,7 +2228,7 @@ class TestIPInput(VppTestCase):
i.admin_down()
def test_ip_input(self):
- """ IP Input Exceptions """
+ """IP Input Exceptions"""
# i can't find a way in scapy to construct an IP packet
# with a length less than the IP header length
@@ -2051,103 +2236,95 @@ class TestIPInput(VppTestCase):
#
# Packet too short - this is forwarded
#
- p_short = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4,
- len=40) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_short = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, len=40)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg0, p_short * NUM_PKTS, self.pg1)
#
# Packet too long - this is dropped
#
- p_long = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4,
- len=400) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_long = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, len=400)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- rx = self.send_and_assert_no_replies(self.pg0, p_long * NUM_PKTS,
- "too long")
+ rx = self.send_and_assert_no_replies(self.pg0, p_long * NUM_PKTS, "too long")
#
# bad chksum - this is dropped
#
- p_chksum = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4,
- chksum=400) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_chksum = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, chksum=400)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- rx = self.send_and_assert_no_replies(self.pg0, p_chksum * NUM_PKTS,
- "bad checksum")
+ rx = self.send_and_assert_no_replies(
+ self.pg0, p_chksum * NUM_PKTS, "bad checksum"
+ )
#
# bad version - this is dropped
#
- p_ver = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4,
- version=3) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_ver = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, version=3)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- rx = self.send_and_assert_no_replies(self.pg0, p_ver * NUM_PKTS,
- "funky version")
+ rx = self.send_and_assert_no_replies(
+ self.pg0, p_ver * NUM_PKTS, "funky version"
+ )
#
# fragment offset 1 - this is dropped
#
- p_frag = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4,
- frag=1) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_frag = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, frag=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- rx = self.send_and_assert_no_replies(self.pg0, p_frag * NUM_PKTS,
- "frag offset")
+ rx = self.send_and_assert_no_replies(self.pg0, p_frag * NUM_PKTS, "frag offset")
#
# TTL expired packet
#
- p_ttl = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4,
- ttl=1) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_ttl = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect_some(self.pg0, p_ttl * NUM_PKTS, self.pg0)
for rx in rxs:
icmp = rx[ICMP]
self.assertEqual(icmptypes[icmp.type], "time-exceeded")
- self.assertEqual(icmpcodes[icmp.type][icmp.code],
- "ttl-zero-during-transit")
+ self.assertEqual(icmpcodes[icmp.type][icmp.code], "ttl-zero-during-transit")
self.assertEqual(icmp.src, self.pg0.remote_ip4)
self.assertEqual(icmp.dst, self.pg1.remote_ip4)
#
# MTU exceeded
#
- p_mtu = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4,
- ttl=10, flags='DF') /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 2000))
+ p_mtu = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=10, flags="DF")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 2000)
+ )
self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1500, 0, 0, 0])
@@ -2156,8 +2333,7 @@ class TestIPInput(VppTestCase):
for rx in rxs:
icmp = rx[ICMP]
self.assertEqual(icmptypes[icmp.type], "dest-unreach")
- self.assertEqual(icmpcodes[icmp.type][icmp.code],
- "fragmentation-needed")
+ self.assertEqual(icmpcodes[icmp.type][icmp.code], "fragmentation-needed")
self.assertEqual(icmp.nexthopmtu, 1500)
self.assertEqual(icmp.src, self.pg0.remote_ip4)
self.assertEqual(icmp.dst, self.pg1.remote_ip4)
@@ -2171,25 +2347,25 @@ class TestIPInput(VppTestCase):
#
# source address 0.0.0.0 and 25.255.255.255 and for-us
#
- p_s0 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="0.0.0.0",
- dst=self.pg0.local_ip4) /
- ICMP(id=4, seq=4) /
- Raw(load=b'\x0a' * 18))
+ p_s0 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="0.0.0.0", dst=self.pg0.local_ip4)
+ / ICMP(id=4, seq=4)
+ / Raw(load=b"\x0a" * 18)
+ )
rx = self.send_and_assert_no_replies(self.pg0, p_s0 * 17)
- p_s0 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="255.255.255.255",
- dst=self.pg0.local_ip4) /
- ICMP(id=4, seq=4) /
- Raw(load=b'\x0a' * 18))
+ p_s0 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="255.255.255.255", dst=self.pg0.local_ip4)
+ / ICMP(id=4, seq=4)
+ / Raw(load=b"\x0a" * 18)
+ )
rx = self.send_and_assert_no_replies(self.pg0, p_s0 * 17)
class TestIPDirectedBroadcast(VppTestCase):
- """ IPv4 Directed Broadcast """
+ """IPv4 Directed Broadcast"""
@classmethod
def setUpClass(cls):
@@ -2213,26 +2389,25 @@ class TestIPDirectedBroadcast(VppTestCase):
i.admin_down()
def test_ip_input(self):
- """ IP Directed Broadcast """
+ """IP Directed Broadcast"""
#
# set the directed broadcast on pg0 first, then config IP4 addresses
# for pg1 directed broadcast is always disabled
- self.vapi.sw_interface_set_ip_directed_broadcast(
- self.pg0.sw_if_index, 1)
-
- p0 = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IP(src="1.1.1.1",
- dst=self.pg0._local_ip4_bcast) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 2000))
- p1 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="1.1.1.1",
- dst=self.pg1._local_ip4_bcast) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 2000))
+ self.vapi.sw_interface_set_ip_directed_broadcast(self.pg0.sw_if_index, 1)
+
+ p0 = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src="1.1.1.1", dst=self.pg0._local_ip4_bcast)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 2000)
+ )
+ p1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="1.1.1.1", dst=self.pg1._local_ip4_bcast)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 2000)
+ )
self.pg0.config_ip4()
self.pg0.resolve_arp()
@@ -2245,19 +2420,19 @@ class TestIPDirectedBroadcast(VppTestCase):
rx = self.send_and_expect(self.pg1, p0 * NUM_PKTS, self.pg0)
self.assertTrue(rx[0][Ether].dst, "ff:ff:ff:ff:ff:ff")
- self.send_and_assert_no_replies(self.pg0, p1 * NUM_PKTS,
- "directed broadcast disabled")
+ self.send_and_assert_no_replies(
+ self.pg0, p1 * NUM_PKTS, "directed broadcast disabled"
+ )
#
# toggle directed broadcast on pg0
#
- self.vapi.sw_interface_set_ip_directed_broadcast(
- self.pg0.sw_if_index, 0)
- self.send_and_assert_no_replies(self.pg1, p0 * NUM_PKTS,
- "directed broadcast disabled")
+ self.vapi.sw_interface_set_ip_directed_broadcast(self.pg0.sw_if_index, 0)
+ self.send_and_assert_no_replies(
+ self.pg1, p0 * NUM_PKTS, "directed broadcast disabled"
+ )
- self.vapi.sw_interface_set_ip_directed_broadcast(
- self.pg0.sw_if_index, 1)
+ self.vapi.sw_interface_set_ip_directed_broadcast(self.pg0.sw_if_index, 1)
rx = self.send_and_expect(self.pg1, p0 * NUM_PKTS, self.pg0)
self.pg0.unconfig_ip4()
@@ -2265,7 +2440,7 @@ class TestIPDirectedBroadcast(VppTestCase):
class TestIPLPM(VppTestCase):
- """ IPv4 longest Prefix Match """
+ """IPv4 longest Prefix Match"""
@classmethod
def setUpClass(cls):
@@ -2292,29 +2467,35 @@ class TestIPLPM(VppTestCase):
i.unconfig_ip4()
def test_ip_lpm(self):
- """ IP longest Prefix Match """
+ """IP longest Prefix Match"""
- s_24 = VppIpRoute(self, "10.1.2.0", 24,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ s_24 = VppIpRoute(
+ self,
+ "10.1.2.0",
+ 24,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
s_24.add_vpp_config()
- s_8 = VppIpRoute(self, "10.0.0.0", 8,
- [VppRoutePath(self.pg2.remote_ip4,
- self.pg2.sw_if_index)])
+ s_8 = VppIpRoute(
+ self,
+ "10.0.0.0",
+ 8,
+ [VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index)],
+ )
s_8.add_vpp_config()
- p_8 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="1.1.1.1",
- dst="10.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 2000))
- p_24 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="1.1.1.1",
- dst="10.1.2.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 2000))
+ p_8 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="1.1.1.1", dst="10.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 2000)
+ )
+ p_24 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="1.1.1.1", dst="10.1.2.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 2000)
+ )
self.logger.info(self.vapi.cli("sh ip fib mtrie"))
rx = self.send_and_expect(self.pg0, p_8 * NUM_PKTS, self.pg2)
@@ -2323,7 +2504,7 @@ class TestIPLPM(VppTestCase):
@tag_fixme_vpp_workers
class TestIPv4Frag(VppTestCase):
- """ IPv4 fragmentation """
+ """IPv4 fragmentation"""
@classmethod
def setUpClass(cls):
@@ -2344,25 +2525,29 @@ class TestIPv4Frag(VppTestCase):
super(TestIPv4Frag, cls).tearDownClass()
def test_frag_large_packets(self):
- """ Fragmentation of large packets """
+ """Fragmentation of large packets"""
self.vapi.cli("adjacency counters enable")
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IP(src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) / Raw())
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw()
+ )
self.extend_packet(p, 6000, "abcde")
saved_payload = p[Raw].load
- nbr = VppNeighbor(self,
- self.dst_if.sw_if_index,
- self.dst_if.remote_mac,
- self.dst_if.remote_ip4).add_vpp_config()
+ nbr = VppNeighbor(
+ self,
+ self.dst_if.sw_if_index,
+ self.dst_if.remote_mac,
+ self.dst_if.remote_ip4,
+ ).add_vpp_config()
# Force fragmentation by setting MTU of output interface
# lower than packet size
- self.vapi.sw_interface_set_mtu(self.dst_if.sw_if_index,
- [5000, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.dst_if.sw_if_index, [5000, 0, 0, 0])
self.pg_enable_capture()
self.src_if.add_stream(p)
@@ -2373,10 +2558,10 @@ class TestIPv4Frag(VppTestCase):
packets = self.dst_if.get_capture(3)
# we should show 3 packets thru the neighbor
- self.assertEqual(3, nbr.get_stats()['packets'])
+ self.assertEqual(3, nbr.get_stats()["packets"])
# Assume VPP sends the fragments in order
- payload = b''
+ payload = b""
for p in packets:
payload_offset = p.frag * 8
if payload_offset > 0:
@@ -2387,7 +2572,7 @@ class TestIPv4Frag(VppTestCase):
class TestIPReplace(VppTestCase):
- """ IPv4 Table Replace """
+ """IPv4 Table Replace"""
@classmethod
def setUpClass(cls):
@@ -2420,7 +2605,7 @@ class TestIPReplace(VppTestCase):
i.unconfig_ip4()
def test_replace(self):
- """ IP Table Replace """
+ """IP Table Replace"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -2432,27 +2617,46 @@ class TestIPReplace(VppTestCase):
for ii, t in enumerate(self.tables):
for jj in range(N_ROUTES):
uni = VppIpRoute(
- self, "10.0.0.%d" % jj, 32,
- [VppRoutePath(links[ii].remote_hosts[0].ip4,
- links[ii].sw_if_index),
- VppRoutePath(links[ii].remote_hosts[1].ip4,
- links[ii].sw_if_index)],
- table_id=t.table_id).add_vpp_config()
+ self,
+ "10.0.0.%d" % jj,
+ 32,
+ [
+ VppRoutePath(
+ links[ii].remote_hosts[0].ip4, links[ii].sw_if_index
+ ),
+ VppRoutePath(
+ links[ii].remote_hosts[1].ip4, links[ii].sw_if_index
+ ),
+ ],
+ table_id=t.table_id,
+ ).add_vpp_config()
multi = VppIpMRoute(
- self, "0.0.0.0",
- "239.0.0.%d" % jj, 32,
+ self,
+ "0.0.0.0",
+ "239.0.0.%d" % jj,
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg3.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)],
- table_id=t.table_id).add_vpp_config()
- routes[ii].append({'uni': uni,
- 'multi': multi})
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ ),
+ VppMRoutePath(
+ self.pg2.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ ),
+ VppMRoutePath(
+ self.pg3.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ ),
+ ],
+ table_id=t.table_id,
+ ).add_vpp_config()
+ routes[ii].append({"uni": uni, "multi": multi})
#
# replace the tables a few times
@@ -2467,14 +2671,14 @@ class TestIPReplace(VppTestCase):
dump = t.dump()
mdump = t.mdump()
for r in routes[ii]:
- self.assertTrue(find_route_in_dump(dump, r['uni'], t))
- self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t))
+ self.assertTrue(find_route_in_dump(dump, r["uni"], t))
+ self.assertTrue(find_mroute_in_dump(mdump, r["multi"], t))
# redownload the even numbered routes
for ii, t in enumerate(self.tables):
for jj in range(0, N_ROUTES, 2):
- routes[ii][jj]['uni'].add_vpp_config()
- routes[ii][jj]['multi'].add_vpp_config()
+ routes[ii][jj]["uni"].add_vpp_config()
+ routes[ii][jj]["multi"].add_vpp_config()
# signal each table replace_end
for t in self.tables:
@@ -2485,29 +2689,29 @@ class TestIPReplace(VppTestCase):
dump = t.dump()
mdump = t.mdump()
for jj in range(0, N_ROUTES, 2):
- self.assertTrue(find_route_in_dump(
- dump, routes[ii][jj]['uni'], t))
- self.assertTrue(find_mroute_in_dump(
- mdump, routes[ii][jj]['multi'], t))
+ self.assertTrue(find_route_in_dump(dump, routes[ii][jj]["uni"], t))
+ self.assertTrue(
+ find_mroute_in_dump(mdump, routes[ii][jj]["multi"], t)
+ )
for jj in range(1, N_ROUTES - 1, 2):
- self.assertFalse(find_route_in_dump(
- dump, routes[ii][jj]['uni'], t))
- self.assertFalse(find_mroute_in_dump(
- mdump, routes[ii][jj]['multi'], t))
+ self.assertFalse(find_route_in_dump(dump, routes[ii][jj]["uni"], t))
+ self.assertFalse(
+ find_mroute_in_dump(mdump, routes[ii][jj]["multi"], t)
+ )
# reload all the routes
for ii, t in enumerate(self.tables):
for r in routes[ii]:
- r['uni'].add_vpp_config()
- r['multi'].add_vpp_config()
+ r["uni"].add_vpp_config()
+ r["multi"].add_vpp_config()
# all the routes are still there
for ii, t in enumerate(self.tables):
dump = t.dump()
mdump = t.mdump()
for r in routes[ii]:
- self.assertTrue(find_route_in_dump(dump, r['uni'], t))
- self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t))
+ self.assertTrue(find_route_in_dump(dump, r["uni"], t))
+ self.assertTrue(find_mroute_in_dump(mdump, r["multi"], t))
#
# finally flush the tables for good measure
@@ -2519,7 +2723,7 @@ class TestIPReplace(VppTestCase):
class TestIPCover(VppTestCase):
- """ IPv4 Table Cover """
+ """IPv4 Table Cover"""
@classmethod
def setUpClass(cls):
@@ -2552,7 +2756,7 @@ class TestIPCover(VppTestCase):
i.unconfig_ip4()
def test_cover(self):
- """ IP Table Cover """
+ """IP Table Cover"""
# add a loop back with a /32 prefix
lo = VppLoInterface(self)
@@ -2560,21 +2764,23 @@ class TestIPCover(VppTestCase):
a = VppIpInterfaceAddress(self, lo, "127.0.0.1", 32).add_vpp_config()
# add a neighbour that matches the loopback's /32
- nbr = VppNeighbor(self,
- lo.sw_if_index,
- lo.remote_mac,
- "127.0.0.1").add_vpp_config()
+ nbr = VppNeighbor(
+ self, lo.sw_if_index, lo.remote_mac, "127.0.0.1"
+ ).add_vpp_config()
# add the default route which will be the cover for /32
- r = VppIpRoute(self, "0.0.0.0", 0,
- [VppRoutePath("127.0.0.1",
- lo.sw_if_index)],
- register=False).add_vpp_config()
+ r = VppIpRoute(
+ self,
+ "0.0.0.0",
+ 0,
+ [VppRoutePath("127.0.0.1", lo.sw_if_index)],
+ register=False,
+ ).add_vpp_config()
# add/remove/add a longer mask cover
- r8 = VppIpRoute(self, "127.0.0.0", 8,
- [VppRoutePath("127.0.0.1",
- lo.sw_if_index)]).add_vpp_config()
+ r8 = VppIpRoute(
+ self, "127.0.0.0", 8, [VppRoutePath("127.0.0.1", lo.sw_if_index)]
+ ).add_vpp_config()
r8.remove_vpp_config()
r8.add_vpp_config()
r8.remove_vpp_config()
@@ -2587,7 +2793,7 @@ class TestIPCover(VppTestCase):
class TestIP4Replace(VppTestCase):
- """ IPv4 Interface Address Replace """
+ """IPv4 Interface Address Replace"""
@classmethod
def setUpClass(cls):
@@ -2614,7 +2820,7 @@ class TestIP4Replace(VppTestCase):
return len(self.vapi.ip_address_dump(intf.sw_if_index))
def test_replace(self):
- """ IP interface address replace """
+ """IP interface address replace"""
intf_pfxs = [[], [], [], []]
@@ -2698,8 +2904,7 @@ class TestIP4Replace(VppTestCase):
for intf in self.pg_interfaces:
# 172.18.x.1/24
addr = "172.18.%d.1" % intf.sw_if_index
- pfxs.append(VppIpInterfaceAddress(self, intf, addr,
- 24).add_vpp_config())
+ pfxs.append(VppIpInterfaceAddress(self, intf, addr, 24).add_vpp_config())
self.vapi.sw_interface_address_replace_end()
@@ -2734,8 +2939,7 @@ class TestIP4Replace(VppTestCase):
for intf in self.pg_interfaces:
# 172.18.x.1/24
addr = "172.18.%d.1" % (intf.sw_if_index + 1)
- pfxs.append(VppIpInterfaceAddress(self, intf,
- addr, 24).add_vpp_config())
+ pfxs.append(VppIpInterfaceAddress(self, intf, addr, 24).add_vpp_config())
self.vapi.sw_interface_address_replace_end()
@@ -2748,7 +2952,7 @@ class TestIP4Replace(VppTestCase):
class TestIPv4PathMTU(VppTestCase):
- """ IPv4 Path MTU """
+ """IPv4 Path MTU"""
@classmethod
def setUpClass(cls):
@@ -2767,7 +2971,7 @@ class TestIPv4PathMTU(VppTestCase):
super(TestIPv4PathMTU, cls).tearDownClass()
def test_path_mtu(self):
- """ Path MTU """
+ """Path MTU"""
#
# The goal here is not to test that fragmentation works correctly,
@@ -2777,28 +2981,26 @@ class TestIPv4PathMTU(VppTestCase):
self.vapi.cli("adjacency counters enable")
# set the interface MTU to a reasonable value
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [1800, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1800, 0, 0, 0])
self.pg1.generate_remote_hosts(4)
- p_2k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 640))
- p_1k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 320))
-
- nbr = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_mac,
- self.pg1.remote_ip4).add_vpp_config()
+ p_2k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 640)
+ )
+ p_1k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 320)
+ )
+
+ nbr = VppNeighbor(
+ self, self.pg1.sw_if_index, self.pg1.remote_mac, self.pg1.remote_ip4
+ ).add_vpp_config()
# this is now the interface MTU frags
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2)
@@ -2832,21 +3034,18 @@ class TestIPv4PathMTU(VppTestCase):
# raise the interface's MTU
# should still use that of the path
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [2000, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2000, 0, 0, 0])
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
# set path high and interface low
pmtu.modify(2000)
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [900, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [900, 0, 0, 0])
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
# remove the path MTU using the mark-n-sweep semantics
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [1800, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1800, 0, 0, 0])
self.vapi.ip_path_mtu_replace_begin()
self.vapi.ip_path_mtu_replace_end()
@@ -2856,27 +3055,27 @@ class TestIPv4PathMTU(VppTestCase):
#
# set path MTU for a neighbour that doesn't exist, yet
#
- pmtu2 = VppIpPathMtu(self,
- self.pg1.remote_hosts[2].ip4,
- 900).add_vpp_config()
-
- p_2k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_hosts[2].ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 640))
- p_1k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_hosts[2].ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 320))
-
- nbr2 = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[2].mac,
- self.pg1.remote_hosts[2].ip4).add_vpp_config()
+ pmtu2 = VppIpPathMtu(self, self.pg1.remote_hosts[2].ip4, 900).add_vpp_config()
+
+ p_2k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[2].ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 640)
+ )
+ p_1k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[2].ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 320)
+ )
+
+ nbr2 = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[2].mac,
+ self.pg1.remote_hosts[2].ip4,
+ ).add_vpp_config()
# should frag to the path MTU
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
@@ -2916,7 +3115,7 @@ class TestIPv4PathMTU(VppTestCase):
class TestIPv4ItfRebind(VppTestCase):
- """ IPv4 Interface Bind w/ attached routes """
+ """IPv4 Interface Bind w/ attached routes"""
def setUp(self):
super(TestIPv4ItfRebind, self).setUp()
@@ -2927,7 +3126,7 @@ class TestIPv4ItfRebind(VppTestCase):
super(TestIPv4ItfRebind, self).tearDown()
def test_rebind(self):
- """ Import to no import """
+ """Import to no import"""
TABLE_ID = 1
tbl = VppIpTable(self, TABLE_ID).add_vpp_config()
@@ -2940,17 +3139,20 @@ class TestIPv4ItfRebind(VppTestCase):
# add an attached route via an pg0
# in a different table. this prefix should import
- rt = VppIpRoute(self, self.pg0.local_ip4, 24,
- [VppRoutePath("0.0.0.0",
- self.pg0.sw_if_index)],
- table_id=TABLE_ID).add_vpp_config()
-
- p = (Ether(dst=self.pg1.local_mac,
- src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4,
- dst=self.pg0.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 640))
+ rt = VppIpRoute(
+ self,
+ self.pg0.local_ip4,
+ 24,
+ [VppRoutePath("0.0.0.0", self.pg0.sw_if_index)],
+ table_id=TABLE_ID,
+ ).add_vpp_config()
+
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 640)
+ )
rx = self.send_and_expect(self.pg1, [p], self.pg0)
self.assertFalse(rx[0].haslayer(ARP))
@@ -2984,7 +3186,7 @@ class TestIPv4ItfRebind(VppTestCase):
tbl.remove_vpp_config()
def test_delete(self):
- """ Swap import tables """
+ """Swap import tables"""
TABLE_ID1 = 1
tbl1_4 = VppIpTable(self, TABLE_ID1).add_vpp_config()
@@ -3006,19 +3208,25 @@ class TestIPv4ItfRebind(VppTestCase):
# add an attached route in the default table via pg0
# this should import to table 1
- rt4 = VppIpRoute(self, self.pg1.local_ip4, 24,
- [VppRoutePath("0.0.0.0",
- self.pg1.sw_if_index)]).add_vpp_config()
- rt6 = VppIpRoute(self, self.pg1.local_ip6, 64,
- [VppRoutePath("0.0.0.0",
- self.pg1.sw_if_index)]).add_vpp_config()
-
- p1 = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=self.pg1.remote_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 640))
+ rt4 = VppIpRoute(
+ self,
+ self.pg1.local_ip4,
+ 24,
+ [VppRoutePath("0.0.0.0", self.pg1.sw_if_index)],
+ ).add_vpp_config()
+ rt6 = VppIpRoute(
+ self,
+ self.pg1.local_ip6,
+ 64,
+ [VppRoutePath("0.0.0.0", self.pg1.sw_if_index)],
+ ).add_vpp_config()
+
+ p1 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 640)
+ )
# inject into table 0
rx = self.send_and_expect(self.pg0, [p1], self.pg1)
@@ -3050,5 +3258,5 @@ class TestIPv4ItfRebind(VppTestCase):
i.admin_down()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ip4_irb.py b/test/test_ip4_irb.py
index de5231c7dca..ac3b30ba71d 100644
--- a/test/test_ip4_irb.py
+++ b/test/test_ip4_irb.py
@@ -66,12 +66,16 @@ class TestIpIrb(VppTestCase):
# Create BD with MAC learning enabled and put interfaces to this BD
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=cls.bvi0.sw_if_index, bd_id=cls.bd_id,
- port_type=L2_PORT_TYPE.BVI)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=cls.pg0.sw_if_index,
- bd_id=cls.bd_id)
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=cls.pg1.sw_if_index,
- bd_id=cls.bd_id)
+ rx_sw_if_index=cls.bvi0.sw_if_index,
+ bd_id=cls.bd_id,
+ port_type=L2_PORT_TYPE.BVI,
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=cls.pg0.sw_if_index, bd_id=cls.bd_id
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=cls.pg1.sw_if_index, bd_id=cls.bd_id
+ )
# Configure IPv4 addresses on BVI interface and routed interface
cls.bvi0.config_ip4()
@@ -103,8 +107,7 @@ class TestIpIrb(VppTestCase):
def show_commands_at_teardown(self):
self.logger.info(self.vapi.cli("show l2patch"))
self.logger.info(self.vapi.cli("show l2fib verbose"))
- self.logger.info(self.vapi.cli("show bridge-domain %s detail" %
- self.bd_id))
+ self.logger.info(self.vapi.cli("show bridge-domain %s detail" % self.bd_id))
self.logger.info(self.vapi.cli("show ip neighbors"))
def create_stream(self, src_ip_if, dst_ip_if, packet_sizes):
@@ -113,19 +116,19 @@ class TestIpIrb(VppTestCase):
remote_dst_host = choice(dst_ip_if.remote_hosts)
info = self.create_packet_info(src_ip_if, dst_ip_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_ip_if.local_mac, src=src_ip_if.remote_mac) /
- IP(src=src_ip_if.remote_ip4,
- dst=remote_dst_host.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_ip_if.local_mac, src=src_ip_if.remote_mac)
+ / IP(src=src_ip_if.remote_ip4, dst=remote_dst_host.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
size = packet_sizes[(i // 2) % len(packet_sizes)]
self.extend_packet(p, size)
pkts.append(p)
return pkts
- def create_stream_l2_to_ip(self, src_l2_if, src_ip_if, dst_ip_if,
- packet_sizes):
+ def create_stream_l2_to_ip(self, src_l2_if, src_ip_if, dst_ip_if, packet_sizes):
pkts = []
for i in range(0, 257):
info = self.create_packet_info(src_ip_if, dst_ip_if)
@@ -133,12 +136,12 @@ class TestIpIrb(VppTestCase):
host = choice(src_l2_if.remote_hosts)
- p = (Ether(src=host.mac,
- dst=src_ip_if.local_mac) /
- IP(src=host.ip4,
- dst=dst_ip_if.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(src=host.mac, dst=src_ip_if.local_mac)
+ / IP(src=host.ip4, dst=dst_ip_if.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
size = packet_sizes[(i // 2) % len(packet_sizes)]
@@ -162,8 +165,8 @@ class TestIpIrb(VppTestCase):
self.assertEqual(payload_info.dst, dst_ip_sw_if_index)
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_ip_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_ip_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
saved_packet = next_info.data
@@ -199,8 +202,8 @@ class TestIpIrb(VppTestCase):
self.assertEqual(payload_info.dst, dst_ip_sw_if_index)
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_ip_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_ip_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
self.assertEqual(packet_index, next_info.index)
@@ -221,7 +224,7 @@ class TestIpIrb(VppTestCase):
self.assertEqual(udp.dport, saved_packet[UDP].dport)
def test_ip4_irb_1(self):
- """ IPv4 IRB test 1
+ """IPv4 IRB test 1
Test scenario:
- ip traffic from pg2 interface must ends in both pg0 and pg1
@@ -229,8 +232,7 @@ class TestIpIrb(VppTestCase):
- no l2 entry configured, pg0 and pg1 are same
"""
- stream = self.create_stream(
- self.pg2, self.bvi0, self.pg_if_packet_sizes)
+ stream = self.create_stream(self.pg2, self.bvi0, self.pg_if_packet_sizes)
self.pg2.add_stream(stream)
self.pg_enable_capture(self.pg_interfaces)
@@ -248,9 +250,11 @@ class TestIpIrb(VppTestCase):
def send_and_verify_l2_to_ip(self):
stream1 = self.create_stream_l2_to_ip(
- self.pg0, self.bvi0, self.pg2, self.pg_if_packet_sizes)
+ self.pg0, self.bvi0, self.pg2, self.pg_if_packet_sizes
+ )
stream2 = self.create_stream_l2_to_ip(
- self.pg1, self.bvi0, self.pg2, self.pg_if_packet_sizes)
+ self.pg1, self.bvi0, self.pg2, self.pg_if_packet_sizes
+ )
self.vapi.cli("clear trace")
self.pg0.add_stream(stream1)
self.pg1.add_stream(stream2)
@@ -262,7 +266,7 @@ class TestIpIrb(VppTestCase):
self.verify_capture_l2_to_ip(self.pg2, self.bvi0, rcvd)
def test_ip4_irb_2(self):
- """ IPv4 IRB test 2
+ """IPv4 IRB test 2
Test scenario:
- ip traffic from pg0 and pg1 ends on pg2
@@ -277,5 +281,5 @@ class TestIpIrb(VppTestCase):
self.pg1.assert_nothing_captured(remark="UU Flood")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ip4_vrf_multi_instance.py b/test/test_ip4_vrf_multi_instance.py
index acef6c4ff09..48c04f70e96 100644
--- a/test/test_ip4_vrf_multi_instance.py
+++ b/test/test_ip4_vrf_multi_instance.py
@@ -77,14 +77,14 @@ from vrf import VRFState
def is_ipv4_misc(p):
- """ Is packet one of uninteresting IPv4 broadcasts? """
+ """Is packet one of uninteresting IPv4 broadcasts?"""
if p.haslayer(ARP):
return True
return False
class TestIp4VrfMultiInst(VppTestCase):
- """ IP4 VRF Multi-instance Test Case """
+ """IP4 VRF Multi-instance Test Case"""
@classmethod
def setUpClass(cls):
@@ -102,8 +102,7 @@ class TestIp4VrfMultiInst(VppTestCase):
try:
# Create pg interfaces
- cls.create_pg_interfaces(
- range(cls.nr_of_vrfs * cls.pg_ifs_per_vrf))
+ cls.create_pg_interfaces(range(cls.nr_of_vrfs * cls.pg_ifs_per_vrf))
# Packet flows mapping pg0 -> pg1, pg2 etc.
cls.flows = dict()
@@ -112,7 +111,8 @@ class TestIp4VrfMultiInst(VppTestCase):
pg_list = [
cls.pg_interfaces[multiplicand * cls.pg_ifs_per_vrf + j]
for j in range(cls.pg_ifs_per_vrf)
- if (multiplicand * cls.pg_ifs_per_vrf + j) != i]
+ if (multiplicand * cls.pg_ifs_per_vrf + j) != i
+ ]
cls.flows[cls.pg_interfaces[i]] = pg_list
# Packet sizes - jumbo packet (9018 bytes) skipped
@@ -141,7 +141,8 @@ class TestIp4VrfMultiInst(VppTestCase):
set_id = i + 1
pg_list = [
cls.pg_interfaces[i * cls.pg_ifs_per_vrf + j]
- for j in range(cls.pg_ifs_per_vrf)]
+ for j in range(cls.pg_ifs_per_vrf)
+ ]
cls.pg_if_sets[set_id] = pg_list
except Exception:
@@ -173,8 +174,9 @@ class TestIp4VrfMultiInst(VppTestCase):
for i in range(self.pg_ifs_per_vrf):
pg_if = self.pg_if_sets[if_set_id][i]
pg_if.set_table_ip4(vrf_id)
- self.logger.info("pg-interface %s added to IPv4 VRF ID %d"
- % (pg_if.name, vrf_id))
+ self.logger.info(
+ "pg-interface %s added to IPv4 VRF ID %d" % (pg_if.name, vrf_id)
+ )
if pg_if not in self.pg_in_vrf:
self.pg_in_vrf.append(pg_if)
if pg_if in self.pg_not_in_vrf:
@@ -194,7 +196,7 @@ class TestIp4VrfMultiInst(VppTestCase):
for i in range(count):
vrf_id = i + start
- self.vapi.ip_table_add_del(is_add=1, table={'table_id': vrf_id})
+ self.vapi.ip_table_add_del(is_add=1, table={"table_id": vrf_id})
self.logger.info("IPv4 VRF ID %d created" % vrf_id)
if vrf_id not in self.vrf_list:
self.vrf_list.append(vrf_id)
@@ -204,8 +206,7 @@ class TestIp4VrfMultiInst(VppTestCase):
self.logger.debug(self.vapi.ppcli("show ip fib"))
self.logger.debug(self.vapi.ppcli("show ip4 neighbors"))
- def create_vrf_by_id_and_assign_interfaces(self, set_id,
- vrf_id=0xffffffff):
+ def create_vrf_by_id_and_assign_interfaces(self, set_id, vrf_id=0xFFFFFFFF):
"""
Create a FIB table / VRF by vrf_id, put 3 pg-ip4 interfaces
to FIB table / VRF.
@@ -213,7 +214,7 @@ class TestIp4VrfMultiInst(VppTestCase):
:param int vrf_id: Required table ID / VRF ID. \
(Default value = 0xffffffff, ID will be selected automatically)
"""
- ret = self.vapi.ip_table_allocate(table={'table_id': vrf_id})
+ ret = self.vapi.ip_table_allocate(table={"table_id": vrf_id})
vrf_id = ret.table.table_id
self.logger.info("IPv4 VRF ID %d created" % vrf_id)
if vrf_id not in self.vrf_list:
@@ -234,7 +235,7 @@ class TestIp4VrfMultiInst(VppTestCase):
"""
if if_set_id is None:
if_set_id = vrf_id
- self.vapi.ip_table_flush(table={'table_id': vrf_id})
+ self.vapi.ip_table_flush(table={"table_id": vrf_id})
if vrf_id in self.vrf_list:
self.vrf_list.remove(vrf_id)
if vrf_id not in self.vrf_reset_list:
@@ -249,7 +250,7 @@ class TestIp4VrfMultiInst(VppTestCase):
self.logger.info("IPv4 VRF ID %d reset finished" % vrf_id)
self.logger.debug(self.vapi.ppcli("show ip fib"))
self.logger.debug(self.vapi.ppcli("show ip neighbors"))
- self.vapi.ip_table_add_del(is_add=0, table={'table_id': vrf_id})
+ self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id})
def create_stream(self, src_if, packet_sizes):
"""
@@ -266,16 +267,20 @@ class TestIp4VrfMultiInst(VppTestCase):
src_host = random.choice(src_hosts)
pkt_info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(pkt_info)
- p = (Ether(dst=src_if.local_mac, src=src_host.mac) /
- IP(src=src_host.ip4, dst=dst_host.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_host.mac)
+ / IP(src=src_host.ip4, dst=dst_host.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
pkt_info.data = p.copy()
size = random.choice(packet_sizes)
self.extend_packet(p, size)
pkts.append(p)
- self.logger.debug("Input stream created for port %s. Length: %u pkt(s)"
- % (src_if.name, len(pkts)))
+ self.logger.debug(
+ "Input stream created for port %s. Length: %u pkt(s)"
+ % (src_if.name, len(pkts))
+ )
return pkts
def create_stream_crosswise_vrf(self, src_if, vrf_id, packet_sizes):
@@ -298,16 +303,20 @@ class TestIp4VrfMultiInst(VppTestCase):
src_host = random.choice(src_hosts)
pkt_info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(pkt_info)
- p = (Ether(dst=src_if.local_mac, src=src_host.mac) /
- IP(src=src_host.ip4, dst=dst_host.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_host.mac)
+ / IP(src=src_host.ip4, dst=dst_host.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
pkt_info.data = p.copy()
size = random.choice(packet_sizes)
self.extend_packet(p, size)
pkts.append(p)
- self.logger.debug("Input stream created for port %s. Length: %u pkt(s)"
- % (src_if.name, len(pkts)))
+ self.logger.debug(
+ "Input stream created for port %s. Length: %u pkt(s)"
+ % (src_if.name, len(pkts))
+ )
return pkts
def verify_capture(self, pg_if, capture):
@@ -328,11 +337,13 @@ class TestIp4VrfMultiInst(VppTestCase):
payload_info = self.payload_to_info(packet[Raw])
packet_index = payload_info.index
self.assertEqual(payload_info.dst, dst_sw_if_index)
- self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
- (pg_if.name, payload_info.src, packet_index))
+ self.logger.debug(
+ "Got packet on port %s: src=%u (id=%u)"
+ % (pg_if.name, payload_info.src, packet_index)
+ )
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertIsNotNone(next_info)
self.assertEqual(packet_index, next_info.index)
@@ -347,11 +358,13 @@ class TestIp4VrfMultiInst(VppTestCase):
raise
for i in self.pg_interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i, dst_sw_if_index, last_info[i.sw_if_index])
+ i, dst_sw_if_index, last_info[i.sw_if_index]
+ )
self.assertIsNone(
remaining_packet,
- "Port %u: Packet expected from source %u didn't arrive" %
- (dst_sw_if_index, i.sw_if_index))
+ "Port %u: Packet expected from source %u didn't arrive"
+ % (dst_sw_if_index, i.sw_if_index),
+ )
def verify_vrf(self, vrf_id, if_set_id=None):
"""
@@ -415,8 +428,9 @@ class TestIp4VrfMultiInst(VppTestCase):
capture = pg_if.get_capture(remark="interface is in VRF")
self.verify_capture(pg_if, capture)
elif pg_if in self.pg_not_in_vrf:
- pg_if.assert_nothing_captured(remark="interface is not in VRF",
- filter_out_fn=is_ipv4_misc)
+ pg_if.assert_nothing_captured(
+ remark="interface is not in VRF", filter_out_fn=is_ipv4_misc
+ )
self.logger.debug("No capture for interface %s" % pg_if.name)
else:
raise Exception("Unknown interface: %s" % pg_if.name)
@@ -436,7 +450,8 @@ class TestIp4VrfMultiInst(VppTestCase):
for vrf_id in self.vrf_list:
for pg_if in self.pg_if_sets[vrf_id]:
pkts = self.create_stream_crosswise_vrf(
- pg_if, vrf_id, self.pg_if_packet_sizes)
+ pg_if, vrf_id, self.pg_if_packet_sizes
+ )
pg_if.add_stream(pkts)
# Enable packet capture and start packet sending
@@ -446,29 +461,27 @@ class TestIp4VrfMultiInst(VppTestCase):
# Verify
# Verify outgoing packet streams per packet-generator interface
for pg_if in self.pg_interfaces:
- pg_if.assert_nothing_captured(remark="interface is in other VRF",
- filter_out_fn=is_ipv4_misc)
+ pg_if.assert_nothing_captured(
+ remark="interface is in other VRF", filter_out_fn=is_ipv4_misc
+ )
self.logger.debug("No capture for interface %s" % pg_if.name)
def test_ip4_vrf_01(self):
- """ IP4 VRF Multi-instance test 1 - create 4 VRFs
- """
+ """IP4 VRF Multi-instance test 1 - create 4 VRFs"""
# Config 1
# Create 4 VRFs
self.create_vrf_and_assign_interfaces(4)
# Verify 1
for vrf_id in self.vrf_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.configured, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState)
# Test 1
self.run_verify_test()
self.run_crosswise_vrf_test()
def test_ip4_vrf_02(self):
- """ IP4 VRF Multi-instance test 2 - reset 2 VRFs
- """
+ """IP4 VRF Multi-instance test 2 - reset 2 VRFs"""
# Config 2
# Reset 2 VRFs
self.reset_vrf_and_remove_from_vrf_list(1)
@@ -476,19 +489,16 @@ class TestIp4VrfMultiInst(VppTestCase):
# Verify 2
for vrf_id in self.vrf_reset_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.reset, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState)
for vrf_id in self.vrf_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.configured, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState)
# Test 2
self.run_verify_test()
self.run_crosswise_vrf_test()
def test_ip4_vrf_03(self):
- """ IP4 VRF Multi-instance 3 - add 2 VRFs
- """
+ """IP4 VRF Multi-instance 3 - add 2 VRFs"""
# Config 3
# Add 1 of reset VRFs and 1 new VRF
self.create_vrf_and_assign_interfaces(1)
@@ -496,19 +506,16 @@ class TestIp4VrfMultiInst(VppTestCase):
# Verify 3
for vrf_id in self.vrf_reset_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.reset, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState)
for vrf_id in self.vrf_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.configured, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState)
# Test 3
self.run_verify_test()
self.run_crosswise_vrf_test()
def test_ip4_vrf_04(self):
- """ IP4 VRF Multi-instance test 4 - reset 4 VRFs
- """
+ """IP4 VRF Multi-instance test 4 - reset 4 VRFs"""
# Config 4
# Reset all VRFs (i.e. no VRF except VRF=0 configured)
for i in range(len(self.vrf_list)):
@@ -516,20 +523,20 @@ class TestIp4VrfMultiInst(VppTestCase):
# Verify 4
for vrf_id in self.vrf_reset_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.reset, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState)
vrf_list_length = len(self.vrf_list)
self.assertEqual(
- vrf_list_length, 0,
- "List of configured VRFs is not empty: %s != 0" % vrf_list_length)
+ vrf_list_length,
+ 0,
+ "List of configured VRFs is not empty: %s != 0" % vrf_list_length,
+ )
# Test 4
self.run_verify_test()
self.run_crosswise_vrf_test()
def test_ip4_vrf_05(self):
- """ IP4 VRF Multi-instance test 5 - id allocation
- """
+ """IP4 VRF Multi-instance test 5 - id allocation"""
# Config 5
# Create several VRFs
# Set vrf_id manually first
@@ -542,8 +549,9 @@ class TestIp4VrfMultiInst(VppTestCase):
# Verify 5
self.assert_equal(self.verify_vrf(1, 1), VRFState.configured, VRFState)
for i, vrf in enumerate(auto_vrf_id):
- self.assert_equal(self.verify_vrf(vrf, i+2),
- VRFState.configured, VRFState)
+ self.assert_equal(
+ self.verify_vrf(vrf, i + 2), VRFState.configured, VRFState
+ )
# Test 5
self.run_verify_test()
@@ -552,18 +560,20 @@ class TestIp4VrfMultiInst(VppTestCase):
# Reset VRFs
self.reset_vrf_and_remove_from_vrf_list(1)
for i, vrf in enumerate(auto_vrf_id):
- self.reset_vrf_and_remove_from_vrf_list(vrf, i+2)
+ self.reset_vrf_and_remove_from_vrf_list(vrf, i + 2)
# Verify 5.1
self.assert_equal(self.verify_vrf(1, 1), VRFState.reset, VRFState)
for i, vrf in enumerate(auto_vrf_id):
- self.assert_equal(self.verify_vrf(vrf, i+2),
- VRFState.reset, VRFState)
+ self.assert_equal(self.verify_vrf(vrf, i + 2), VRFState.reset, VRFState)
vrf_list_length = len(self.vrf_list)
self.assertEqual(
- vrf_list_length, 0,
- "List of configured VRFs is not empty: %s != 0" % vrf_list_length)
+ vrf_list_length,
+ 0,
+ "List of configured VRFs is not empty: %s != 0" % vrf_list_length,
+ )
+
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ip6.py b/test/test_ip6.py
index c86cb777aed..ca153dba0e6 100644
--- a/test/test_ip6.py
+++ b/test/test_ip6.py
@@ -9,26 +9,58 @@ import scapy.compat
import scapy.layers.inet6 as inet6
from scapy.layers.inet import UDP, IP
from scapy.contrib.mpls import MPLS
-from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_RS, \
- ICMPv6ND_RA, ICMPv6NDOptMTU, ICMPv6NDOptSrcLLAddr, ICMPv6NDOptPrefixInfo, \
- ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, ICMPv6DestUnreach, icmp6types, \
- ICMPv6TimeExceeded, ICMPv6EchoRequest, ICMPv6EchoReply, \
- IPv6ExtHdrHopByHop, ICMPv6MLReport2, ICMPv6MLDMultAddrRec
+from scapy.layers.inet6 import (
+ IPv6,
+ ICMPv6ND_NS,
+ ICMPv6ND_RS,
+ ICMPv6ND_RA,
+ ICMPv6NDOptMTU,
+ ICMPv6NDOptSrcLLAddr,
+ ICMPv6NDOptPrefixInfo,
+ ICMPv6ND_NA,
+ ICMPv6NDOptDstLLAddr,
+ ICMPv6DestUnreach,
+ icmp6types,
+ ICMPv6TimeExceeded,
+ ICMPv6EchoRequest,
+ ICMPv6EchoReply,
+ IPv6ExtHdrHopByHop,
+ ICMPv6MLReport2,
+ ICMPv6MLDMultAddrRec,
+)
from scapy.layers.l2 import Ether, Dot1Q, GRE
from scapy.packet import Raw
-from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ptop, in6_islladdr, \
- in6_mactoifaceid
+from scapy.utils6 import (
+ in6_getnsma,
+ in6_getnsmac,
+ in6_ptop,
+ in6_islladdr,
+ in6_mactoifaceid,
+)
from six import moves
from framework import VppTestCase, VppTestRunner, tag_run_solo
from util import ppp, ip6_normalize, mk_ll_addr
from vpp_papi import VppEnum
from vpp_ip import DpoProto, VppIpPuntPolicer, VppIpPuntRedirect, VppIpPathMtu
-from vpp_ip_route import VppIpRoute, VppRoutePath, find_route, VppIpMRoute, \
- VppMRoutePath, VppMplsIpBind, \
- VppMplsRoute, VppMplsTable, VppIpTable, FibPathType, FibPathProto, \
- VppIpInterfaceAddress, find_route_in_dump, find_mroute_in_dump, \
- VppIp6LinkLocalAddress, VppIpRouteV2
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ find_route,
+ VppIpMRoute,
+ VppMRoutePath,
+ VppMplsIpBind,
+ VppMplsRoute,
+ VppMplsTable,
+ VppIpTable,
+ FibPathType,
+ FibPathProto,
+ VppIpInterfaceAddress,
+ find_route_in_dump,
+ find_mroute_in_dump,
+ VppIp6LinkLocalAddress,
+ VppIpRouteV2,
+)
from vpp_neighbor import find_nbr, VppNeighbor
from vpp_ipip_tun_interface import VppIpIpTunInterface
from vpp_pg_interface import is_ipv6_misc
@@ -61,13 +93,11 @@ class TestIPv6ND(VppTestCase):
# the rx'd RA should be addressed to the sender's source
self.assertTrue(rx.haslayer(ICMPv6ND_RA))
- self.assertEqual(in6_ptop(rx[IPv6].dst),
- in6_ptop(dst_ip))
+ self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip))
# and come from the router's link local
self.assertTrue(in6_islladdr(rx[IPv6].src))
- self.assertEqual(in6_ptop(rx[IPv6].src),
- in6_ptop(mk_ll_addr(intf.local_mac)))
+ self.assertEqual(in6_ptop(rx[IPv6].src), in6_ptop(mk_ll_addr(intf.local_mac)))
def validate_na(self, intf, rx, dst_ip=None, tgt_ip=None):
if not dst_ip:
@@ -83,12 +113,10 @@ class TestIPv6ND(VppTestCase):
# the rx'd NA should be addressed to the sender's source
self.assertTrue(rx.haslayer(ICMPv6ND_NA))
- self.assertEqual(in6_ptop(rx[IPv6].dst),
- in6_ptop(dst_ip))
+ self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip))
# and come from the target address
- self.assertEqual(
- in6_ptop(rx[IPv6].src), in6_ptop(tgt_ip))
+ self.assertEqual(in6_ptop(rx[IPv6].src), in6_ptop(tgt_ip))
# Dest link-layer options should have the router's MAC
dll = rx[ICMPv6NDOptDstLLAddr]
@@ -106,23 +134,22 @@ class TestIPv6ND(VppTestCase):
# the rx'd NS should be addressed to an mcast address
# derived from the target address
- self.assertEqual(
- in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip))
+ self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip))
# expect the tgt IP in the NS header
ns = rx[ICMPv6ND_NS]
self.assertEqual(in6_ptop(ns.tgt), in6_ptop(tgt_ip))
# packet is from the router's local address
- self.assertEqual(
- in6_ptop(rx[IPv6].src), intf.local_ip6)
+ self.assertEqual(in6_ptop(rx[IPv6].src), intf.local_ip6)
# Src link-layer options should have the router's MAC
sll = rx[ICMPv6NDOptSrcLLAddr]
self.assertEqual(sll.lladdr, intf.local_mac)
- def send_and_expect_ra(self, intf, pkts, remark, dst_ip=None,
- filter_out_fn=is_ipv6_misc):
+ def send_and_expect_ra(
+ self, intf, pkts, remark, dst_ip=None, filter_out_fn=is_ipv6_misc
+ ):
intf.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -132,9 +159,9 @@ class TestIPv6ND(VppTestCase):
rx = rx[0]
self.validate_ra(intf, rx, dst_ip)
- def send_and_expect_na(self, intf, pkts, remark, dst_ip=None,
- tgt_ip=None,
- filter_out_fn=is_ipv6_misc):
+ def send_and_expect_na(
+ self, intf, pkts, remark, dst_ip=None, tgt_ip=None, filter_out_fn=is_ipv6_misc
+ ):
intf.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -144,8 +171,9 @@ class TestIPv6ND(VppTestCase):
rx = rx[0]
self.validate_na(intf, rx, dst_ip, tgt_ip)
- def send_and_expect_ns(self, tx_intf, rx_intf, pkts, tgt_ip,
- filter_out_fn=is_ipv6_misc):
+ def send_and_expect_ns(
+ self, tx_intf, rx_intf, pkts, tgt_ip, filter_out_fn=is_ipv6_misc
+ ):
self.vapi.cli("clear trace")
tx_intf.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -168,7 +196,7 @@ class TestIPv6ND(VppTestCase):
@tag_run_solo
class TestIPv6(TestIPv6ND):
- """ IPv6 Test Case """
+ """IPv6 Test Case"""
@classmethod
def setUpClass(cls):
@@ -268,17 +296,26 @@ class TestIPv6(TestIPv6ND):
:param VppInterface src_if: Interface to create packet stream for.
"""
hdr_ext = 4 if isinstance(src_if, VppSubInterface) else 0
- pkt_tmpl = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IPv6(src=src_if.remote_ip6) /
- inet6.UDP(sport=1234, dport=1234))
-
- pkts = [self.modify_packet(src_if, i, pkt_tmpl)
- for i in moves.range(self.pg_if_packet_sizes[0],
- self.pg_if_packet_sizes[1], 10)]
- pkts_b = [self.modify_packet(src_if, i, pkt_tmpl)
- for i in moves.range(self.pg_if_packet_sizes[1] + hdr_ext,
- self.pg_if_packet_sizes[2] + hdr_ext,
- 50)]
+ pkt_tmpl = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IPv6(src=src_if.remote_ip6)
+ / inet6.UDP(sport=1234, dport=1234)
+ )
+
+ pkts = [
+ self.modify_packet(src_if, i, pkt_tmpl)
+ for i in moves.range(
+ self.pg_if_packet_sizes[0], self.pg_if_packet_sizes[1], 10
+ )
+ ]
+ pkts_b = [
+ self.modify_packet(src_if, i, pkt_tmpl)
+ for i in moves.range(
+ self.pg_if_packet_sizes[1] + hdr_ext,
+ self.pg_if_packet_sizes[2] + hdr_ext,
+ 50,
+ )
+ ]
pkts.extend(pkts_b)
return pkts
@@ -296,7 +333,7 @@ class TestIPv6(TestIPv6ND):
last_info[i.sw_if_index] = None
is_sub_if = False
dst_sw_if_index = dst_if.sw_if_index
- if hasattr(dst_if, 'parent'):
+ if hasattr(dst_if, "parent"):
is_sub_if = True
for packet in capture:
if is_sub_if:
@@ -310,45 +347,47 @@ class TestIPv6(TestIPv6ND):
packet_index = payload_info.index
self.assertEqual(payload_info.dst, dst_sw_if_index)
self.logger.debug(
- "Got packet on port %s: src=%u (id=%u)" %
- (dst_if.name, payload_info.src, packet_index))
+ "Got packet on port %s: src=%u (id=%u)"
+ % (dst_if.name, payload_info.src, packet_index)
+ )
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
self.assertEqual(packet_index, next_info.index)
saved_packet = next_info.data
# Check standard fields
- self.assertEqual(
- ip.src, saved_packet[IPv6].src)
- self.assertEqual(
- ip.dst, saved_packet[IPv6].dst)
- self.assertEqual(
- udp.sport, saved_packet[inet6.UDP].sport)
- self.assertEqual(
- udp.dport, saved_packet[inet6.UDP].dport)
+ self.assertEqual(ip.src, saved_packet[IPv6].src)
+ self.assertEqual(ip.dst, saved_packet[IPv6].dst)
+ self.assertEqual(udp.sport, saved_packet[inet6.UDP].sport)
+ self.assertEqual(udp.dport, saved_packet[inet6.UDP].dport)
except:
self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
for i in self.interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index])
- self.assertTrue(remaining_packet is None,
- "Interface %s: Packet expected from interface %s "
- "didn't arrive" % (dst_if.name, i.name))
+ i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]
+ )
+ self.assertTrue(
+ remaining_packet is None,
+ "Interface %s: Packet expected from interface %s "
+ "didn't arrive" % (dst_if.name, i.name),
+ )
def test_next_header_anomaly(self):
- """ IPv6 next header anomaly test
+ """IPv6 next header anomaly test
Test scenario:
- ipv6 next header field = Fragment Header (44)
- next header is ICMPv6 Echo Request
- wait for reassembly
"""
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44) /
- ICMPv6EchoRequest())
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44)
+ / ICMPv6EchoRequest()
+ )
self.pg0.add_stream(pkt)
self.pg_start()
@@ -357,7 +396,7 @@ class TestIPv6(TestIPv6ND):
self.sleep(10)
def test_fib(self):
- """ IPv6 FIB test
+ """IPv6 FIB test
Test scenario:
- Create IPv6 stream for pg0 interface
@@ -383,7 +422,7 @@ class TestIPv6(TestIPv6ND):
self.verify_capture(i, pkts)
def test_ns(self):
- """ IPv6 Neighbour Solicitation Exceptions
+ """IPv6 Neighbour Solicitation Exceptions
Test scenario:
- Send an NS Sourced from an address not covered by the link sub-net
@@ -397,16 +436,17 @@ class TestIPv6(TestIPv6ND):
nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6))
d = inet_ntop(AF_INET6, nsma)
- p = (Ether(dst=in6_getnsmac(nsma)) /
- IPv6(dst=d, src="2002::2") /
- ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
- ICMPv6NDOptSrcLLAddr(
- lladdr=self.pg0.remote_mac))
+ p = (
+ Ether(dst=in6_getnsmac(nsma))
+ / IPv6(dst=d, src="2002::2")
+ / ICMPv6ND_NS(tgt=self.pg0.local_ip6)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac)
+ )
pkts = [p]
self.send_and_assert_no_replies(
- self.pg0, pkts,
- "No response to NS source by address not on sub-net")
+ self.pg0, pkts, "No response to NS source by address not on sub-net"
+ )
#
# An NS for sent to a solicited mcast group the router is
@@ -416,16 +456,17 @@ class TestIPv6(TestIPv6ND):
nsma = in6_getnsma(inet_pton(AF_INET6, "fd::ffff"))
d = inet_ntop(AF_INET6, nsma)
- p = (Ether(dst=in6_getnsmac(nsma)) /
- IPv6(dst=d, src=self.pg0.remote_ip6) /
- ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
- ICMPv6NDOptSrcLLAddr(
- lladdr=self.pg0.remote_mac))
+ p = (
+ Ether(dst=in6_getnsmac(nsma))
+ / IPv6(dst=d, src=self.pg0.remote_ip6)
+ / ICMPv6ND_NS(tgt=self.pg0.local_ip6)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac)
+ )
pkts = [p]
self.send_and_assert_no_replies(
- self.pg0, pkts,
- "No response to NS sent to unjoined mcast address")
+ self.pg0, pkts, "No response to NS sent to unjoined mcast address"
+ )
#
# An NS whose target address is one the router does not own
@@ -433,88 +474,94 @@ class TestIPv6(TestIPv6ND):
nsma = in6_getnsma(inet_pton(AF_INET6, self.pg0.local_ip6))
d = inet_ntop(AF_INET6, nsma)
- p = (Ether(dst=in6_getnsmac(nsma)) /
- IPv6(dst=d, src=self.pg0.remote_ip6) /
- ICMPv6ND_NS(tgt="fd::ffff") /
- ICMPv6NDOptSrcLLAddr(
- lladdr=self.pg0.remote_mac))
+ p = (
+ Ether(dst=in6_getnsmac(nsma))
+ / IPv6(dst=d, src=self.pg0.remote_ip6)
+ / ICMPv6ND_NS(tgt="fd::ffff")
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac)
+ )
pkts = [p]
- self.send_and_assert_no_replies(self.pg0, pkts,
- "No response to NS for unknown target")
+ self.send_and_assert_no_replies(
+ self.pg0, pkts, "No response to NS for unknown target"
+ )
#
# A neighbor entry that has no associated FIB-entry
#
self.pg0.generate_remote_hosts(4)
- nd_entry = VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[2].mac,
- self.pg0.remote_hosts[2].ip6,
- is_no_fib_entry=1)
+ nd_entry = VppNeighbor(
+ self,
+ self.pg0.sw_if_index,
+ self.pg0.remote_hosts[2].mac,
+ self.pg0.remote_hosts[2].ip6,
+ is_no_fib_entry=1,
+ )
nd_entry.add_vpp_config()
#
# check we have the neighbor, but no route
#
- self.assertTrue(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0._remote_hosts[2].ip6))
- self.assertFalse(find_route(self,
- self.pg0._remote_hosts[2].ip6,
- 128))
+ self.assertTrue(
+ find_nbr(self, self.pg0.sw_if_index, self.pg0._remote_hosts[2].ip6)
+ )
+ self.assertFalse(find_route(self, self.pg0._remote_hosts[2].ip6, 128))
#
# send an NS from a link local address to the interface's global
# address
#
- p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
- IPv6(
- dst=d, src=self.pg0._remote_hosts[2].ip6_ll) /
- ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
- ICMPv6NDOptSrcLLAddr(
- lladdr=self.pg0.remote_mac))
+ p = (
+ Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac)
+ / IPv6(dst=d, src=self.pg0._remote_hosts[2].ip6_ll)
+ / ICMPv6ND_NS(tgt=self.pg0.local_ip6)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac)
+ )
- self.send_and_expect_na(self.pg0, p,
- "NS from link-local",
- dst_ip=self.pg0._remote_hosts[2].ip6_ll,
- tgt_ip=self.pg0.local_ip6)
+ self.send_and_expect_na(
+ self.pg0,
+ p,
+ "NS from link-local",
+ dst_ip=self.pg0._remote_hosts[2].ip6_ll,
+ tgt_ip=self.pg0.local_ip6,
+ )
#
# we should have learned an ND entry for the peer's link-local
# but not inserted a route to it in the FIB
#
- self.assertTrue(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0._remote_hosts[2].ip6_ll))
- self.assertFalse(find_route(self,
- self.pg0._remote_hosts[2].ip6_ll,
- 128))
+ self.assertTrue(
+ find_nbr(self, self.pg0.sw_if_index, self.pg0._remote_hosts[2].ip6_ll)
+ )
+ self.assertFalse(find_route(self, self.pg0._remote_hosts[2].ip6_ll, 128))
#
# An NS to the router's own Link-local
#
- p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
- IPv6(
- dst=d, src=self.pg0._remote_hosts[3].ip6_ll) /
- ICMPv6ND_NS(tgt=self.pg0.local_ip6_ll) /
- ICMPv6NDOptSrcLLAddr(
- lladdr=self.pg0.remote_mac))
+ p = (
+ Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac)
+ / IPv6(dst=d, src=self.pg0._remote_hosts[3].ip6_ll)
+ / ICMPv6ND_NS(tgt=self.pg0.local_ip6_ll)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac)
+ )
- self.send_and_expect_na(self.pg0, p,
- "NS to/from link-local",
- dst_ip=self.pg0._remote_hosts[3].ip6_ll,
- tgt_ip=self.pg0.local_ip6_ll)
+ self.send_and_expect_na(
+ self.pg0,
+ p,
+ "NS to/from link-local",
+ dst_ip=self.pg0._remote_hosts[3].ip6_ll,
+ tgt_ip=self.pg0.local_ip6_ll,
+ )
#
# do not respond to a NS for the peer's address
#
- p = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
- IPv6(dst=d,
- src=self.pg0._remote_hosts[3].ip6_ll) /
- ICMPv6ND_NS(tgt=self.pg0._remote_hosts[3].ip6_ll) /
- ICMPv6NDOptSrcLLAddr(
- lladdr=self.pg0.remote_mac))
+ p = (
+ Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac)
+ / IPv6(dst=d, src=self.pg0._remote_hosts[3].ip6_ll)
+ / ICMPv6ND_NS(tgt=self.pg0._remote_hosts[3].ip6_ll)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac)
+ )
self.send_and_assert_no_replies(self.pg0, p)
@@ -522,15 +569,13 @@ class TestIPv6(TestIPv6ND):
# we should have learned an ND entry for the peer's link-local
# but not inserted a route to it in the FIB
#
- self.assertTrue(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0._remote_hosts[3].ip6_ll))
- self.assertFalse(find_route(self,
- self.pg0._remote_hosts[3].ip6_ll,
- 128))
+ self.assertTrue(
+ find_nbr(self, self.pg0.sw_if_index, self.pg0._remote_hosts[3].ip6_ll)
+ )
+ self.assertFalse(find_route(self, self.pg0._remote_hosts[3].ip6_ll, 128))
def test_ns_duplicates(self):
- """ ND Duplicates"""
+ """ND Duplicates"""
#
# Generate some hosts on the LAN
@@ -540,26 +585,30 @@ class TestIPv6(TestIPv6ND):
#
# Add host 1 on pg1 and pg2
#
- ns_pg1 = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[1].mac,
- self.pg1.remote_hosts[1].ip6)
+ ns_pg1 = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[1].mac,
+ self.pg1.remote_hosts[1].ip6,
+ )
ns_pg1.add_vpp_config()
- ns_pg2 = VppNeighbor(self,
- self.pg2.sw_if_index,
- self.pg2.remote_mac,
- self.pg1.remote_hosts[1].ip6)
+ ns_pg2 = VppNeighbor(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_mac,
+ self.pg1.remote_hosts[1].ip6,
+ )
ns_pg2.add_vpp_config()
#
# IP packet destined for pg1 remote host arrives on pg1 again.
#
- p = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=self.pg1.remote_hosts[1].ip6) /
- inet6.UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_hosts[1].ip6)
+ / inet6.UDP(sport=1234, dport=1234)
+ / Raw()
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
@@ -567,11 +616,13 @@ class TestIPv6(TestIPv6ND):
rx1 = self.pg1.get_capture(1)
- self.verify_ip(rx1[0],
- self.pg1.local_mac,
- self.pg1.remote_hosts[1].mac,
- self.pg0.remote_ip6,
- self.pg1.remote_hosts[1].ip6)
+ self.verify_ip(
+ rx1[0],
+ self.pg1.local_mac,
+ self.pg1.remote_hosts[1].mac,
+ self.pg0.remote_ip6,
+ self.pg1.remote_hosts[1].ip6,
+ )
#
# remove the duplicate on pg1
@@ -579,8 +630,7 @@ class TestIPv6(TestIPv6ND):
#
ns_pg1.remove_vpp_config()
- self.send_and_expect_ns(self.pg0, self.pg1,
- p, self.pg1.remote_hosts[1].ip6)
+ self.send_and_expect_ns(self.pg0, self.pg1, p, self.pg1.remote_hosts[1].ip6)
#
# Add it back
@@ -593,14 +643,15 @@ class TestIPv6(TestIPv6ND):
rx1 = self.pg1.get_capture(1)
- self.verify_ip(rx1[0],
- self.pg1.local_mac,
- self.pg1.remote_hosts[1].mac,
- self.pg0.remote_ip6,
- self.pg1.remote_hosts[1].ip6)
+ self.verify_ip(
+ rx1[0],
+ self.pg1.local_mac,
+ self.pg1.remote_hosts[1].mac,
+ self.pg0.remote_ip6,
+ self.pg1.remote_hosts[1].ip6,
+ )
- def validate_ra(self, intf, rx, dst_ip=None, src_ip=None,
- mtu=9000, pi_opt=None):
+ def validate_ra(self, intf, rx, dst_ip=None, src_ip=None, mtu=9000, pi_opt=None):
if not dst_ip:
dst_ip = intf.remote_ip6
if not src_ip:
@@ -614,8 +665,7 @@ class TestIPv6(TestIPv6ND):
# the rx'd RA should be addressed to the sender's source
self.assertTrue(rx.haslayer(ICMPv6ND_RA))
- self.assertEqual(in6_ptop(rx[IPv6].dst),
- in6_ptop(dst_ip))
+ self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(dst_ip))
# and come from the router's link local
self.assertTrue(in6_islladdr(rx[IPv6].src))
@@ -631,8 +681,7 @@ class TestIPv6(TestIPv6ND):
if not pi_opt:
# the RA should not contain prefix information
- self.assertFalse(ra.haslayer(
- ICMPv6NDOptPrefixInfo))
+ self.assertFalse(ra.haslayer(ICMPv6NDOptPrefixInfo))
else:
raos = rx.getlayer(ICMPv6NDOptPrefixInfo, 1)
@@ -642,24 +691,30 @@ class TestIPv6(TestIPv6ND):
# however, the getlayer(.., 2) does give one instance.
# so we cheat here and construct a new opt instance for comparison
rd = ICMPv6NDOptPrefixInfo(
- prefixlen=raos.prefixlen,
- prefix=raos.prefix,
- L=raos.L,
- A=raos.A)
+ prefixlen=raos.prefixlen, prefix=raos.prefix, L=raos.L, A=raos.A
+ )
if type(pi_opt) is list:
for ii in range(len(pi_opt)):
self.assertEqual(pi_opt[ii], rd)
- rd = rx.getlayer(
- ICMPv6NDOptPrefixInfo, ii + 2)
+ rd = rx.getlayer(ICMPv6NDOptPrefixInfo, ii + 2)
else:
- self.assertEqual(pi_opt, raos, 'Expected: %s, received: %s'
- % (pi_opt.show(dump=True),
- raos.show(dump=True)))
-
- def send_and_expect_ra(self, intf, pkts, remark, dst_ip=None,
- filter_out_fn=is_ipv6_misc,
- opt=None,
- src_ip=None):
+ self.assertEqual(
+ pi_opt,
+ raos,
+ "Expected: %s, received: %s"
+ % (pi_opt.show(dump=True), raos.show(dump=True)),
+ )
+
+ def send_and_expect_ra(
+ self,
+ intf,
+ pkts,
+ remark,
+ dst_ip=None,
+ filter_out_fn=is_ipv6_misc,
+ opt=None,
+ src_ip=None,
+ ):
self.vapi.cli("clear trace")
intf.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -671,7 +726,7 @@ class TestIPv6(TestIPv6ND):
self.validate_ra(intf, rx, dst_ip, src_ip=src_ip, pi_opt=opt)
def test_rs(self):
- """ IPv6 Router Solicitation Exceptions
+ """IPv6 Router Solicitation Exceptions
Test scenario:
"""
@@ -692,9 +747,11 @@ class TestIPv6(TestIPv6ND):
# An RS from a link source address
# - expect an RA in return
#
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) /
- ICMPv6ND_RS())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6)
+ / ICMPv6ND_RS()
+ )
pkts = [p]
self.send_and_expect_ra(self.pg0, pkts, "Genuine RS")
@@ -716,26 +773,26 @@ class TestIPv6(TestIPv6ND):
# An RS sent from a non-link local source
#
self.pg0.ip6_ra_config(send_unicast=1)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6,
- src="2002::ffff") /
- ICMPv6ND_RS())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src="2002::ffff")
+ / ICMPv6ND_RS()
+ )
pkts = [p]
- self.send_and_assert_no_replies(self.pg0, pkts,
- "RS from non-link source")
+ self.send_and_assert_no_replies(self.pg0, pkts, "RS from non-link source")
#
# Source an RS from a link local address
#
self.pg0.ip6_ra_config(send_unicast=1)
ll = mk_ll_addr(self.pg0.remote_mac)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6, src=ll) /
- ICMPv6ND_RS())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=ll)
+ / ICMPv6ND_RS()
+ )
pkts = [p]
- self.send_and_expect_ra(self.pg0, pkts,
- "RS sourced from link-local",
- dst_ip=ll)
+ self.send_and_expect_ra(self.pg0, pkts, "RS sourced from link-local", dst_ip=ll)
#
# Source an RS from a link local address
@@ -743,12 +800,13 @@ class TestIPv6(TestIPv6ND):
#
self.pg0.ip6_ra_config(send_unicast=1, suppress=1)
ll = mk_ll_addr(self.pg0.remote_mac)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6, src=ll) /
- ICMPv6ND_RS())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=ll)
+ / ICMPv6ND_RS()
+ )
pkts = [p]
- self.send_and_assert_no_replies(self.pg0, pkts,
- "Suppressed RS from link-local")
+ self.send_and_assert_no_replies(self.pg0, pkts, "Suppressed RS from link-local")
#
# Send the RS multicast
@@ -757,13 +815,13 @@ class TestIPv6(TestIPv6ND):
self.pg0.ip6_ra_config(send_unicast=1)
dmac = in6_getnsmac(inet_pton(AF_INET6, "ff02::2"))
ll = mk_ll_addr(self.pg0.remote_mac)
- p = (Ether(dst=dmac, src=self.pg0.remote_mac) /
- IPv6(dst="ff02::2", src=ll) /
- ICMPv6ND_RS())
+ p = (
+ Ether(dst=dmac, src=self.pg0.remote_mac)
+ / IPv6(dst="ff02::2", src=ll)
+ / ICMPv6ND_RS()
+ )
pkts = [p]
- self.send_and_expect_ra(self.pg0, pkts,
- "RS sourced from link-local",
- dst_ip=ll)
+ self.send_and_expect_ra(self.pg0, pkts, "RS sourced from link-local", dst_ip=ll)
#
# Source from the unspecified address ::. This happens when the RS
@@ -774,209 +832,204 @@ class TestIPv6(TestIPv6ND):
# it's not an error.
#
self.pg0.ip6_ra_config(send_unicast=1)
- p = (Ether(dst=dmac, src=self.pg0.remote_mac) /
- IPv6(dst="ff02::2", src="::") /
- ICMPv6ND_RS())
+ p = (
+ Ether(dst=dmac, src=self.pg0.remote_mac)
+ / IPv6(dst="ff02::2", src="::")
+ / ICMPv6ND_RS()
+ )
pkts = [p]
- self.send_and_expect_ra(self.pg0, pkts,
- "RS sourced from unspecified",
- dst_ip="ff02::1",
- filter_out_fn=None)
+ self.send_and_expect_ra(
+ self.pg0,
+ pkts,
+ "RS sourced from unspecified",
+ dst_ip="ff02::1",
+ filter_out_fn=None,
+ )
#
# Configure The RA to announce the links prefix
#
- self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
- self.pg0.local_ip6_prefix_len))
+ self.pg0.ip6_ra_prefix(
+ "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len)
+ )
#
# RAs should now contain the prefix information option
#
opt = ICMPv6NDOptPrefixInfo(
- prefixlen=self.pg0.local_ip6_prefix_len,
- prefix=self.pg0.local_ip6,
- L=1,
- A=1)
+ prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=1, A=1
+ )
self.pg0.ip6_ra_config(send_unicast=1)
ll = mk_ll_addr(self.pg0.remote_mac)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6, src=ll) /
- ICMPv6ND_RS())
- self.send_and_expect_ra(self.pg0, p,
- "RA with prefix-info",
- dst_ip=ll,
- opt=opt)
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=ll)
+ / ICMPv6ND_RS()
+ )
+ self.send_and_expect_ra(self.pg0, p, "RA with prefix-info", dst_ip=ll, opt=opt)
#
# Change the prefix info to not off-link
# L-flag is clear
#
- self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
- self.pg0.local_ip6_prefix_len),
- off_link=1)
+ self.pg0.ip6_ra_prefix(
+ "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len), off_link=1
+ )
opt = ICMPv6NDOptPrefixInfo(
- prefixlen=self.pg0.local_ip6_prefix_len,
- prefix=self.pg0.local_ip6,
- L=0,
- A=1)
+ prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=0, A=1
+ )
self.pg0.ip6_ra_config(send_unicast=1)
- self.send_and_expect_ra(self.pg0, p,
- "RA with Prefix info with L-flag=0",
- dst_ip=ll,
- opt=opt)
+ self.send_and_expect_ra(
+ self.pg0, p, "RA with Prefix info with L-flag=0", dst_ip=ll, opt=opt
+ )
#
# Change the prefix info to not off-link, no-autoconfig
# L and A flag are clear in the advert
#
- self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
- self.pg0.local_ip6_prefix_len),
- off_link=1,
- no_autoconfig=1)
+ self.pg0.ip6_ra_prefix(
+ "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len),
+ off_link=1,
+ no_autoconfig=1,
+ )
opt = ICMPv6NDOptPrefixInfo(
- prefixlen=self.pg0.local_ip6_prefix_len,
- prefix=self.pg0.local_ip6,
- L=0,
- A=0)
+ prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=0, A=0
+ )
self.pg0.ip6_ra_config(send_unicast=1)
- self.send_and_expect_ra(self.pg0, p,
- "RA with Prefix info with A & L-flag=0",
- dst_ip=ll,
- opt=opt)
+ self.send_and_expect_ra(
+ self.pg0, p, "RA with Prefix info with A & L-flag=0", dst_ip=ll, opt=opt
+ )
#
# Change the flag settings back to the defaults
# L and A flag are set in the advert
#
- self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
- self.pg0.local_ip6_prefix_len))
+ self.pg0.ip6_ra_prefix(
+ "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len)
+ )
opt = ICMPv6NDOptPrefixInfo(
- prefixlen=self.pg0.local_ip6_prefix_len,
- prefix=self.pg0.local_ip6,
- L=1,
- A=1)
+ prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=1, A=1
+ )
self.pg0.ip6_ra_config(send_unicast=1)
- self.send_and_expect_ra(self.pg0, p,
- "RA with Prefix info",
- dst_ip=ll,
- opt=opt)
+ self.send_and_expect_ra(self.pg0, p, "RA with Prefix info", dst_ip=ll, opt=opt)
#
# Change the prefix info to not off-link, no-autoconfig
# L and A flag are clear in the advert
#
- self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
- self.pg0.local_ip6_prefix_len),
- off_link=1,
- no_autoconfig=1)
+ self.pg0.ip6_ra_prefix(
+ "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len),
+ off_link=1,
+ no_autoconfig=1,
+ )
opt = ICMPv6NDOptPrefixInfo(
- prefixlen=self.pg0.local_ip6_prefix_len,
- prefix=self.pg0.local_ip6,
- L=0,
- A=0)
+ prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=0, A=0
+ )
self.pg0.ip6_ra_config(send_unicast=1)
- self.send_and_expect_ra(self.pg0, p,
- "RA with Prefix info with A & L-flag=0",
- dst_ip=ll,
- opt=opt)
+ self.send_and_expect_ra(
+ self.pg0, p, "RA with Prefix info with A & L-flag=0", dst_ip=ll, opt=opt
+ )
#
# Use the reset to defaults option to revert to defaults
# L and A flag are clear in the advert
#
- self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
- self.pg0.local_ip6_prefix_len),
- use_default=1)
+ self.pg0.ip6_ra_prefix(
+ "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len), use_default=1
+ )
opt = ICMPv6NDOptPrefixInfo(
- prefixlen=self.pg0.local_ip6_prefix_len,
- prefix=self.pg0.local_ip6,
- L=1,
- A=1)
+ prefixlen=self.pg0.local_ip6_prefix_len, prefix=self.pg0.local_ip6, L=1, A=1
+ )
self.pg0.ip6_ra_config(send_unicast=1)
- self.send_and_expect_ra(self.pg0, p,
- "RA with Prefix reverted to defaults",
- dst_ip=ll,
- opt=opt)
+ self.send_and_expect_ra(
+ self.pg0, p, "RA with Prefix reverted to defaults", dst_ip=ll, opt=opt
+ )
#
# Advertise Another prefix. With no L-flag/A-flag
#
- self.pg0.ip6_ra_prefix('%s/%s' % (self.pg1.local_ip6,
- self.pg1.local_ip6_prefix_len),
- off_link=1,
- no_autoconfig=1)
+ self.pg0.ip6_ra_prefix(
+ "%s/%s" % (self.pg1.local_ip6, self.pg1.local_ip6_prefix_len),
+ off_link=1,
+ no_autoconfig=1,
+ )
- opt = [ICMPv6NDOptPrefixInfo(
- prefixlen=self.pg0.local_ip6_prefix_len,
- prefix=self.pg0.local_ip6,
- L=1,
- A=1),
+ opt = [
+ ICMPv6NDOptPrefixInfo(
+ prefixlen=self.pg0.local_ip6_prefix_len,
+ prefix=self.pg0.local_ip6,
+ L=1,
+ A=1,
+ ),
ICMPv6NDOptPrefixInfo(
prefixlen=self.pg1.local_ip6_prefix_len,
prefix=self.pg1.local_ip6,
L=0,
- A=0)]
+ A=0,
+ ),
+ ]
self.pg0.ip6_ra_config(send_unicast=1)
ll = mk_ll_addr(self.pg0.remote_mac)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0.local_ip6, src=ll) /
- ICMPv6ND_RS())
- self.send_and_expect_ra(self.pg0, p,
- "RA with multiple Prefix infos",
- dst_ip=ll,
- opt=opt)
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=ll)
+ / ICMPv6ND_RS()
+ )
+ self.send_and_expect_ra(
+ self.pg0, p, "RA with multiple Prefix infos", dst_ip=ll, opt=opt
+ )
#
# Remove the first prefix-info - expect the second is still in the
# advert
#
- self.pg0.ip6_ra_prefix('%s/%s' % (self.pg0.local_ip6,
- self.pg0.local_ip6_prefix_len),
- is_no=1)
+ self.pg0.ip6_ra_prefix(
+ "%s/%s" % (self.pg0.local_ip6, self.pg0.local_ip6_prefix_len), is_no=1
+ )
opt = ICMPv6NDOptPrefixInfo(
- prefixlen=self.pg1.local_ip6_prefix_len,
- prefix=self.pg1.local_ip6,
- L=0,
- A=0)
+ prefixlen=self.pg1.local_ip6_prefix_len, prefix=self.pg1.local_ip6, L=0, A=0
+ )
self.pg0.ip6_ra_config(send_unicast=1)
- self.send_and_expect_ra(self.pg0, p,
- "RA with Prefix reverted to defaults",
- dst_ip=ll,
- opt=opt)
+ self.send_and_expect_ra(
+ self.pg0, p, "RA with Prefix reverted to defaults", dst_ip=ll, opt=opt
+ )
#
# Remove the second prefix-info - expect no prefix-info in the adverts
#
- self.pg0.ip6_ra_prefix('%s/%s' % (self.pg1.local_ip6,
- self.pg1.local_ip6_prefix_len),
- is_no=1)
+ self.pg0.ip6_ra_prefix(
+ "%s/%s" % (self.pg1.local_ip6, self.pg1.local_ip6_prefix_len), is_no=1
+ )
#
# change the link's link local, so we know that works too.
#
self.vapi.sw_interface_ip6_set_link_local_address(
- sw_if_index=self.pg0.sw_if_index,
- ip="fe80::88")
+ sw_if_index=self.pg0.sw_if_index, ip="fe80::88"
+ )
self.pg0.ip6_ra_config(send_unicast=1)
- self.send_and_expect_ra(self.pg0, p,
- "RA with Prefix reverted to defaults",
- dst_ip=ll,
- src_ip="fe80::88")
+ self.send_and_expect_ra(
+ self.pg0,
+ p,
+ "RA with Prefix reverted to defaults",
+ dst_ip=ll,
+ src_ip="fe80::88",
+ )
#
# Reset the periodic advertisements back to default values
@@ -985,7 +1038,7 @@ class TestIPv6(TestIPv6ND):
self.pg0.ip6_ra_config(no=1, send_unicast=1)
def test_mld(self):
- """ MLD Report """
+ """MLD Report"""
#
# test one MLD is sent after applying an IPv6 Address on an interface
#
@@ -1006,25 +1059,30 @@ class TestIPv6(TestIPv6ND):
# make sure ipv6 packets with hop by hop options have
# correct checksums
self.assert_packet_checksums_valid(rx)
- if rx.haslayer(IPv6ExtHdrHopByHop) and \
- rx.haslayer(Dot1Q) and \
- rx[Dot1Q].vlan == 99:
+ if (
+ rx.haslayer(IPv6ExtHdrHopByHop)
+ and rx.haslayer(Dot1Q)
+ and rx[Dot1Q].vlan == 99
+ ):
mld = rx[ICMPv6MLReport2]
self.assertEqual(mld.records_number, 4)
class TestIPv6RouteLookup(VppTestCase):
- """ IPv6 Route Lookup Test Case """
+ """IPv6 Route Lookup Test Case"""
+
routes = []
def route_lookup(self, prefix, exact):
- return self.vapi.api(self.vapi.papi.ip_route_lookup,
- {
- 'table_id': 0,
- 'exact': exact,
- 'prefix': prefix,
- })
+ return self.vapi.api(
+ self.vapi.papi.ip_route_lookup,
+ {
+ "table_id": 0,
+ "exact": exact,
+ "prefix": prefix,
+ },
+ )
@classmethod
def setUpClass(cls):
@@ -1037,8 +1095,7 @@ class TestIPv6RouteLookup(VppTestCase):
def setUp(self):
super(TestIPv6RouteLookup, self).setUp()
- drop_nh = VppRoutePath("::1", 0xffffffff,
- type=FibPathType.FIB_PATH_TYPE_DROP)
+ drop_nh = VppRoutePath("::1", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_DROP)
# Add 3 routes
r = VppIpRoute(self, "2001:1111::", 32, [drop_nh])
@@ -1064,12 +1121,12 @@ class TestIPv6RouteLookup(VppTestCase):
# Verify we find the host route
prefix = "2001:1111:2222::1/128"
result = self.route_lookup(prefix, True)
- assert (prefix == str(result.route.prefix))
+ assert prefix == str(result.route.prefix)
# Verify we find a middle prefix route
prefix = "2001:1111:2222::/48"
result = self.route_lookup(prefix, True)
- assert (prefix == str(result.route.prefix))
+ assert prefix == str(result.route.prefix)
# Verify we do not find an available LPM.
with self.vapi.assert_negative_api_retval():
@@ -1079,17 +1136,17 @@ class TestIPv6RouteLookup(VppTestCase):
# verify we find lpm
lpm_prefix = "2001:1111:2222::/48"
result = self.route_lookup("2001:1111:2222::2/128", False)
- assert (lpm_prefix == str(result.route.prefix))
+ assert lpm_prefix == str(result.route.prefix)
# Verify we find the exact when not requested
result = self.route_lookup(lpm_prefix, False)
- assert (lpm_prefix == str(result.route.prefix))
+ assert lpm_prefix == str(result.route.prefix)
# Can't seem to delete the default route so no negative LPM test.
class TestIPv6IfAddrRoute(VppTestCase):
- """ IPv6 Interface Addr Route Test Case """
+ """IPv6 Interface Addr Route Test Case"""
@classmethod
def setUpClass(cls):
@@ -1117,7 +1174,7 @@ class TestIPv6IfAddrRoute(VppTestCase):
i.admin_down()
def test_ipv6_ifaddrs_same_prefix(self):
- """ IPv6 Interface Addresses Same Prefix test
+ """IPv6 Interface Addresses Same Prefix test
Test scenario:
@@ -1161,7 +1218,7 @@ class TestIPv6IfAddrRoute(VppTestCase):
self.assertFalse(find_route(self, addr2, 128))
def test_ipv6_ifaddr_del(self):
- """ Delete an interface address that does not exist """
+ """Delete an interface address that does not exist"""
loopbacks = self.create_loopback_interfaces(1)
lo = self.lo_interfaces[0]
@@ -1174,13 +1231,12 @@ class TestIPv6IfAddrRoute(VppTestCase):
#
with self.vapi.assert_negative_api_retval():
self.vapi.sw_interface_add_del_address(
- sw_if_index=lo.sw_if_index,
- prefix=self.pg0.local_ip6_prefix,
- is_add=0)
+ sw_if_index=lo.sw_if_index, prefix=self.pg0.local_ip6_prefix, is_add=0
+ )
class TestICMPv6Echo(VppTestCase):
- """ ICMPv6 Echo Test Case """
+ """ICMPv6 Echo Test Case"""
@classmethod
def setUpClass(cls):
@@ -1209,7 +1265,7 @@ class TestICMPv6Echo(VppTestCase):
i.admin_down()
def test_icmpv6_echo(self):
- """ VPP replies to ICMPv6 Echo Request
+ """VPP replies to ICMPv6 Echo Request
Test scenario:
@@ -1219,14 +1275,18 @@ class TestICMPv6Echo(VppTestCase):
# test both with global and local ipv6 addresses
dsts = (self.pg0.local_ip6, self.pg0.local_ip6_ll)
- id = 0xb
+ id = 0xB
seq = 5
- data = b'\x0a' * 18
+ data = b"\x0a" * 18
p = list()
for dst in dsts:
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=dst) /
- ICMPv6EchoRequest(id=id, seq=seq, data=data)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=dst)
+ / ICMPv6EchoRequest(id=id, seq=seq, data=data)
+ )
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
@@ -1248,7 +1308,7 @@ class TestICMPv6Echo(VppTestCase):
class TestIPv6RD(TestIPv6ND):
- """ IPv6 Router Discovery Test Case """
+ """IPv6 Router Discovery Test Case"""
@classmethod
def setUpClass(cls):
@@ -1278,51 +1338,52 @@ class TestIPv6RD(TestIPv6ND):
super(TestIPv6RD, self).tearDown()
def test_rd_send_router_solicitation(self):
- """ Verify router solicitation packets """
+ """Verify router solicitation packets"""
count = 2
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.vapi.ip6nd_send_router_solicitation(self.pg1.sw_if_index,
- mrc=count)
+ self.vapi.ip6nd_send_router_solicitation(self.pg1.sw_if_index, mrc=count)
rx_list = self.pg1.get_capture(count, timeout=3)
self.assertEqual(len(rx_list), count)
for packet in rx_list:
self.assertEqual(packet.haslayer(IPv6), 1)
- self.assertEqual(packet[IPv6].haslayer(
- ICMPv6ND_RS), 1)
+ self.assertEqual(packet[IPv6].haslayer(ICMPv6ND_RS), 1)
dst = ip6_normalize(packet[IPv6].dst)
dst2 = ip6_normalize("ff02::2")
self.assert_equal(dst, dst2)
src = ip6_normalize(packet[IPv6].src)
src2 = ip6_normalize(self.pg1.local_ip6_ll)
self.assert_equal(src, src2)
- self.assertTrue(
- bool(packet[ICMPv6ND_RS].haslayer(
- ICMPv6NDOptSrcLLAddr)))
- self.assert_equal(
- packet[ICMPv6NDOptSrcLLAddr].lladdr,
- self.pg1.local_mac)
+ self.assertTrue(bool(packet[ICMPv6ND_RS].haslayer(ICMPv6NDOptSrcLLAddr)))
+ self.assert_equal(packet[ICMPv6NDOptSrcLLAddr].lladdr, self.pg1.local_mac)
def verify_prefix_info(self, reported_prefix, prefix_option):
prefix = IPv6Network(
- text_type(prefix_option.getfieldval("prefix") +
- "/" +
- text_type(prefix_option.getfieldval("prefixlen"))),
- strict=False)
- self.assert_equal(reported_prefix.prefix.network_address,
- prefix.network_address)
+ text_type(
+ prefix_option.getfieldval("prefix")
+ + "/"
+ + text_type(prefix_option.getfieldval("prefixlen"))
+ ),
+ strict=False,
+ )
+ self.assert_equal(
+ reported_prefix.prefix.network_address, prefix.network_address
+ )
L = prefix_option.getfieldval("L")
A = prefix_option.getfieldval("A")
option_flags = (L << 7) | (A << 6)
self.assert_equal(reported_prefix.flags, option_flags)
- self.assert_equal(reported_prefix.valid_time,
- prefix_option.getfieldval("validlifetime"))
- self.assert_equal(reported_prefix.preferred_time,
- prefix_option.getfieldval("preferredlifetime"))
+ self.assert_equal(
+ reported_prefix.valid_time, prefix_option.getfieldval("validlifetime")
+ )
+ self.assert_equal(
+ reported_prefix.preferred_time,
+ prefix_option.getfieldval("preferredlifetime"),
+ )
def test_rd_receive_router_advertisement(self):
- """ Verify events triggered by received RA packets """
+ """Verify events triggered by received RA packets"""
self.vapi.want_ip6_ra_events(enable=1)
@@ -1344,12 +1405,13 @@ class TestIPv6RD(TestIPv6ND):
A=0,
)
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(dst=self.pg1.local_ip6_ll,
- src=mk_ll_addr(self.pg1.remote_mac)) /
- ICMPv6ND_RA() /
- prefix_info_1 /
- prefix_info_2)
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(dst=self.pg1.local_ip6_ll, src=mk_ll_addr(self.pg1.remote_mac))
+ / ICMPv6ND_RA()
+ / prefix_info_1
+ / prefix_info_2
+ )
self.pg1.add_stream([p])
self.pg_start()
@@ -1360,7 +1422,8 @@ class TestIPv6RD(TestIPv6ND):
self.assert_equal(ev.router_lifetime_in_sec, 1800)
self.assert_equal(ev.neighbor_reachable_time_in_msec, 0)
self.assert_equal(
- ev.time_in_msec_between_retransmitted_neighbor_solicitations, 0)
+ ev.time_in_msec_between_retransmitted_neighbor_solicitations, 0
+ )
self.assert_equal(ev.n_prefixes, 2)
@@ -1369,7 +1432,7 @@ class TestIPv6RD(TestIPv6ND):
class TestIPv6RDControlPlane(TestIPv6ND):
- """ IPv6 Router Discovery Control Plane Test Case """
+ """IPv6 Router Discovery Control Plane Test Case"""
@classmethod
def setUpClass(cls):
@@ -1403,8 +1466,11 @@ class TestIPv6RDControlPlane(TestIPv6ND):
ra = ICMPv6ND_RA(routerlifetime=routerlifetime)
else:
ra = ICMPv6ND_RA()
- p = (Ether(dst=pg.local_mac, src=pg.remote_mac) /
- IPv6(dst=dst_ip, src=src_ip) / ra)
+ p = (
+ Ether(dst=pg.local_mac, src=pg.remote_mac)
+ / IPv6(dst=dst_ip, src=src_ip)
+ / ra
+ )
return p
@staticmethod
@@ -1415,8 +1481,8 @@ class TestIPv6RDControlPlane(TestIPv6ND):
for path in entry.route.paths:
if path.sw_if_index != 0xFFFFFFFF:
defaut_route = {}
- defaut_route['sw_if_index'] = path.sw_if_index
- defaut_route['next_hop'] = path.nh.address.ip6
+ defaut_route["sw_if_index"] = path.sw_if_index
+ defaut_route["next_hop"] = path.nh.address.ip6
list.append(defaut_route)
return list
@@ -1431,7 +1497,7 @@ class TestIPv6RDControlPlane(TestIPv6ND):
return list
def wait_for_no_default_route(self, n_tries=50, s_time=1):
- while (n_tries):
+ while n_tries:
fib = self.vapi.ip_route_dump(0, True)
default_routes = self.get_default_routes(fib)
if 0 == len(default_routes):
@@ -1442,7 +1508,7 @@ class TestIPv6RDControlPlane(TestIPv6ND):
return False
def test_all(self):
- """ Test handling of SLAAC addresses and default routes """
+ """Test handling of SLAAC addresses and default routes"""
fib = self.vapi.ip_route_dump(0, True)
default_routes = self.get_default_routes(fib)
@@ -1455,22 +1521,25 @@ class TestIPv6RDControlPlane(TestIPv6ND):
self.sleep(0.1)
# send RA
- packet = (self.create_ra_packet(
- self.pg0) / ICMPv6NDOptPrefixInfo(
- prefix="1::",
- prefixlen=64,
- validlifetime=2,
- preferredlifetime=2,
- L=1,
- A=1,
- ) / ICMPv6NDOptPrefixInfo(
- prefix="7::",
- prefixlen=20,
- validlifetime=1500,
- preferredlifetime=1000,
- L=1,
- A=0,
- ))
+ packet = (
+ self.create_ra_packet(self.pg0)
+ / ICMPv6NDOptPrefixInfo(
+ prefix="1::",
+ prefixlen=64,
+ validlifetime=2,
+ preferredlifetime=2,
+ L=1,
+ A=1,
+ )
+ / ICMPv6NDOptPrefixInfo(
+ prefix="7::",
+ prefixlen=20,
+ validlifetime=1500,
+ preferredlifetime=1000,
+ L=1,
+ A=0,
+ )
+ )
self.pg0.add_stream([packet])
self.pg_start()
@@ -1482,16 +1551,17 @@ class TestIPv6RDControlPlane(TestIPv6ND):
addresses = set(self.get_interface_addresses(fib, self.pg0))
new_addresses = addresses.difference(initial_addresses)
self.assertEqual(len(new_addresses), 1)
- prefix = IPv6Network(text_type("%s/%d" % (list(new_addresses)[0], 20)),
- strict=False)
- self.assertEqual(prefix, IPv6Network(text_type('1::/20')))
+ prefix = IPv6Network(
+ text_type("%s/%d" % (list(new_addresses)[0], 20)), strict=False
+ )
+ self.assertEqual(prefix, IPv6Network(text_type("1::/20")))
# check FIB for new default route
default_routes = self.get_default_routes(fib)
self.assertEqual(len(default_routes), 1)
dr = default_routes[0]
- self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
- self.assertEqual(dr['next_hop'], router_address)
+ self.assertEqual(dr["sw_if_index"], self.pg0.sw_if_index)
+ self.assertEqual(dr["next_hop"], router_address)
# send RA to delete default route
packet = self.create_ra_packet(self.pg0, routerlifetime=0)
@@ -1519,8 +1589,8 @@ class TestIPv6RDControlPlane(TestIPv6ND):
default_routes = self.get_default_routes(fib)
self.assertEqual(len(default_routes), 1)
dr = default_routes[0]
- self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
- self.assertEqual(dr['next_hop'], router_address)
+ self.assertEqual(dr["sw_if_index"], self.pg0.sw_if_index)
+ self.assertEqual(dr["next_hop"], router_address)
# send RA, updating router lifetime to 1s
packet = self.create_ra_packet(self.pg0, 1)
@@ -1534,8 +1604,8 @@ class TestIPv6RDControlPlane(TestIPv6ND):
default_routes = self.get_default_routes(fib)
self.assertEqual(len(default_routes), 1)
dr = default_routes[0]
- self.assertEqual(dr['sw_if_index'], self.pg0.sw_if_index)
- self.assertEqual(dr['next_hop'], router_address)
+ self.assertEqual(dr["sw_if_index"], self.pg0.sw_if_index)
+ self.assertEqual(dr["next_hop"], router_address)
self.sleep_on_vpp_time(1)
@@ -1547,9 +1617,10 @@ class TestIPv6RDControlPlane(TestIPv6ND):
new_addresses = addresses.difference(initial_addresses)
self.assertEqual(len(new_addresses), 1)
- prefix = IPv6Network(text_type("%s/%d" % (list(new_addresses)[0], 20)),
- strict=False)
- self.assertEqual(prefix, IPv6Network(text_type('1::/20')))
+ prefix = IPv6Network(
+ text_type("%s/%d" % (list(new_addresses)[0], 20)), strict=False
+ )
+ self.assertEqual(prefix, IPv6Network(text_type("1::/20")))
self.sleep_on_vpp_time(1)
@@ -1561,7 +1632,7 @@ class TestIPv6RDControlPlane(TestIPv6ND):
class IPv6NDProxyTest(TestIPv6ND):
- """ IPv6 ND ProxyTest Case """
+ """IPv6 ND ProxyTest Case"""
@classmethod
def setUpClass(cls):
@@ -1589,7 +1660,7 @@ class IPv6NDProxyTest(TestIPv6ND):
super(IPv6NDProxyTest, self).tearDown()
def test_nd_proxy(self):
- """ IPv6 Proxy ND """
+ """IPv6 Proxy ND"""
#
# Generate some hosts in the subnet that we are proxying
@@ -1604,12 +1675,12 @@ class IPv6NDProxyTest(TestIPv6ND):
# expect no response since it's from an address that is not
# on the link that has the prefix configured
#
- ns_pg1 = (Ether(dst=in6_getnsmac(nsma), src=self.pg1.remote_mac) /
- IPv6(dst=d,
- src=self.pg0._remote_hosts[2].ip6) /
- ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
- ICMPv6NDOptSrcLLAddr(
- lladdr=self.pg0._remote_hosts[2].mac))
+ ns_pg1 = (
+ Ether(dst=in6_getnsmac(nsma), src=self.pg1.remote_mac)
+ / IPv6(dst=d, src=self.pg0._remote_hosts[2].ip6)
+ / ICMPv6ND_NS(tgt=self.pg0.local_ip6)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0._remote_hosts[2].mac)
+ )
self.send_and_assert_no_replies(self.pg1, ns_pg1, "Off link NS")
@@ -1617,32 +1688,38 @@ class IPv6NDProxyTest(TestIPv6ND):
# Add proxy support for the host
#
self.vapi.ip6nd_proxy_add_del(
- is_add=1, ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6),
- sw_if_index=self.pg1.sw_if_index)
+ is_add=1,
+ ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6),
+ sw_if_index=self.pg1.sw_if_index,
+ )
#
# try that NS again. this time we expect an NA back
#
- self.send_and_expect_na(self.pg1, ns_pg1,
- "NS to proxy entry",
- dst_ip=self.pg0._remote_hosts[2].ip6,
- tgt_ip=self.pg0.local_ip6)
+ self.send_and_expect_na(
+ self.pg1,
+ ns_pg1,
+ "NS to proxy entry",
+ dst_ip=self.pg0._remote_hosts[2].ip6,
+ tgt_ip=self.pg0.local_ip6,
+ )
#
# ... and that we have an entry in the ND cache
#
- self.assertTrue(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg0._remote_hosts[2].ip6))
+ self.assertTrue(
+ find_nbr(self, self.pg1.sw_if_index, self.pg0._remote_hosts[2].ip6)
+ )
#
# ... and we can route traffic to it
#
- t = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(dst=self.pg0._remote_hosts[2].ip6,
- src=self.pg0.remote_ip6) /
- inet6.UDP(sport=10000, dport=20000) /
- Raw(b'\xa5' * 100))
+ t = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(dst=self.pg0._remote_hosts[2].ip6, src=self.pg0.remote_ip6)
+ / inet6.UDP(sport=10000, dport=20000)
+ / Raw(b"\xa5" * 100)
+ )
self.pg0.add_stream(t)
self.pg_enable_capture(self.pg_interfaces)
@@ -1653,58 +1730,64 @@ class IPv6NDProxyTest(TestIPv6ND):
self.assertEqual(rx[Ether].dst, self.pg0._remote_hosts[2].mac)
self.assertEqual(rx[Ether].src, self.pg1.local_mac)
- self.assertEqual(rx[IPv6].src,
- t[IPv6].src)
- self.assertEqual(rx[IPv6].dst,
- t[IPv6].dst)
+ self.assertEqual(rx[IPv6].src, t[IPv6].src)
+ self.assertEqual(rx[IPv6].dst, t[IPv6].dst)
#
# Test we proxy for the host on the main interface
#
- ns_pg0 = (Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac) /
- IPv6(dst=d, src=self.pg0.remote_ip6) /
- ICMPv6ND_NS(
- tgt=self.pg0._remote_hosts[2].ip6) /
- ICMPv6NDOptSrcLLAddr(
- lladdr=self.pg0.remote_mac))
+ ns_pg0 = (
+ Ether(dst=in6_getnsmac(nsma), src=self.pg0.remote_mac)
+ / IPv6(dst=d, src=self.pg0.remote_ip6)
+ / ICMPv6ND_NS(tgt=self.pg0._remote_hosts[2].ip6)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac)
+ )
- self.send_and_expect_na(self.pg0, ns_pg0,
- "NS to proxy entry on main",
- tgt_ip=self.pg0._remote_hosts[2].ip6,
- dst_ip=self.pg0.remote_ip6)
+ self.send_and_expect_na(
+ self.pg0,
+ ns_pg0,
+ "NS to proxy entry on main",
+ tgt_ip=self.pg0._remote_hosts[2].ip6,
+ dst_ip=self.pg0.remote_ip6,
+ )
#
# Setup and resolve proxy for another host on another interface
#
- ns_pg2 = (Ether(dst=in6_getnsmac(nsma), src=self.pg2.remote_mac) /
- IPv6(dst=d,
- src=self.pg0._remote_hosts[3].ip6) /
- ICMPv6ND_NS(tgt=self.pg0.local_ip6) /
- ICMPv6NDOptSrcLLAddr(
- lladdr=self.pg0._remote_hosts[2].mac))
+ ns_pg2 = (
+ Ether(dst=in6_getnsmac(nsma), src=self.pg2.remote_mac)
+ / IPv6(dst=d, src=self.pg0._remote_hosts[3].ip6)
+ / ICMPv6ND_NS(tgt=self.pg0.local_ip6)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0._remote_hosts[2].mac)
+ )
self.vapi.ip6nd_proxy_add_del(
- is_add=1, ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6),
- sw_if_index=self.pg2.sw_if_index)
+ is_add=1,
+ ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6),
+ sw_if_index=self.pg2.sw_if_index,
+ )
- self.send_and_expect_na(self.pg2, ns_pg2,
- "NS to proxy entry other interface",
- dst_ip=self.pg0._remote_hosts[3].ip6,
- tgt_ip=self.pg0.local_ip6)
+ self.send_and_expect_na(
+ self.pg2,
+ ns_pg2,
+ "NS to proxy entry other interface",
+ dst_ip=self.pg0._remote_hosts[3].ip6,
+ tgt_ip=self.pg0.local_ip6,
+ )
- self.assertTrue(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg0._remote_hosts[3].ip6))
+ self.assertTrue(
+ find_nbr(self, self.pg2.sw_if_index, self.pg0._remote_hosts[3].ip6)
+ )
#
# hosts can communicate. pg2->pg1
#
- t2 = (Ether(dst=self.pg2.local_mac,
- src=self.pg0.remote_hosts[3].mac) /
- IPv6(dst=self.pg0._remote_hosts[2].ip6,
- src=self.pg0._remote_hosts[3].ip6) /
- inet6.UDP(sport=10000, dport=20000) /
- Raw(b'\xa5' * 100))
+ t2 = (
+ Ether(dst=self.pg2.local_mac, src=self.pg0.remote_hosts[3].mac)
+ / IPv6(dst=self.pg0._remote_hosts[2].ip6, src=self.pg0._remote_hosts[3].ip6)
+ / inet6.UDP(sport=10000, dport=20000)
+ / Raw(b"\xa5" * 100)
+ )
self.pg2.add_stream(t2)
self.pg_enable_capture(self.pg_interfaces)
@@ -1715,27 +1798,29 @@ class IPv6NDProxyTest(TestIPv6ND):
self.assertEqual(rx[Ether].dst, self.pg0._remote_hosts[2].mac)
self.assertEqual(rx[Ether].src, self.pg1.local_mac)
- self.assertEqual(rx[IPv6].src,
- t2[IPv6].src)
- self.assertEqual(rx[IPv6].dst,
- t2[IPv6].dst)
+ self.assertEqual(rx[IPv6].src, t2[IPv6].src)
+ self.assertEqual(rx[IPv6].dst, t2[IPv6].dst)
#
# remove the proxy configs
#
self.vapi.ip6nd_proxy_add_del(
ip=inet_pton(AF_INET6, self.pg0._remote_hosts[2].ip6),
- sw_if_index=self.pg1.sw_if_index, is_add=0)
+ sw_if_index=self.pg1.sw_if_index,
+ is_add=0,
+ )
self.vapi.ip6nd_proxy_add_del(
ip=inet_pton(AF_INET6, self.pg0._remote_hosts[3].ip6),
- sw_if_index=self.pg2.sw_if_index, is_add=0)
+ sw_if_index=self.pg2.sw_if_index,
+ is_add=0,
+ )
- self.assertFalse(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg0._remote_hosts[3].ip6))
- self.assertFalse(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg0._remote_hosts[2].ip6))
+ self.assertFalse(
+ find_nbr(self, self.pg2.sw_if_index, self.pg0._remote_hosts[3].ip6)
+ )
+ self.assertFalse(
+ find_nbr(self, self.pg1.sw_if_index, self.pg0._remote_hosts[2].ip6)
+ )
#
# no longer proxy-ing...
@@ -1758,7 +1843,7 @@ class IPv6NDProxyTest(TestIPv6ND):
class TestIP6Null(VppTestCase):
- """ IPv6 routes via NULL """
+ """IPv6 routes via NULL"""
@classmethod
def setUpClass(cls):
@@ -1786,21 +1871,28 @@ class TestIP6Null(VppTestCase):
i.admin_down()
def test_ip_null(self):
- """ IP NULL route """
+ """IP NULL route"""
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst="2001::1") /
- inet6.UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst="2001::1")
+ / inet6.UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# A route via IP NULL that will reply with ICMP unreachables
#
ip_unreach = VppIpRoute(
- self, "2001::", 64,
- [VppRoutePath("::", 0xffffffff,
- type=FibPathType.FIB_PATH_TYPE_ICMP_UNREACH)])
+ self,
+ "2001::",
+ 64,
+ [
+ VppRoutePath(
+ "::", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_ICMP_UNREACH
+ )
+ ],
+ )
ip_unreach.add_vpp_config()
self.pg0.add_stream(p)
@@ -1821,9 +1913,15 @@ class TestIP6Null(VppTestCase):
# A route via IP NULL that will reply with ICMP prohibited
#
ip_prohibit = VppIpRoute(
- self, "2001::1", 128,
- [VppRoutePath("::", 0xffffffff,
- type=FibPathType.FIB_PATH_TYPE_ICMP_PROHIBIT)])
+ self,
+ "2001::1",
+ 128,
+ [
+ VppRoutePath(
+ "::", 0xFFFFFFFF, type=FibPathType.FIB_PATH_TYPE_ICMP_PROHIBIT
+ )
+ ],
+ )
ip_prohibit.add_vpp_config()
self.pg0.add_stream(p)
@@ -1839,7 +1937,7 @@ class TestIP6Null(VppTestCase):
class TestIP6Disabled(VppTestCase):
- """ IPv6 disabled """
+ """IPv6 disabled"""
@classmethod
def setUpClass(cls):
@@ -1870,7 +1968,7 @@ class TestIP6Disabled(VppTestCase):
i.admin_down()
def test_ip_disabled(self):
- """ IP Disabled """
+ """IP Disabled"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -1881,24 +1979,32 @@ class TestIP6Disabled(VppTestCase):
route_ff_01 = VppIpMRoute(
self,
"::",
- "ffef::1", 128,
+ "ffef::1",
+ 128,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_ff_01.add_vpp_config()
- pu = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IPv6(src="2001::1", dst=self.pg0.remote_ip6) /
- inet6.UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- pm = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IPv6(src="2001::1", dst="ffef::1") /
- inet6.UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pu = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IPv6(src="2001::1", dst=self.pg0.remote_ip6)
+ / inet6.UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ pm = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IPv6(src="2001::1", dst="ffef::1")
+ / inet6.UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# PG1 does not forward IP traffic
@@ -1937,7 +2043,7 @@ class TestIP6Disabled(VppTestCase):
class TestIP6LoadBalance(VppTestCase):
- """ IPv6 Load-Balancing """
+ """IPv6 Load-Balancing"""
@classmethod
def setUpClass(cls):
@@ -1969,7 +2075,7 @@ class TestIP6LoadBalance(VppTestCase):
super(TestIP6LoadBalance, self).tearDown()
def test_ip6_load_balance(self):
- """ IPv6 Load-Balancing """
+ """IPv6 Load-Balancing"""
#
# An array of packets that differ only in the destination port
@@ -1991,47 +2097,65 @@ class TestIP6LoadBalance(VppTestCase):
for ii in range(NUM_PKTS):
port_ip_hdr = (
- IPv6(dst="3000::1", src="3000:1::1") /
- inet6.UDP(sport=1234, dport=1234 + ii) /
- Raw(b'\xa5' * 100))
- port_ip_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- port_ip_hdr))
- port_mpls_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- MPLS(label=66, ttl=2) /
- port_ip_hdr))
- port_mpls_neos_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- MPLS(label=67, ttl=2) /
- MPLS(label=77, ttl=2) /
- port_ip_hdr))
- port_ent_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- MPLS(label=67, ttl=2) /
- MPLS(label=14, ttl=2) /
- MPLS(label=999, ttl=2) /
- port_ip_hdr))
+ IPv6(dst="3000::1", src="3000:1::1")
+ / inet6.UDP(sport=1234, dport=1234 + ii)
+ / Raw(b"\xa5" * 100)
+ )
+ port_ip_pkts.append(
+ (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / port_ip_hdr)
+ )
+ port_mpls_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / MPLS(label=66, ttl=2)
+ / port_ip_hdr
+ )
+ )
+ port_mpls_neos_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / MPLS(label=67, ttl=2)
+ / MPLS(label=77, ttl=2)
+ / port_ip_hdr
+ )
+ )
+ port_ent_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / MPLS(label=67, ttl=2)
+ / MPLS(label=14, ttl=2)
+ / MPLS(label=999, ttl=2)
+ / port_ip_hdr
+ )
+ )
src_ip_hdr = (
- IPv6(dst="3000::1", src="3000:1::%d" % ii) /
- inet6.UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- src_ip_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- src_ip_hdr))
- src_mpls_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- MPLS(label=66, ttl=2) /
- src_ip_hdr))
+ IPv6(dst="3000::1", src="3000:1::%d" % ii)
+ / inet6.UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ src_ip_pkts.append(
+ (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / src_ip_hdr)
+ )
+ src_mpls_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / MPLS(label=66, ttl=2)
+ / src_ip_hdr
+ )
+ )
#
# A route for the IP packets
#
- route_3000_1 = VppIpRoute(self, "3000::1", 128,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index),
- VppRoutePath(self.pg2.remote_ip6,
- self.pg2.sw_if_index)])
+ route_3000_1 = VppIpRoute(
+ self,
+ "3000::1",
+ 128,
+ [
+ VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index),
+ VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index),
+ ],
+ )
route_3000_1.add_vpp_config()
#
@@ -2043,13 +2167,15 @@ class TestIP6LoadBalance(VppTestCase):
#
# An MPLS route for the non-EOS packets
#
- route_67 = VppMplsRoute(self, 67, 0,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index,
- labels=[67]),
- VppRoutePath(self.pg2.remote_ip6,
- self.pg2.sw_if_index,
- labels=[67])])
+ route_67 = VppMplsRoute(
+ self,
+ 67,
+ 0,
+ [
+ VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index, labels=[67]),
+ VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index, labels=[67]),
+ ],
+ )
route_67.add_vpp_config()
#
@@ -2061,17 +2187,20 @@ class TestIP6LoadBalance(VppTestCase):
# be guaranteed. But with 64 different packets we do expect some
# balancing. So instead just ensure there is traffic on each link.
#
- rx = self.send_and_expect_load_balancing(self.pg0, port_ip_pkts,
- [self.pg1, self.pg2])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, port_ip_pkts, [self.pg1, self.pg2]
+ )
n_ip_pg0 = len(rx[0])
- self.send_and_expect_load_balancing(self.pg0, src_ip_pkts,
- [self.pg1, self.pg2])
- self.send_and_expect_load_balancing(self.pg0, port_mpls_pkts,
- [self.pg1, self.pg2])
- self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
- [self.pg1, self.pg2])
- rx = self.send_and_expect_load_balancing(self.pg0, port_mpls_neos_pkts,
- [self.pg1, self.pg2])
+ self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, [self.pg1, self.pg2])
+ self.send_and_expect_load_balancing(
+ self.pg0, port_mpls_pkts, [self.pg1, self.pg2]
+ )
+ self.send_and_expect_load_balancing(
+ self.pg0, src_mpls_pkts, [self.pg1, self.pg2]
+ )
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, port_mpls_neos_pkts, [self.pg1, self.pg2]
+ )
n_mpls_pg0 = len(rx[0])
#
@@ -2079,12 +2208,14 @@ class TestIP6LoadBalance(VppTestCase):
#
self.vapi.set_ip_flow_hash_router_id(router_id=0x11111111)
- rx = self.send_and_expect_load_balancing(self.pg0, port_ip_pkts,
- [self.pg1, self.pg2])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, port_ip_pkts, [self.pg1, self.pg2]
+ )
self.assertNotEqual(n_ip_pg0, len(rx[0]))
- rx = self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
- [self.pg1, self.pg2])
+ rx = self.send_and_expect_load_balancing(
+ self.pg0, src_mpls_pkts, [self.pg1, self.pg2]
+ )
self.assertNotEqual(n_mpls_pg0, len(rx[0]))
#
@@ -2098,20 +2229,22 @@ class TestIP6LoadBalance(VppTestCase):
# - now only the stream with differing source address will
# load-balance
#
- self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, proto=1,
- sport=0, dport=0, is_ipv6=1)
+ self.vapi.set_ip_flow_hash(
+ vrf_id=0, src=1, dst=1, proto=1, sport=0, dport=0, is_ipv6=1
+ )
- self.send_and_expect_load_balancing(self.pg0, src_ip_pkts,
- [self.pg1, self.pg2])
- self.send_and_expect_load_balancing(self.pg0, src_mpls_pkts,
- [self.pg1, self.pg2])
+ self.send_and_expect_load_balancing(self.pg0, src_ip_pkts, [self.pg1, self.pg2])
+ self.send_and_expect_load_balancing(
+ self.pg0, src_mpls_pkts, [self.pg1, self.pg2]
+ )
self.send_and_expect_only(self.pg0, port_ip_pkts, self.pg2)
#
# change the flow hash config back to defaults
#
- self.vapi.set_ip_flow_hash(vrf_id=0, src=1, dst=1, sport=1, dport=1,
- proto=1, is_ipv6=1)
+ self.vapi.set_ip_flow_hash(
+ vrf_id=0, src=1, dst=1, sport=1, dport=1, proto=1, is_ipv6=1
+ )
#
# Recursive prefixes
@@ -2122,44 +2255,52 @@ class TestIP6LoadBalance(VppTestCase):
src_pkts = []
for ii in range(257):
- port_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(dst="4000::1",
- src="4000:1::1") /
- inet6.UDP(sport=1234,
- dport=1234 + ii) /
- Raw(b'\xa5' * 100)))
- src_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(dst="4000::1",
- src="4000:1::%d" % ii) /
- inet6.UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)))
-
- route_3000_2 = VppIpRoute(self, "3000::2", 128,
- [VppRoutePath(self.pg3.remote_ip6,
- self.pg3.sw_if_index),
- VppRoutePath(self.pg4.remote_ip6,
- self.pg4.sw_if_index)])
+ port_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(dst="4000::1", src="4000:1::1")
+ / inet6.UDP(sport=1234, dport=1234 + ii)
+ / Raw(b"\xa5" * 100)
+ )
+ )
+ src_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(dst="4000::1", src="4000:1::%d" % ii)
+ / inet6.UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ )
+
+ route_3000_2 = VppIpRoute(
+ self,
+ "3000::2",
+ 128,
+ [
+ VppRoutePath(self.pg3.remote_ip6, self.pg3.sw_if_index),
+ VppRoutePath(self.pg4.remote_ip6, self.pg4.sw_if_index),
+ ],
+ )
route_3000_2.add_vpp_config()
- route_4000_1 = VppIpRoute(self, "4000::1", 128,
- [VppRoutePath("3000::1",
- 0xffffffff),
- VppRoutePath("3000::2",
- 0xffffffff)])
+ route_4000_1 = VppIpRoute(
+ self,
+ "4000::1",
+ 128,
+ [VppRoutePath("3000::1", 0xFFFFFFFF), VppRoutePath("3000::2", 0xFFFFFFFF)],
+ )
route_4000_1.add_vpp_config()
#
# inject the packet on pg0 - expect load-balancing across all 4 paths
#
self.vapi.cli("clear trace")
- self.send_and_expect_load_balancing(self.pg0, port_pkts,
- [self.pg1, self.pg2,
- self.pg3, self.pg4])
- self.send_and_expect_load_balancing(self.pg0, src_pkts,
- [self.pg1, self.pg2,
- self.pg3, self.pg4])
+ self.send_and_expect_load_balancing(
+ self.pg0, port_pkts, [self.pg1, self.pg2, self.pg3, self.pg4]
+ )
+ self.send_and_expect_load_balancing(
+ self.pg0, src_pkts, [self.pg1, self.pg2, self.pg3, self.pg4]
+ )
#
# Recursive prefixes
@@ -2168,22 +2309,26 @@ class TestIP6LoadBalance(VppTestCase):
port_pkts = []
for ii in range(257):
- port_pkts.append((Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(dst="6000::1",
- src="6000:1::1") /
- inet6.UDP(sport=1234,
- dport=1234 + ii) /
- Raw(b'\xa5' * 100)))
-
- route_5000_2 = VppIpRoute(self, "5000::2", 128,
- [VppRoutePath(self.pg3.remote_ip6,
- self.pg3.sw_if_index)])
+ port_pkts.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(dst="6000::1", src="6000:1::1")
+ / inet6.UDP(sport=1234, dport=1234 + ii)
+ / Raw(b"\xa5" * 100)
+ )
+ )
+
+ route_5000_2 = VppIpRoute(
+ self,
+ "5000::2",
+ 128,
+ [VppRoutePath(self.pg3.remote_ip6, self.pg3.sw_if_index)],
+ )
route_5000_2.add_vpp_config()
- route_6000_1 = VppIpRoute(self, "6000::1", 128,
- [VppRoutePath("5000::2",
- 0xffffffff)])
+ route_6000_1 = VppIpRoute(
+ self, "6000::1", 128, [VppRoutePath("5000::2", 0xFFFFFFFF)]
+ )
route_6000_1.add_vpp_config()
#
@@ -2194,7 +2339,7 @@ class TestIP6LoadBalance(VppTestCase):
class IP6PuntSetup(object):
- """ Setup for IPv6 Punt Police/Redirect """
+ """Setup for IPv6 Punt Police/Redirect"""
def punt_setup(self):
self.create_pg_interfaces(range(4))
@@ -2204,12 +2349,12 @@ class IP6PuntSetup(object):
i.config_ip6()
i.resolve_ndp()
- self.pkt = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=self.pg0.local_ip6) /
- inet6.TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ self.pkt = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / inet6.TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
def punt_teardown(self):
for i in self.pg_interfaces:
@@ -2218,7 +2363,7 @@ class IP6PuntSetup(object):
class TestIP6Punt(IP6PuntSetup, VppTestCase):
- """ IPv6 Punt Police/Redirect """
+ """IPv6 Punt Police/Redirect"""
def setUp(self):
super(TestIP6Punt, self).setUp()
@@ -2229,7 +2374,7 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase):
super(TestIP6Punt, self).tearDown()
def test_ip_punt(self):
- """ IP6 punt police and redirect """
+ """IP6 punt police and redirect"""
pkts = self.pkt * 1025
@@ -2237,8 +2382,9 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase):
# Configure a punt redirect via pg1.
#
nh_addr = self.pg1.remote_ip6
- ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index,
- self.pg1.sw_if_index, nh_addr)
+ ip_punt_redirect = VppIpPuntRedirect(
+ self, self.pg0.sw_if_index, self.pg1.sw_if_index, nh_addr
+ )
ip_punt_redirect.add_vpp_config()
self.send_and_expect(self.pg0, pkts, self.pg1)
@@ -2248,8 +2394,7 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase):
#
policer = VppPolicer(self, "ip6-punt", 400, 0, 10, 0, rate_type=1)
policer.add_vpp_config()
- ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index,
- is_ip6=True)
+ ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index, is_ip6=True)
ip_punt_policer.add_vpp_config()
self.vapi.cli("clear trace")
@@ -2265,9 +2410,9 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase):
stats = policer.get_stats()
# Single rate policer - expect conform, violate but no exceed
- self.assertGreater(stats['conform_packets'], 0)
- self.assertEqual(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ self.assertGreater(stats["conform_packets"], 0)
+ self.assertEqual(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
self.assertGreater(len(rx), 0)
self.assertLess(len(rx), len(pkts))
@@ -2283,31 +2428,34 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase):
# remove the redirect. expect full drop.
#
ip_punt_redirect.remove_vpp_config()
- self.send_and_assert_no_replies(self.pg0, pkts,
- "IP no punt config")
+ self.send_and_assert_no_replies(self.pg0, pkts, "IP no punt config")
#
# Add a redirect that is not input port selective
#
- ip_punt_redirect = VppIpPuntRedirect(self, 0xffffffff,
- self.pg1.sw_if_index, nh_addr)
+ ip_punt_redirect = VppIpPuntRedirect(
+ self, 0xFFFFFFFF, self.pg1.sw_if_index, nh_addr
+ )
ip_punt_redirect.add_vpp_config()
self.send_and_expect(self.pg0, pkts, self.pg1)
ip_punt_redirect.remove_vpp_config()
def test_ip_punt_dump(self):
- """ IP6 punt redirect dump"""
+ """IP6 punt redirect dump"""
#
# Configure a punt redirects
#
nh_address = self.pg3.remote_ip6
- ipr_03 = VppIpPuntRedirect(self, self.pg0.sw_if_index,
- self.pg3.sw_if_index, nh_address)
- ipr_13 = VppIpPuntRedirect(self, self.pg1.sw_if_index,
- self.pg3.sw_if_index, nh_address)
- ipr_23 = VppIpPuntRedirect(self, self.pg2.sw_if_index,
- self.pg3.sw_if_index, '0::0')
+ ipr_03 = VppIpPuntRedirect(
+ self, self.pg0.sw_if_index, self.pg3.sw_if_index, nh_address
+ )
+ ipr_13 = VppIpPuntRedirect(
+ self, self.pg1.sw_if_index, self.pg3.sw_if_index, nh_address
+ )
+ ipr_23 = VppIpPuntRedirect(
+ self, self.pg2.sw_if_index, self.pg3.sw_if_index, "0::0"
+ )
ipr_03.add_vpp_config()
ipr_13.add_vpp_config()
ipr_23.add_vpp_config()
@@ -2322,16 +2470,17 @@ class TestIP6Punt(IP6PuntSetup, VppTestCase):
#
# Dump punt redirects for all interfaces
#
- punts = self.vapi.ip_punt_redirect_dump(0xffffffff, is_ipv6=1)
+ punts = self.vapi.ip_punt_redirect_dump(0xFFFFFFFF, is_ipv6=1)
self.assertEqual(len(punts), 3)
for p in punts:
self.assertEqual(p.punt.tx_sw_if_index, self.pg3.sw_if_index)
self.assertNotEqual(punts[1].punt.nh, self.pg3.remote_ip6)
- self.assertEqual(str(punts[2].punt.nh), '::')
+ self.assertEqual(str(punts[2].punt.nh), "::")
class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase):
- """ IPv6 Punt Police/Redirect """
+ """IPv6 Punt Police/Redirect"""
+
vpp_worker_count = 2
def setUp(self):
@@ -2343,29 +2492,42 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase):
super(TestIP6PuntHandoff, self).tearDown()
def test_ip_punt(self):
- """ IP6 punt policer thread handoff """
+ """IP6 punt policer thread handoff"""
pkts = self.pkt * NUM_PKTS
#
# Configure a punt redirect via pg1.
#
nh_addr = self.pg1.remote_ip6
- ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index,
- self.pg1.sw_if_index, nh_addr)
+ ip_punt_redirect = VppIpPuntRedirect(
+ self, self.pg0.sw_if_index, self.pg1.sw_if_index, nh_addr
+ )
ip_punt_redirect.add_vpp_config()
action_tx = PolicerAction(
- VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT,
- 0)
+ VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0
+ )
#
# This policer drops no packets, we are just
# testing that they get to the right thread.
#
- policer = VppPolicer(self, "ip6-punt", 400, 0, 10, 0, 1,
- 0, 0, False, action_tx, action_tx, action_tx)
+ policer = VppPolicer(
+ self,
+ "ip6-punt",
+ 400,
+ 0,
+ 10,
+ 0,
+ 1,
+ 0,
+ 0,
+ False,
+ action_tx,
+ action_tx,
+ action_tx,
+ )
policer.add_vpp_config()
- ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index,
- is_ip6=True)
+ ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index, is_ip6=True)
ip_punt_policer.add_vpp_config()
for worker in [0, 1]:
@@ -2377,9 +2539,9 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase):
stats = policer.get_stats()
# Single rate policer - expect conform, violate but no exceed
- self.assertGreater(stats['conform_packets'], 0)
- self.assertEqual(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ self.assertGreater(stats["conform_packets"], 0)
+ self.assertEqual(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
# Worker 0, should have done all the policing
stats0 = policer.get_stats(worker=0)
@@ -2387,9 +2549,9 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase):
# Worker 1, should have handed everything off
stats1 = policer.get_stats(worker=1)
- self.assertEqual(stats1['conform_packets'], 0)
- self.assertEqual(stats1['exceed_packets'], 0)
- self.assertEqual(stats1['violate_packets'], 0)
+ self.assertEqual(stats1["conform_packets"], 0)
+ self.assertEqual(stats1["exceed_packets"], 0)
+ self.assertEqual(stats1["violate_packets"], 0)
# Bind the policer to worker 1 and repeat
policer.bind_vpp_config(1, True)
@@ -2402,19 +2564,23 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase):
stats0 = policer.get_stats(worker=0)
stats1 = policer.get_stats(worker=1)
- self.assertGreater(stats0['conform_packets'], 0)
- self.assertEqual(stats0['exceed_packets'], 0)
- self.assertGreater(stats0['violate_packets'], 0)
+ self.assertGreater(stats0["conform_packets"], 0)
+ self.assertEqual(stats0["exceed_packets"], 0)
+ self.assertGreater(stats0["violate_packets"], 0)
- self.assertGreater(stats1['conform_packets'], 0)
- self.assertEqual(stats1['exceed_packets'], 0)
- self.assertGreater(stats1['violate_packets'], 0)
+ self.assertGreater(stats1["conform_packets"], 0)
+ self.assertEqual(stats1["exceed_packets"], 0)
+ self.assertGreater(stats1["violate_packets"], 0)
- self.assertEqual(stats0['conform_packets'] + stats1['conform_packets'],
- stats['conform_packets'])
+ self.assertEqual(
+ stats0["conform_packets"] + stats1["conform_packets"],
+ stats["conform_packets"],
+ )
- self.assertEqual(stats0['violate_packets'] + stats1['violate_packets'],
- stats['violate_packets'])
+ self.assertEqual(
+ stats0["violate_packets"] + stats1["violate_packets"],
+ stats["violate_packets"],
+ )
# Unbind the policer and repeat
policer.bind_vpp_config(1, False)
@@ -2427,11 +2593,9 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase):
stats0new = policer.get_stats(worker=0)
stats1new = policer.get_stats(worker=1)
- self.assertGreater(stats0new['conform_packets'],
- stats0['conform_packets'])
- self.assertEqual(stats0new['exceed_packets'], 0)
- self.assertGreater(stats0new['violate_packets'],
- stats0['violate_packets'])
+ self.assertGreater(stats0new["conform_packets"], stats0["conform_packets"])
+ self.assertEqual(stats0new["exceed_packets"], 0)
+ self.assertGreater(stats0new["violate_packets"], stats0["violate_packets"])
self.assertEqual(stats1, stats1new)
@@ -2444,7 +2608,7 @@ class TestIP6PuntHandoff(IP6PuntSetup, VppTestCase):
class TestIP6Deag(VppTestCase):
- """ IPv6 Deaggregate Routes """
+ """IPv6 Deaggregate Routes"""
@classmethod
def setUpClass(cls):
@@ -2471,7 +2635,7 @@ class TestIP6Deag(VppTestCase):
i.admin_down()
def test_ip_deag(self):
- """ IP Deag Routes """
+ """IP Deag Routes"""
#
# Create a table to be used for:
@@ -2487,16 +2651,22 @@ class TestIP6Deag(VppTestCase):
# Add a route in the default table to point to a deag/
# second lookup in each of these tables
#
- route_to_dst = VppIpRoute(self, "1::1", 128,
- [VppRoutePath("::",
- 0xffffffff,
- nh_table_id=1)])
+ route_to_dst = VppIpRoute(
+ self, "1::1", 128, [VppRoutePath("::", 0xFFFFFFFF, nh_table_id=1)]
+ )
route_to_src = VppIpRoute(
- self, "1::2", 128,
- [VppRoutePath("::",
- 0xffffffff,
- nh_table_id=2,
- type=FibPathType.FIB_PATH_TYPE_SOURCE_LOOKUP)])
+ self,
+ "1::2",
+ 128,
+ [
+ VppRoutePath(
+ "::",
+ 0xFFFFFFFF,
+ nh_table_id=2,
+ type=FibPathType.FIB_PATH_TYPE_SOURCE_LOOKUP,
+ )
+ ],
+ )
route_to_dst.add_vpp_config()
route_to_src.add_vpp_config()
@@ -2505,31 +2675,34 @@ class TestIP6Deag(VppTestCase):
# packets to these destination are dropped, since they'll
# hit the respective default routes in the second table
#
- p_dst = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src="5::5", dst="1::1") /
- inet6.TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- p_src = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src="2::2", dst="1::2") /
- inet6.TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_dst = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src="5::5", dst="1::1")
+ / inet6.TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ p_src = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src="2::2", dst="1::2")
+ / inet6.TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
pkts_dst = p_dst * 257
pkts_src = p_src * 257
- self.send_and_assert_no_replies(self.pg0, pkts_dst,
- "IP in dst table")
- self.send_and_assert_no_replies(self.pg0, pkts_src,
- "IP in src table")
+ self.send_and_assert_no_replies(self.pg0, pkts_dst, "IP in dst table")
+ self.send_and_assert_no_replies(self.pg0, pkts_src, "IP in src table")
#
# add a route in the dst table to forward via pg1
#
- route_in_dst = VppIpRoute(self, "1::1", 128,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)],
- table_id=1)
+ route_in_dst = VppIpRoute(
+ self,
+ "1::1",
+ 128,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ table_id=1,
+ )
route_in_dst.add_vpp_config()
self.send_and_expect(self.pg0, pkts_dst, self.pg1)
@@ -2537,33 +2710,34 @@ class TestIP6Deag(VppTestCase):
#
# add a route in the src table to forward via pg2
#
- route_in_src = VppIpRoute(self, "2::2", 128,
- [VppRoutePath(self.pg2.remote_ip6,
- self.pg2.sw_if_index)],
- table_id=2)
+ route_in_src = VppIpRoute(
+ self,
+ "2::2",
+ 128,
+ [VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index)],
+ table_id=2,
+ )
route_in_src.add_vpp_config()
self.send_and_expect(self.pg0, pkts_src, self.pg2)
#
# loop in the lookup DP
#
- route_loop = VppIpRoute(self, "3::3", 128,
- [VppRoutePath("::",
- 0xffffffff)])
+ route_loop = VppIpRoute(self, "3::3", 128, [VppRoutePath("::", 0xFFFFFFFF)])
route_loop.add_vpp_config()
- p_l = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src="3::4", dst="3::3") /
- inet6.TCP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_l = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src="3::4", dst="3::3")
+ / inet6.TCP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- self.send_and_assert_no_replies(self.pg0, p_l * 257,
- "IP lookup loop")
+ self.send_and_assert_no_replies(self.pg0, p_l * 257, "IP lookup loop")
class TestIP6Input(VppTestCase):
- """ IPv6 Input Exception Test Cases """
+ """IPv6 Input Exception Test Cases"""
@classmethod
def setUpClass(cls):
@@ -2590,72 +2764,110 @@ class TestIP6Input(VppTestCase):
i.admin_down()
def test_ip_input_icmp_reply(self):
- """ IP6 Input Exception - Return ICMP (3,0) """
+ """IP6 Input Exception - Return ICMP (3,0)"""
#
# hop limit - ICMP replies
#
- p_version = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=self.pg1.remote_ip6,
- hlim=1) /
- inet6.UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_version = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6, hlim=1)
+ / inet6.UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
- rxs = self.send_and_expect_some(self.pg0,
- p_version * NUM_PKTS,
- self.pg0)
+ rxs = self.send_and_expect_some(self.pg0, p_version * NUM_PKTS, self.pg0)
for rx in rxs:
icmp = rx[ICMPv6TimeExceeded]
# 0: "hop limit exceeded in transit",
self.assertEqual((icmp.type, icmp.code), (3, 0))
- icmpv6_data = '\x0a' * 18
+ icmpv6_data = "\x0a" * 18
all_0s = "::"
all_1s = "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"
- @parameterized.expand([
- # Name, src, dst, l4proto, msg, timeout
- ("src='iface', dst='iface'", None, None,
- inet6.UDP(sport=1234, dport=1234), "funky version", None),
- ("src='All 0's', dst='iface'", all_0s, None,
- ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
- ("src='iface', dst='All 0's'", None, all_0s,
- ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
- ("src='All 1's', dst='iface'", all_1s, None,
- ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
- ("src='iface', dst='All 1's'", None, all_1s,
- ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
- ("src='All 1's', dst='All 1's'", all_1s, all_1s,
- ICMPv6EchoRequest(id=0xb, seq=5, data=icmpv6_data), None, 0.1),
-
- ])
+ @parameterized.expand(
+ [
+ # Name, src, dst, l4proto, msg, timeout
+ (
+ "src='iface', dst='iface'",
+ None,
+ None,
+ inet6.UDP(sport=1234, dport=1234),
+ "funky version",
+ None,
+ ),
+ (
+ "src='All 0's', dst='iface'",
+ all_0s,
+ None,
+ ICMPv6EchoRequest(id=0xB, seq=5, data=icmpv6_data),
+ None,
+ 0.1,
+ ),
+ (
+ "src='iface', dst='All 0's'",
+ None,
+ all_0s,
+ ICMPv6EchoRequest(id=0xB, seq=5, data=icmpv6_data),
+ None,
+ 0.1,
+ ),
+ (
+ "src='All 1's', dst='iface'",
+ all_1s,
+ None,
+ ICMPv6EchoRequest(id=0xB, seq=5, data=icmpv6_data),
+ None,
+ 0.1,
+ ),
+ (
+ "src='iface', dst='All 1's'",
+ None,
+ all_1s,
+ ICMPv6EchoRequest(id=0xB, seq=5, data=icmpv6_data),
+ None,
+ 0.1,
+ ),
+ (
+ "src='All 1's', dst='All 1's'",
+ all_1s,
+ all_1s,
+ ICMPv6EchoRequest(id=0xB, seq=5, data=icmpv6_data),
+ None,
+ 0.1,
+ ),
+ ]
+ )
def test_ip_input_no_replies(self, name, src, dst, l4, msg, timeout):
- self._testMethodDoc = 'IPv6 Input Exception - %s' % name
-
- p_version = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=src or self.pg0.remote_ip6,
- dst=dst or self.pg1.remote_ip6,
- version=3) /
- l4 /
- Raw(b'\xa5' * 100))
+ self._testMethodDoc = "IPv6 Input Exception - %s" % name
+
+ p_version = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(
+ src=src or self.pg0.remote_ip6,
+ dst=dst or self.pg1.remote_ip6,
+ version=3,
+ )
+ / l4
+ / Raw(b"\xa5" * 100)
+ )
- self.send_and_assert_no_replies(self.pg0, p_version * NUM_PKTS,
- remark=msg or "",
- timeout=timeout)
+ self.send_and_assert_no_replies(
+ self.pg0, p_version * NUM_PKTS, remark=msg or "", timeout=timeout
+ )
def test_hop_by_hop(self):
- """ Hop-by-hop header test """
-
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- IPv6ExtHdrHopByHop() /
- inet6.UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ """Hop-by-hop header test"""
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / IPv6ExtHdrHopByHop()
+ / inet6.UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
@@ -2663,7 +2875,7 @@ class TestIP6Input(VppTestCase):
class TestIP6Replace(VppTestCase):
- """ IPv6 Table Replace """
+ """IPv6 Table Replace"""
@classmethod
def setUpClass(cls):
@@ -2685,8 +2897,7 @@ class TestIP6Replace(VppTestCase):
i.admin_up()
i.config_ip6()
i.generate_remote_hosts(2)
- self.tables.append(VppIpTable(self, table_id,
- True).add_vpp_config())
+ self.tables.append(VppIpTable(self, table_id, True).add_vpp_config())
table_id += 1
def tearDown(self):
@@ -2696,7 +2907,7 @@ class TestIP6Replace(VppTestCase):
i.unconfig_ip6()
def test_replace(self):
- """ IP Table Replace """
+ """IP Table Replace"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -2713,31 +2924,50 @@ class TestIP6Replace(VppTestCase):
for ii, t in enumerate(self.tables):
for jj in range(1, N_ROUTES):
uni = VppIpRoute(
- self, "2001::%d" % jj if jj != 0 else "2001::", 128,
- [VppRoutePath(links[ii].remote_hosts[0].ip6,
- links[ii].sw_if_index),
- VppRoutePath(links[ii].remote_hosts[1].ip6,
- links[ii].sw_if_index)],
- table_id=t.table_id).add_vpp_config()
+ self,
+ "2001::%d" % jj if jj != 0 else "2001::",
+ 128,
+ [
+ VppRoutePath(
+ links[ii].remote_hosts[0].ip6, links[ii].sw_if_index
+ ),
+ VppRoutePath(
+ links[ii].remote_hosts[1].ip6, links[ii].sw_if_index
+ ),
+ ],
+ table_id=t.table_id,
+ ).add_vpp_config()
multi = VppIpMRoute(
- self, "::",
- "ff:2001::%d" % jj, 128,
+ self,
+ "::",
+ "ff:2001::%d" % jj,
+ 128,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
- VppMRoutePath(self.pg2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
- VppMRoutePath(self.pg3.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)],
- table_id=t.table_id).add_vpp_config()
- routes[ii].append({'uni': uni,
- 'multi': multi})
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ VppMRoutePath(
+ self.pg2.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ VppMRoutePath(
+ self.pg3.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ ],
+ table_id=t.table_id,
+ ).add_vpp_config()
+ routes[ii].append({"uni": uni, "multi": multi})
#
# replace the tables a few times
@@ -2752,14 +2982,14 @@ class TestIP6Replace(VppTestCase):
dump = t.dump()
mdump = t.mdump()
for r in routes[ii]:
- self.assertTrue(find_route_in_dump(dump, r['uni'], t))
- self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t))
+ self.assertTrue(find_route_in_dump(dump, r["uni"], t))
+ self.assertTrue(find_mroute_in_dump(mdump, r["multi"], t))
# redownload the even numbered routes
for ii, t in enumerate(self.tables):
for jj in range(0, N_ROUTES, 2):
- routes[ii][jj]['uni'].add_vpp_config()
- routes[ii][jj]['multi'].add_vpp_config()
+ routes[ii][jj]["uni"].add_vpp_config()
+ routes[ii][jj]["multi"].add_vpp_config()
# signal each table converged
for t in self.tables:
@@ -2770,29 +3000,29 @@ class TestIP6Replace(VppTestCase):
dump = t.dump()
mdump = t.mdump()
for jj in range(0, N_ROUTES, 2):
- self.assertTrue(find_route_in_dump(
- dump, routes[ii][jj]['uni'], t))
- self.assertTrue(find_mroute_in_dump(
- mdump, routes[ii][jj]['multi'], t))
+ self.assertTrue(find_route_in_dump(dump, routes[ii][jj]["uni"], t))
+ self.assertTrue(
+ find_mroute_in_dump(mdump, routes[ii][jj]["multi"], t)
+ )
for jj in range(1, N_ROUTES - 1, 2):
- self.assertFalse(find_route_in_dump(
- dump, routes[ii][jj]['uni'], t))
- self.assertFalse(find_mroute_in_dump(
- mdump, routes[ii][jj]['multi'], t))
+ self.assertFalse(find_route_in_dump(dump, routes[ii][jj]["uni"], t))
+ self.assertFalse(
+ find_mroute_in_dump(mdump, routes[ii][jj]["multi"], t)
+ )
# reload all the routes
for ii, t in enumerate(self.tables):
for r in routes[ii]:
- r['uni'].add_vpp_config()
- r['multi'].add_vpp_config()
+ r["uni"].add_vpp_config()
+ r["multi"].add_vpp_config()
# all the routes are still there
for ii, t in enumerate(self.tables):
dump = t.dump()
mdump = t.mdump()
for r in routes[ii]:
- self.assertTrue(find_route_in_dump(dump, r['uni'], t))
- self.assertTrue(find_mroute_in_dump(mdump, r['multi'], t))
+ self.assertTrue(find_route_in_dump(dump, r["uni"], t))
+ self.assertTrue(find_mroute_in_dump(mdump, r["multi"], t))
#
# finally flush the tables for good measure
@@ -2804,7 +3034,7 @@ class TestIP6Replace(VppTestCase):
class TestIP6AddrReplace(VppTestCase):
- """ IPv6 Interface Address Replace """
+ """IPv6 Interface Address Replace"""
@classmethod
def setUpClass(cls):
@@ -2831,7 +3061,7 @@ class TestIP6AddrReplace(VppTestCase):
return len(self.vapi.ip_address_dump(intf.sw_if_index, True))
def test_replace(self):
- """ IP interface address replace """
+ """IP interface address replace"""
intf_pfxs = [[], [], [], []]
@@ -2915,8 +3145,7 @@ class TestIP6AddrReplace(VppTestCase):
for intf in self.pg_interfaces:
# 2001:18:x::1/64
addr = "2001:18:%d::1" % intf.sw_if_index
- pfxs.append(VppIpInterfaceAddress(self, intf, addr,
- 64).add_vpp_config())
+ pfxs.append(VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config())
self.vapi.sw_interface_address_replace_end()
@@ -2951,8 +3180,7 @@ class TestIP6AddrReplace(VppTestCase):
for intf in self.pg_interfaces:
# 2001:18:x::1/64
addr = "2001:18:%d::1" % (intf.sw_if_index + 1)
- pfxs.append(VppIpInterfaceAddress(self, intf,
- addr, 64).add_vpp_config())
+ pfxs.append(VppIpInterfaceAddress(self, intf, addr, 64).add_vpp_config())
self.vapi.sw_interface_address_replace_end()
@@ -2965,7 +3193,7 @@ class TestIP6AddrReplace(VppTestCase):
class TestIP6LinkLocal(VppTestCase):
- """ IPv6 Link Local """
+ """IPv6 Link Local"""
@classmethod
def setUpClass(cls):
@@ -2989,7 +3217,7 @@ class TestIP6LinkLocal(VppTestCase):
i.admin_down()
def test_ip6_ll(self):
- """ IPv6 Link Local """
+ """IPv6 Link Local"""
#
# two APIs to add a link local address.
@@ -3004,35 +3232,33 @@ class TestIP6LinkLocal(VppTestCase):
ll2 = "fe80:2::2"
ll3 = "fe80:3::3"
- VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_mac,
- ll2).add_vpp_config()
+ VppNeighbor(
+ self, self.pg0.sw_if_index, self.pg0.remote_mac, ll2
+ ).add_vpp_config()
VppIpInterfaceAddress(self, self.pg0, ll1, 128).add_vpp_config()
#
# should be able to ping the ll
#
- p_echo_request_1 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=ll2,
- dst=ll1) /
- ICMPv6EchoRequest())
+ p_echo_request_1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=ll2, dst=ll1)
+ / ICMPv6EchoRequest()
+ )
self.send_and_expect(self.pg0, [p_echo_request_1], self.pg0)
#
# change the link-local on pg0
#
- v_ll3 = VppIpInterfaceAddress(self, self.pg0,
- ll3, 128).add_vpp_config()
+ v_ll3 = VppIpInterfaceAddress(self, self.pg0, ll3, 128).add_vpp_config()
- p_echo_request_3 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=ll2,
- dst=ll3) /
- ICMPv6EchoRequest())
+ p_echo_request_3 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=ll2, dst=ll3)
+ / ICMPv6EchoRequest()
+ )
self.send_and_expect(self.pg0, [p_echo_request_3], self.pg0)
@@ -3057,13 +3283,13 @@ class TestIP6LinkLocal(VppTestCase):
self.send_and_expect(self.pg1, [p_echo_request_3], self.pg1)
def test_ip6_ll_p2p(self):
- """ IPv6 Link Local P2P (GRE)"""
+ """IPv6 Link Local P2P (GRE)"""
self.pg0.config_ip4()
self.pg0.resolve_arp()
- gre_if = VppGreInterface(self,
- self.pg0.local_ip4,
- self.pg0.remote_ip4).add_vpp_config()
+ gre_if = VppGreInterface(
+ self, self.pg0.local_ip4, self.pg0.remote_ip4
+ ).add_vpp_config()
gre_if.admin_up()
ll1 = "fe80:1::1"
@@ -3073,20 +3299,20 @@ class TestIP6LinkLocal(VppTestCase):
self.logger.info(self.vapi.cli("sh ip6-ll gre0 fe80:2::2"))
- p_echo_request_1 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg0.local_ip4) /
- GRE() /
- IPv6(src=ll2, dst=ll1) /
- ICMPv6EchoRequest())
+ p_echo_request_1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / GRE()
+ / IPv6(src=ll2, dst=ll1)
+ / ICMPv6EchoRequest()
+ )
self.send_and_expect(self.pg0, [p_echo_request_1], self.pg0)
self.pg0.unconfig_ip4()
gre_if.remove_vpp_config()
def test_ip6_ll_p2mp(self):
- """ IPv6 Link Local P2MP (GRE)"""
+ """IPv6 Link Local P2MP (GRE)"""
self.pg0.config_ip4()
self.pg0.resolve_arp()
@@ -3095,8 +3321,8 @@ class TestIP6LinkLocal(VppTestCase):
self,
self.pg0.local_ip4,
"0.0.0.0",
- mode=(VppEnum.vl_api_tunnel_mode_t.
- TUNNEL_API_MODE_MP)).add_vpp_config()
+ mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP),
+ ).add_vpp_config()
gre_if.admin_up()
ll1 = "fe80:1::1"
@@ -3104,13 +3330,13 @@ class TestIP6LinkLocal(VppTestCase):
VppIpInterfaceAddress(self, gre_if, ll1, 128).add_vpp_config()
- p_echo_request_1 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg0.local_ip4) /
- GRE() /
- IPv6(src=ll2, dst=ll1) /
- ICMPv6EchoRequest())
+ p_echo_request_1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / GRE()
+ / IPv6(src=ll2, dst=ll1)
+ / ICMPv6EchoRequest()
+ )
# no route back at this point
self.send_and_assert_no_replies(self.pg0, [p_echo_request_1])
@@ -3127,7 +3353,7 @@ class TestIP6LinkLocal(VppTestCase):
class TestIPv6PathMTU(VppTestCase):
- """ IPv6 Path MTU """
+ """IPv6 Path MTU"""
def setUp(self):
super(TestIPv6PathMTU, self).setUp()
@@ -3147,7 +3373,7 @@ class TestIPv6PathMTU(VppTestCase):
i.admin_down()
def test_path_mtu_local(self):
- """ Path MTU for attached neighbour """
+ """Path MTU for attached neighbour"""
self.vapi.cli("set log class ip level debug")
#
@@ -3161,41 +3387,37 @@ class TestIPv6PathMTU(VppTestCase):
# packets post encap
#
tun = VppIpIpTunInterface(
- self,
- self.pg1,
- self.pg1.local_ip6,
- self.pg1.remote_ip6)
+ self, self.pg1, self.pg1.local_ip6, self.pg1.remote_ip6
+ )
tun.add_vpp_config()
tun.admin_up()
tun.config_ip6()
# set the interface MTU to a reasonable value
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [2800, 0, 0, 0])
-
- p_6k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=tun.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 2000))
- p_2k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=tun.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 1000))
- p_1k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=tun.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 600))
-
- nbr = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_mac,
- self.pg1.remote_ip6).add_vpp_config()
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2800, 0, 0, 0])
+
+ p_6k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 2000)
+ )
+ p_2k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 1000)
+ )
+ p_1k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 600)
+ )
+
+ nbr = VppNeighbor(
+ self, self.pg1.sw_if_index, self.pg1.remote_mac, self.pg1.remote_ip6
+ ).add_vpp_config()
# this is now the interface MTU frags
self.send_and_expect(self.pg0, [p_6k], self.pg1, n_rx=4)
@@ -3228,28 +3450,25 @@ class TestIPv6PathMTU(VppTestCase):
# raise the interface's MTU
# should still use that of the path
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [2000, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2000, 0, 0, 0])
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
# set path high and interface low
pmtu.modify(2000)
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [1300, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1300, 0, 0, 0])
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
# remove the path MTU
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [2800, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2800, 0, 0, 0])
pmtu.modify(0)
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2)
self.send_and_expect(self.pg0, [p_1k], self.pg1)
def test_path_mtu_remote(self):
- """ Path MTU for remote neighbour """
+ """Path MTU for remote neighbour"""
self.vapi.cli("set log class ip level debug")
#
@@ -3260,44 +3479,37 @@ class TestIPv6PathMTU(VppTestCase):
tun_dst = "2001::1"
route = VppIpRoute(
- self, tun_dst, 64,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)]).add_vpp_config()
+ self, tun_dst, 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)]
+ ).add_vpp_config()
#
# IPv6 will only frag locally generated packets, so use tunnelled
# packets post encap
#
- tun = VppIpIpTunInterface(
- self,
- self.pg1,
- self.pg1.local_ip6,
- tun_dst)
+ tun = VppIpIpTunInterface(self, self.pg1, self.pg1.local_ip6, tun_dst)
tun.add_vpp_config()
tun.admin_up()
tun.config_ip6()
# set the interface MTU to a reasonable value
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [2800, 0, 0, 0])
-
- p_2k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=tun.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 1000))
- p_1k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=tun.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 600))
-
- nbr = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_mac,
- self.pg1.remote_ip6).add_vpp_config()
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2800, 0, 0, 0])
+
+ p_2k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 1000)
+ )
+ p_1k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 600)
+ )
+
+ nbr = VppNeighbor(
+ self, self.pg1.sw_if_index, self.pg1.remote_mac, self.pg1.remote_ip6
+ ).add_vpp_config()
# this is now the interface MTU frags
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2)
@@ -3328,44 +3540,38 @@ class TestIPv6PathMTU(VppTestCase):
# raise the interface's MTU
# should still use that of the path
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [2000, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2000, 0, 0, 0])
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
# turn the tun_dst into an attached neighbour
- route.modify([VppRoutePath("::",
- self.pg1.sw_if_index)])
- nbr2 = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_mac,
- tun_dst).add_vpp_config()
+ route.modify([VppRoutePath("::", self.pg1.sw_if_index)])
+ nbr2 = VppNeighbor(
+ self, self.pg1.sw_if_index, self.pg1.remote_mac, tun_dst
+ ).add_vpp_config()
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
# add back to not attached
nbr2.remove_vpp_config()
- route.modify([VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ route.modify([VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)])
# set path high and interface low
pmtu.modify(2000)
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [1300, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [1300, 0, 0, 0])
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=3)
self.send_and_expect(self.pg0, [p_1k], self.pg1, n_rx=2)
# remove the path MTU
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [2800, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2800, 0, 0, 0])
pmtu.remove_vpp_config()
self.send_and_expect(self.pg0, [p_2k], self.pg1, n_rx=2)
self.send_and_expect(self.pg0, [p_1k], self.pg1)
class TestIPFibSource(VppTestCase):
- """ IPv6 Table FibSource """
+ """IPv6 Table FibSource"""
@classmethod
def setUpClass(cls):
@@ -3394,7 +3600,7 @@ class TestIPFibSource(VppTestCase):
i.unconfig_ip4()
def test_fib_source(self):
- """ IP Table FibSource """
+ """IP Table FibSource"""
routes = self.vapi.ip_route_v2_dump(0, True)
@@ -3404,15 +3610,15 @@ class TestIPFibSource(VppTestCase):
# dump all the sources in the FIB
sources = self.vapi.fib_source_dump()
for source in sources:
- if (source.src.name == "API"):
+ if source.src.name == "API":
api_source = source.src
- if (source.src.name == "interface"):
+ if source.src.name == "interface":
intf_source = source.src
- if (source.src.name == "adjacency"):
+ if source.src.name == "adjacency":
adj_source = source.src
- if (source.src.name == "special"):
+ if source.src.name == "special":
special_source = source.src
- if (source.src.name == "default-route"):
+ if source.src.name == "default-route":
dr_source = source.src
# dump the individual route types
@@ -3426,37 +3632,43 @@ class TestIPFibSource(VppTestCase):
self.assertEqual(len(routes), 1)
# add a new soure that'a better than the API
- self.vapi.fib_source_add(src={'name': "bgp",
- "priority": api_source.priority - 1})
+ self.vapi.fib_source_add(
+ src={"name": "bgp", "priority": api_source.priority - 1}
+ )
# dump all the sources to check our new one is there
sources = self.vapi.fib_source_dump()
for source in sources:
- if (source.src.name == "bgp"):
+ if source.src.name == "bgp":
bgp_source = source.src
self.assertTrue(bgp_source)
- self.assertEqual(bgp_source.priority,
- api_source.priority - 1)
+ self.assertEqual(bgp_source.priority, api_source.priority - 1)
# add a route with the default API source
r1 = VppIpRouteV2(
- self, "2001::1", 128,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index)]).add_vpp_config()
+ self,
+ "2001::1",
+ 128,
+ [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)],
+ ).add_vpp_config()
- r2 = VppIpRouteV2(self, "2001::1", 128,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)],
- src=bgp_source.id).add_vpp_config()
+ r2 = VppIpRouteV2(
+ self,
+ "2001::1",
+ 128,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ src=bgp_source.id,
+ ).add_vpp_config()
# ensure the BGP source takes priority
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst="2001::1") /
- inet6.UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst="2001::1")
+ / inet6.UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect(self.pg0, [p], self.pg1)
@@ -3467,7 +3679,7 @@ class TestIPFibSource(VppTestCase):
class TestIPxAF(VppTestCase):
- """ IP cross AF """
+ """IP cross AF"""
@classmethod
def setUpClass(cls):
@@ -3497,20 +3709,23 @@ class TestIPxAF(VppTestCase):
i.unconfig_ip6()
def test_x_af(self):
- """ Cross AF routing """
+ """Cross AF routing"""
N_PKTS = 63
# a v4 route via a v6 attached next-hop
VppIpRoute(
- self, "1.1.1.1", 32,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)]).add_vpp_config()
-
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst="1.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ self,
+ "1.1.1.1",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ ).add_vpp_config()
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst="1.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1)
for rx in rxs:
@@ -3518,15 +3733,18 @@ class TestIPxAF(VppTestCase):
# a v6 route via a v4 attached next-hop
VppIpRoute(
- self, "2001::1", 128,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)]).add_vpp_config()
-
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst="2001::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ self,
+ "2001::1",
+ 128,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ ).add_vpp_config()
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst="2001::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1)
for rx in rxs:
@@ -3534,56 +3752,56 @@ class TestIPxAF(VppTestCase):
# a recursive v4 route via a v6 next-hop (from above)
VppIpRoute(
- self, "2.2.2.2", 32,
- [VppRoutePath("2001::1",
- 0xffffffff)]).add_vpp_config()
-
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst="2.2.2.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ self, "2.2.2.2", 32, [VppRoutePath("2001::1", 0xFFFFFFFF)]
+ ).add_vpp_config()
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst="2.2.2.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1)
# a recursive v4 route via a v6 next-hop
VppIpRoute(
- self, "2.2.2.3", 32,
- [VppRoutePath(self.pg1.remote_ip6,
- 0xffffffff)]).add_vpp_config()
-
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst="2.2.2.3") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ self, "2.2.2.3", 32, [VppRoutePath(self.pg1.remote_ip6, 0xFFFFFFFF)]
+ ).add_vpp_config()
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst="2.2.2.3")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1)
# a recursive v6 route via a v4 next-hop
VppIpRoute(
- self, "3001::1", 128,
- [VppRoutePath(self.pg1.remote_ip4,
- 0xffffffff)]).add_vpp_config()
-
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst="3001::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ self, "3001::1", 128, [VppRoutePath(self.pg1.remote_ip4, 0xFFFFFFFF)]
+ ).add_vpp_config()
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst="3001::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1)
for rx in rxs:
self.assertEqual(rx[IPv6].dst, "3001::1")
VppIpRoute(
- self, "3001::2", 128,
- [VppRoutePath("1.1.1.1",
- 0xffffffff)]).add_vpp_config()
-
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst="3001::2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ self, "3001::2", 128, [VppRoutePath("1.1.1.1", 0xFFFFFFFF)]
+ ).add_vpp_config()
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst="3001::2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1)
for rx in rxs:
@@ -3591,7 +3809,7 @@ class TestIPxAF(VppTestCase):
class TestIPv6Punt(VppTestCase):
- """ IPv6 Punt Police/Redirect """
+ """IPv6 Punt Police/Redirect"""
def setUp(self):
super(TestIPv6Punt, self).setUp()
@@ -3609,7 +3827,7 @@ class TestIPv6Punt(VppTestCase):
i.admin_down()
def test_ip6_punt(self):
- """ IPv6 punt police and redirect """
+ """IPv6 punt police and redirect"""
# use UDP packet that have a port we need to explicitly
# register to get punted.
@@ -3617,30 +3835,32 @@ class TestIPv6Punt(VppTestCase):
af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6
udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP
punt_udp = {
- 'type': pt_l4,
- 'punt': {
- 'l4': {
- 'af': af_ip6,
- 'protocol': udp_proto,
- 'port': 7654,
+ "type": pt_l4,
+ "punt": {
+ "l4": {
+ "af": af_ip6,
+ "protocol": udp_proto,
+ "port": 7654,
}
- }
+ },
}
self.vapi.set_punt(is_add=1, punt=punt_udp)
- pkts = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- UDP(sport=1234, dport=7654) /
- Raw(b'\xa5' * 100)) * 1025
+ pkts = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / UDP(sport=1234, dport=7654)
+ / Raw(b"\xa5" * 100)
+ ) * 1025
#
# Configure a punt redirect via pg1.
#
nh_addr = self.pg1.remote_ip6
- ip_punt_redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index,
- self.pg1.sw_if_index, nh_addr)
+ ip_punt_redirect = VppIpPuntRedirect(
+ self, self.pg0.sw_if_index, self.pg1.sw_if_index, nh_addr
+ )
ip_punt_redirect.add_vpp_config()
self.send_and_expect(self.pg0, pkts, self.pg1)
@@ -3650,8 +3870,7 @@ class TestIPv6Punt(VppTestCase):
#
policer = VppPolicer(self, "ip6-punt", 400, 0, 10, 0, rate_type=1)
policer.add_vpp_config()
- ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index,
- is_ip6=True)
+ ip_punt_policer = VppIpPuntPolicer(self, policer.policer_index, is_ip6=True)
ip_punt_policer.add_vpp_config()
self.vapi.cli("clear trace")
@@ -3668,9 +3887,9 @@ class TestIPv6Punt(VppTestCase):
stats = policer.get_stats()
# Single rate policer - expect conform, violate but no exceed
- self.assertGreater(stats['conform_packets'], 0)
- self.assertEqual(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ self.assertGreater(stats["conform_packets"], 0)
+ self.assertEqual(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
self.assertGreater(len(rx), 0)
self.assertLess(len(rx), len(pkts))
@@ -3686,31 +3905,34 @@ class TestIPv6Punt(VppTestCase):
# remove the redirect. expect full drop.
#
ip_punt_redirect.remove_vpp_config()
- self.send_and_assert_no_replies(self.pg0, pkts,
- "IP no punt config")
+ self.send_and_assert_no_replies(self.pg0, pkts, "IP no punt config")
#
# Add a redirect that is not input port selective
#
- ip_punt_redirect = VppIpPuntRedirect(self, 0xffffffff,
- self.pg1.sw_if_index, nh_addr)
+ ip_punt_redirect = VppIpPuntRedirect(
+ self, 0xFFFFFFFF, self.pg1.sw_if_index, nh_addr
+ )
ip_punt_redirect.add_vpp_config()
self.send_and_expect(self.pg0, pkts, self.pg1)
ip_punt_redirect.remove_vpp_config()
def test_ip6_punt_dump(self):
- """ IPv6 punt redirect dump"""
+ """IPv6 punt redirect dump"""
#
# Configure a punt redirects
#
nh_address = self.pg3.remote_ip6
- ipr_03 = VppIpPuntRedirect(self, self.pg0.sw_if_index,
- self.pg3.sw_if_index, nh_address)
- ipr_13 = VppIpPuntRedirect(self, self.pg1.sw_if_index,
- self.pg3.sw_if_index, nh_address)
- ipr_23 = VppIpPuntRedirect(self, self.pg2.sw_if_index,
- self.pg3.sw_if_index, "::")
+ ipr_03 = VppIpPuntRedirect(
+ self, self.pg0.sw_if_index, self.pg3.sw_if_index, nh_address
+ )
+ ipr_13 = VppIpPuntRedirect(
+ self, self.pg1.sw_if_index, self.pg3.sw_if_index, nh_address
+ )
+ ipr_23 = VppIpPuntRedirect(
+ self, self.pg2.sw_if_index, self.pg3.sw_if_index, "::"
+ )
ipr_03.add_vpp_config()
ipr_13.add_vpp_config()
ipr_23.add_vpp_config()
@@ -3725,14 +3947,13 @@ class TestIPv6Punt(VppTestCase):
#
# Dump punt redirects for all interfaces
#
- punts = self.vapi.ip_punt_redirect_dump(sw_if_index=0xffffffff,
- is_ipv6=True)
+ punts = self.vapi.ip_punt_redirect_dump(sw_if_index=0xFFFFFFFF, is_ipv6=True)
self.assertEqual(len(punts), 3)
for p in punts:
self.assertEqual(p.punt.tx_sw_if_index, self.pg3.sw_if_index)
self.assertNotEqual(punts[1].punt.nh, self.pg3.remote_ip6)
- self.assertEqual(str(punts[2].punt.nh), '::')
+ self.assertEqual(str(punts[2].punt.nh), "::")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ip6_nd_mirror_proxy.py b/test/test_ip6_nd_mirror_proxy.py
index fa9880122fc..9214e32b447 100644
--- a/test/test_ip6_nd_mirror_proxy.py
+++ b/test/test_ip6_nd_mirror_proxy.py
@@ -7,8 +7,15 @@ from socket import AF_INET6, inet_pton, inet_ntop
from framework import tag_fixme_vpp_workers
from framework import VppTestCase, VppTestRunner
from vpp_neighbor import VppNeighbor, find_nbr
-from vpp_ip_route import VppIpRoute, VppRoutePath, find_route, \
- VppIpTable, DpoProto, FibPathType, VppIpInterfaceAddress
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ find_route,
+ VppIpTable,
+ DpoProto,
+ FibPathType,
+ VppIpInterfaceAddress,
+)
from vpp_papi import VppEnum
from vpp_ip import VppIpPuntRedirect
@@ -16,14 +23,21 @@ import scapy.compat
from scapy.packet import Raw
from scapy.layers.l2 import Ether, ARP, Dot1Q
from scapy.layers.inet import IP, UDP, TCP
-from scapy.layers.inet6 import IPv6, ipv6nh, ICMPv6ND_NS, ICMPv6ND_NA, \
- ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6EchoRequest, \
- ICMPv6EchoReply
+from scapy.layers.inet6 import (
+ IPv6,
+ ipv6nh,
+ ICMPv6ND_NS,
+ ICMPv6ND_NA,
+ ICMPv6NDOptSrcLLAddr,
+ ICMPv6NDOptDstLLAddr,
+ ICMPv6EchoRequest,
+ ICMPv6EchoReply,
+)
from scapy.utils6 import in6_ptop, in6_getnsma, in6_getnsmac, in6_ismaddr
class TestNDPROXY(VppTestCase):
- """ IP6 ND (mirror) Proxy Test Case """
+ """IP6 ND (mirror) Proxy Test Case"""
@classmethod
def setUpClass(self):
@@ -49,7 +63,7 @@ class TestNDPROXY(VppTestCase):
i.admin_down()
def test_nd_mirror_proxy(self):
- """ Interface (Mirror) Proxy ND """
+ """Interface (Mirror) Proxy ND"""
#
# When VPP has an interface whose address is also applied to a TAP
@@ -70,17 +84,19 @@ class TestNDPROXY(VppTestCase):
#
# Enable ND proxy on pg1
#
- self.vapi.ip6nd_proxy_enable_disable(sw_if_index=self.pg1.sw_if_index,
- is_enable=1)
+ self.vapi.ip6nd_proxy_enable_disable(
+ sw_if_index=self.pg1.sw_if_index, is_enable=1
+ )
#
# Send the ND request with an originating address that
# is VPP's own address
#
- nd_req_from_host = (Ether(src=self.pg1.remote_mac,
- dst=in6_getnsmac(nsma)) /
- IPv6(dst=d, src=self.pg0.local_ip6) /
- ICMPv6ND_NS(tgt=addr) /
- ICMPv6NDOptSrcLLAddr(lladdr=self.pg1.remote_mac))
+ nd_req_from_host = (
+ Ether(src=self.pg1.remote_mac, dst=in6_getnsmac(nsma))
+ / IPv6(dst=d, src=self.pg0.local_ip6)
+ / ICMPv6ND_NS(tgt=addr)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg1.remote_mac)
+ )
rx = self.send_and_expect(self.pg1, [nd_req_from_host], self.pg1)
self.assertEqual(rx[0][Ether].src, self.pg1.local_mac)
@@ -90,22 +106,19 @@ class TestNDPROXY(VppTestCase):
self.assertEqual(ipv6nh[rx[0][IPv6].nh], "ICMPv6")
self.assertEqual(rx[0][ICMPv6ND_NA].tgt, self.pg0.remote_ip6)
self.assertTrue(rx[0].haslayer(ICMPv6NDOptDstLLAddr))
- self.assertEqual(rx[0][ICMPv6NDOptDstLLAddr].lladdr,
- self.pg1.local_mac)
+ self.assertEqual(rx[0][ICMPv6NDOptDstLLAddr].lladdr, self.pg1.local_mac)
#
# Send the unicast ND request
#
- unicast_nd_req_from_host = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IPv6(dst=self.pg0.remote_ip6,
- src=self.pg1.remote_ip6_ll) /
- ICMPv6ND_NS(tgt=self.pg0.remote_ip6) /
- ICMPv6NDOptSrcLLAddr(
- lladdr=self.pg1.remote_mac))
+ unicast_nd_req_from_host = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IPv6(dst=self.pg0.remote_ip6, src=self.pg1.remote_ip6_ll)
+ / ICMPv6ND_NS(tgt=self.pg0.remote_ip6)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg1.remote_mac)
+ )
- rx = self.send_and_expect(self.pg1, [unicast_nd_req_from_host],
- self.pg0)
+ rx = self.send_and_expect(self.pg1, [unicast_nd_req_from_host], self.pg0)
self.assertEqual(rx[0][Ether].src, self.pg0.local_mac)
self.assertEqual(rx[0][Ether].dst, in6_getnsmac(nsma))
self.assertEqual(rx[0][IPv6].src, self.pg0.local_ip6)
@@ -113,8 +126,7 @@ class TestNDPROXY(VppTestCase):
self.assertEqual(ipv6nh[rx[0][IPv6].nh], "ICMPv6")
self.assertEqual(rx[0][ICMPv6ND_NS].tgt, self.pg0.remote_ip6)
self.assertTrue(rx[0].haslayer(ICMPv6NDOptSrcLLAddr))
- self.assertEqual(rx[0][ICMPv6NDOptSrcLLAddr].lladdr,
- self.pg0.local_mac)
+ self.assertEqual(rx[0][ICMPv6NDOptSrcLLAddr].lladdr, self.pg0.local_mac)
# Resolve the NDs on the uplink
self.pg0.resolve_ndp()
@@ -123,28 +135,26 @@ class TestNDPROXY(VppTestCase):
# Again send the unicast ND request, this time dst address should be
# in local cache
#
- rx = self.send_and_expect(self.pg1, [unicast_nd_req_from_host],
- self.pg1)
+ rx = self.send_and_expect(self.pg1, [unicast_nd_req_from_host], self.pg1)
self.assertEqual(rx[0][Ether].src, self.pg1.local_mac)
self.assertEqual(rx[0][Ether].dst, self.pg1.remote_mac)
self.assertEqual(rx[0][IPv6].src, self.pg0.remote_ip6)
- self.assertEqual(in6_ptop(rx[0][IPv6].dst),
- in6_ptop(self.pg1.remote_ip6_ll))
+ self.assertEqual(in6_ptop(rx[0][IPv6].dst), in6_ptop(self.pg1.remote_ip6_ll))
self.assertEqual(ipv6nh[rx[0][IPv6].nh], "ICMPv6")
self.assertEqual(rx[0][ICMPv6ND_NA].tgt, self.pg0.remote_ip6)
self.assertTrue(rx[0].haslayer(ICMPv6NDOptDstLLAddr))
- self.assertEqual(rx[0][ICMPv6NDOptDstLLAddr].lladdr,
- self.pg1.local_mac)
+ self.assertEqual(rx[0][ICMPv6NDOptDstLLAddr].lladdr, self.pg1.local_mac)
#
# Send the Echo Request from host to remote (of uplink)
#
id = self.pg1.sw_if_index
seq = 0x1
- echo_request = (Ether(dst=self.pg1.local_mac,
- src=self.pg1.remote_mac) /
- IPv6(dst=self.pg0.remote_ip6, src=self.pg0.local_ip6) /
- ICMPv6EchoRequest(seq=seq, id=id))
+ echo_request = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(dst=self.pg0.remote_ip6, src=self.pg0.local_ip6)
+ / ICMPv6EchoRequest(seq=seq, id=id)
+ )
rx = self.send_and_expect(self.pg1, [echo_request], self.pg0)
self.assertEqual(rx[0][Ether].src, self.pg0.local_mac)
@@ -159,13 +169,16 @@ class TestNDPROXY(VppTestCase):
#
# setup a punt redirect so packets from the uplink go to the tap
#
- redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index,
- self.pg1.sw_if_index, self.pg0.local_ip6)
+ redirect = VppIpPuntRedirect(
+ self, self.pg0.sw_if_index, self.pg1.sw_if_index, self.pg0.local_ip6
+ )
redirect.add_vpp_config()
- echo_reply = (Ether(dst=self.pg0.remote_mac, src=self.pg0.local_mac) /
- IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6) /
- ICMPv6EchoReply(seq=1, id=id))
+ echo_reply = (
+ Ether(dst=self.pg0.remote_mac, src=self.pg0.local_mac)
+ / IPv6(dst=self.pg0.local_ip6, src=self.pg0.remote_ip6)
+ / ICMPv6EchoReply(seq=1, id=id)
+ )
rx = self.send_and_expect(self.pg0, [echo_reply], self.pg1)
self.assertEqual(rx[0][Ether].src, self.pg1.local_mac)
@@ -180,9 +193,11 @@ class TestNDPROXY(VppTestCase):
#
# cleanup
#
- self.vapi.ip6nd_proxy_enable_disable(sw_if_index=self.pg1.sw_if_index,
- is_enable=0)
+ self.vapi.ip6nd_proxy_enable_disable(
+ sw_if_index=self.pg1.sw_if_index, is_enable=0
+ )
redirect.remove_vpp_config()
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ip6_vrf_multi_instance.py b/test/test_ip6_vrf_multi_instance.py
index d95e7927f98..73df30d77f2 100644
--- a/test/test_ip6_vrf_multi_instance.py
+++ b/test/test_ip6_vrf_multi_instance.py
@@ -69,8 +69,14 @@ import socket
from scapy.packet import Raw
from scapy.layers.l2 import Ether
-from scapy.layers.inet6 import UDP, IPv6, ICMPv6ND_NS, ICMPv6ND_RA, \
- RouterAlert, IPv6ExtHdrHopByHop
+from scapy.layers.inet6 import (
+ UDP,
+ IPv6,
+ ICMPv6ND_NS,
+ ICMPv6ND_RA,
+ RouterAlert,
+ IPv6ExtHdrHopByHop,
+)
from scapy.utils6 import in6_ismaddr, in6_isllsnmaddr, in6_getAddrType
from scapy.pton_ntop import inet_ntop
@@ -80,8 +86,8 @@ from vrf import VRFState
def is_ipv6_misc_ext(p):
- """ Is packet one of uninteresting IPv6 broadcasts (extended to filter out
- ICMPv6 Neighbor Discovery - Neighbor Advertisement packets too)? """
+ """Is packet one of uninteresting IPv6 broadcasts (extended to filter out
+ ICMPv6 Neighbor Discovery - Neighbor Advertisement packets too)?"""
if p.haslayer(ICMPv6ND_RA):
if in6_ismaddr(p[IPv6].dst):
return True
@@ -96,7 +102,7 @@ def is_ipv6_misc_ext(p):
class TestIP6VrfMultiInst(VppTestCase):
- """ IP6 VRF Multi-instance Test Case """
+ """IP6 VRF Multi-instance Test Case"""
@classmethod
def setUpClass(cls):
@@ -114,8 +120,7 @@ class TestIP6VrfMultiInst(VppTestCase):
try:
# Create pg interfaces
- cls.create_pg_interfaces(
- range(cls.nr_of_vrfs * cls.pg_ifs_per_vrf))
+ cls.create_pg_interfaces(range(cls.nr_of_vrfs * cls.pg_ifs_per_vrf))
# Packet flows mapping pg0 -> pg1, pg2 etc.
cls.flows = dict()
@@ -124,7 +129,8 @@ class TestIP6VrfMultiInst(VppTestCase):
pg_list = [
cls.pg_interfaces[multiplicand * cls.pg_ifs_per_vrf + j]
for j in range(cls.pg_ifs_per_vrf)
- if (multiplicand * cls.pg_ifs_per_vrf + j) != i]
+ if (multiplicand * cls.pg_ifs_per_vrf + j) != i
+ ]
cls.flows[cls.pg_interfaces[i]] = pg_list
# Packet sizes - jumbo packet (9018 bytes) skipped
@@ -153,7 +159,8 @@ class TestIP6VrfMultiInst(VppTestCase):
set_id = i + 1
pg_list = [
cls.pg_interfaces[i * cls.pg_ifs_per_vrf + j]
- for j in range(cls.pg_ifs_per_vrf)]
+ for j in range(cls.pg_ifs_per_vrf)
+ ]
cls.pg_if_sets[set_id] = pg_list
except Exception:
@@ -185,8 +192,9 @@ class TestIP6VrfMultiInst(VppTestCase):
for i in range(self.pg_ifs_per_vrf):
pg_if = self.pg_if_sets[if_set_id][i]
pg_if.set_table_ip6(vrf_id)
- self.logger.info("pg-interface %s added to IPv6 VRF ID %d"
- % (pg_if.name, vrf_id))
+ self.logger.info(
+ "pg-interface %s added to IPv6 VRF ID %d" % (pg_if.name, vrf_id)
+ )
if pg_if not in self.pg_in_vrf:
self.pg_in_vrf.append(pg_if)
if pg_if in self.pg_not_in_vrf:
@@ -206,8 +214,9 @@ class TestIP6VrfMultiInst(VppTestCase):
"""
for i in range(count):
vrf_id = i + start
- self.vapi.ip_table_add_del(is_add=1,
- table={'table_id': vrf_id, 'is_ip6': 1})
+ self.vapi.ip_table_add_del(
+ is_add=1, table={"table_id": vrf_id, "is_ip6": 1}
+ )
self.logger.info("IPv6 VRF ID %d created" % vrf_id)
if vrf_id not in self.vrf_list:
self.vrf_list.append(vrf_id)
@@ -217,8 +226,7 @@ class TestIP6VrfMultiInst(VppTestCase):
self.logger.debug(self.vapi.ppcli("show ip6 fib"))
self.logger.debug(self.vapi.ppcli("show ip6 neighbors"))
- def create_vrf_by_id_and_assign_interfaces(self, set_id,
- vrf_id=0xffffffff):
+ def create_vrf_by_id_and_assign_interfaces(self, set_id, vrf_id=0xFFFFFFFF):
"""
Create a FIB table / VRF by vrf_id, put 3 pg-ip6 interfaces
to FIB table / VRF.
@@ -226,8 +234,7 @@ class TestIP6VrfMultiInst(VppTestCase):
:param int vrf_id: Required table ID / VRF ID. \
(Default value = 0xffffffff, ID will be selected automatically)
"""
- ret = self.vapi.ip_table_allocate(table={'table_id': vrf_id,
- 'is_ip6': 1})
+ ret = self.vapi.ip_table_allocate(table={"table_id": vrf_id, "is_ip6": 1})
vrf_id = ret.table.table_id
self.logger.info("IPv6 VRF ID %d created" % vrf_id)
if vrf_id not in self.vrf_list:
@@ -248,7 +255,7 @@ class TestIP6VrfMultiInst(VppTestCase):
"""
if if_set_id is None:
if_set_id = vrf_id
- self.vapi.ip_table_flush(table={'table_id': vrf_id, 'is_ip6': 1})
+ self.vapi.ip_table_flush(table={"table_id": vrf_id, "is_ip6": 1})
if vrf_id in self.vrf_list:
self.vrf_list.remove(vrf_id)
if vrf_id not in self.vrf_reset_list:
@@ -270,8 +277,7 @@ class TestIP6VrfMultiInst(VppTestCase):
self.vrf_list.remove(vrf_id)
if vrf_id in self.vrf_reset_list:
self.vrf_reset_list.remove(vrf_id)
- self.vapi.ip_table_add_del(is_add=0,
- table={'table_id': vrf_id, 'is_ip6': 1})
+ self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id, "is_ip6": 1})
def create_stream(self, src_if, packet_sizes):
"""
@@ -288,16 +294,20 @@ class TestIP6VrfMultiInst(VppTestCase):
src_host = random.choice(src_hosts)
pkt_info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(pkt_info)
- p = (Ether(dst=src_if.local_mac, src=src_host.mac) /
- IPv6(src=src_host.ip6, dst=dst_host.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_host.mac)
+ / IPv6(src=src_host.ip6, dst=dst_host.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
pkt_info.data = p.copy()
size = random.choice(packet_sizes)
self.extend_packet(p, size)
pkts.append(p)
- self.logger.debug("Input stream created for port %s. Length: %u pkt(s)"
- % (src_if.name, len(pkts)))
+ self.logger.debug(
+ "Input stream created for port %s. Length: %u pkt(s)"
+ % (src_if.name, len(pkts))
+ )
return pkts
def create_stream_crosswise_vrf(self, src_if, vrf_id, packet_sizes):
@@ -320,16 +330,20 @@ class TestIP6VrfMultiInst(VppTestCase):
src_host = random.choice(src_hosts)
pkt_info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(pkt_info)
- p = (Ether(dst=src_if.local_mac, src=src_host.mac) /
- IPv6(src=src_host.ip6, dst=dst_host.ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_host.mac)
+ / IPv6(src=src_host.ip6, dst=dst_host.ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
pkt_info.data = p.copy()
size = random.choice(packet_sizes)
self.extend_packet(p, size)
pkts.append(p)
- self.logger.debug("Input stream created for port %s. Length: %u pkt(s)"
- % (src_if.name, len(pkts)))
+ self.logger.debug(
+ "Input stream created for port %s. Length: %u pkt(s)"
+ % (src_if.name, len(pkts))
+ )
return pkts
def verify_capture(self, pg_if, capture):
@@ -350,11 +364,13 @@ class TestIP6VrfMultiInst(VppTestCase):
payload_info = self.payload_to_info(packet[Raw])
packet_index = payload_info.index
self.assertEqual(payload_info.dst, dst_sw_if_index)
- self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
- (pg_if.name, payload_info.src, packet_index))
+ self.logger.debug(
+ "Got packet on port %s: src=%u (id=%u)"
+ % (pg_if.name, payload_info.src, packet_index)
+ )
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertIsNotNone(next_info)
self.assertEqual(packet_index, next_info.index)
@@ -369,11 +385,13 @@ class TestIP6VrfMultiInst(VppTestCase):
raise
for i in self.pg_interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i, dst_sw_if_index, last_info[i.sw_if_index])
+ i, dst_sw_if_index, last_info[i.sw_if_index]
+ )
self.assertIsNone(
remaining_packet,
- "Port %u: Packet expected from source %u didn't arrive" %
- (dst_sw_if_index, i.sw_if_index))
+ "Port %u: Packet expected from source %u didn't arrive"
+ % (dst_sw_if_index, i.sw_if_index),
+ )
def verify_vrf(self, vrf_id, if_set_id=None):
"""
@@ -437,8 +455,9 @@ class TestIP6VrfMultiInst(VppTestCase):
capture = pg_if.get_capture(remark="interface is in VRF")
self.verify_capture(pg_if, capture)
elif pg_if in self.pg_not_in_vrf:
- pg_if.assert_nothing_captured(remark="interface is not in VRF",
- filter_out_fn=is_ipv6_misc_ext)
+ pg_if.assert_nothing_captured(
+ remark="interface is not in VRF", filter_out_fn=is_ipv6_misc_ext
+ )
self.logger.debug("No capture for interface %s" % pg_if.name)
else:
raise Exception("Unknown interface: %s" % pg_if.name)
@@ -458,7 +477,8 @@ class TestIP6VrfMultiInst(VppTestCase):
for vrf_id in self.vrf_list:
for pg_if in self.pg_if_sets[vrf_id]:
pkts = self.create_stream_crosswise_vrf(
- pg_if, vrf_id, self.pg_if_packet_sizes)
+ pg_if, vrf_id, self.pg_if_packet_sizes
+ )
pg_if.add_stream(pkts)
# Enable packet capture and start packet sending
@@ -468,29 +488,27 @@ class TestIP6VrfMultiInst(VppTestCase):
# Verify
# Verify outgoing packet streams per packet-generator interface
for pg_if in self.pg_interfaces:
- pg_if.assert_nothing_captured(remark="interface is in other VRF",
- filter_out_fn=is_ipv6_misc_ext)
+ pg_if.assert_nothing_captured(
+ remark="interface is in other VRF", filter_out_fn=is_ipv6_misc_ext
+ )
self.logger.debug("No capture for interface %s" % pg_if.name)
def test_ip6_vrf_01(self):
- """ IP6 VRF Multi-instance test 1 - create 4 VRFs
- """
+ """IP6 VRF Multi-instance test 1 - create 4 VRFs"""
# Config 1
# Create 4 VRFs
self.create_vrf_and_assign_interfaces(4)
# Verify 1
for vrf_id in self.vrf_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.configured, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState)
# Test 1
self.run_verify_test()
self.run_crosswise_vrf_test()
def test_ip6_vrf_02(self):
- """ IP6 VRF Multi-instance test 2 - reset 2 VRFs
- """
+ """IP6 VRF Multi-instance test 2 - reset 2 VRFs"""
# Config 2
# Delete 2 VRFs
self.reset_vrf_and_remove_from_vrf_list(1)
@@ -498,11 +516,9 @@ class TestIP6VrfMultiInst(VppTestCase):
# Verify 2
for vrf_id in self.vrf_reset_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.reset, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState)
for vrf_id in self.vrf_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.configured, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState)
# Test 2
self.run_verify_test()
@@ -513,8 +529,7 @@ class TestIP6VrfMultiInst(VppTestCase):
# self.reset_vrf_and_remove_from_vrf_list(vrf_id)
def test_ip6_vrf_03(self):
- """ IP6 VRF Multi-instance 3 - add 2 VRFs
- """
+ """IP6 VRF Multi-instance 3 - add 2 VRFs"""
# Config 3
# Add 1 of reset VRFs and 1 new VRF
self.create_vrf_and_assign_interfaces(1)
@@ -522,11 +537,9 @@ class TestIP6VrfMultiInst(VppTestCase):
# Verify 3
for vrf_id in self.vrf_reset_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.reset, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState)
for vrf_id in self.vrf_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.configured, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState)
# Test 3
self.run_verify_test()
@@ -537,8 +550,7 @@ class TestIP6VrfMultiInst(VppTestCase):
# self.reset_vrf_and_remove_from_vrf_list(vrf_id)
def test_ip6_vrf_04(self):
- """ IP6 VRF Multi-instance test 4 - reset 4 VRFs
- """
+ """IP6 VRF Multi-instance test 4 - reset 4 VRFs"""
# Config 4
# Reset all VRFs (i.e. no VRF except VRF=0 configured)
for i in range(len(self.vrf_list)):
@@ -547,20 +559,20 @@ class TestIP6VrfMultiInst(VppTestCase):
# Verify 4
for vrf_id in self.vrf_reset_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.reset, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState)
vrf_list_length = len(self.vrf_list)
self.assertEqual(
- vrf_list_length, 0,
- "List of configured VRFs is not empty: %s != 0" % vrf_list_length)
+ vrf_list_length,
+ 0,
+ "List of configured VRFs is not empty: %s != 0" % vrf_list_length,
+ )
# Test 4
self.run_verify_test()
self.run_crosswise_vrf_test()
def test_ip6_vrf_05(self):
- """ IP6 VRF Multi-instance test 5 - auto allocate vrf id
- """
+ """IP6 VRF Multi-instance test 5 - auto allocate vrf id"""
# Config 5
# Create several VRFs
# Set vrf_id manually first
@@ -571,11 +583,11 @@ class TestIP6VrfMultiInst(VppTestCase):
]
# Verify 5
- self.assert_equal(self.verify_vrf(10, 1), VRFState.configured,
- VRFState)
+ self.assert_equal(self.verify_vrf(10, 1), VRFState.configured, VRFState)
for i, vrf in enumerate(auto_vrf_id):
- self.assert_equal(self.verify_vrf(vrf, i+2),
- VRFState.configured, VRFState)
+ self.assert_equal(
+ self.verify_vrf(vrf, i + 2), VRFState.configured, VRFState
+ )
# Test 5
self.run_verify_test()
@@ -584,18 +596,19 @@ class TestIP6VrfMultiInst(VppTestCase):
# Reset VRFs
self.reset_vrf_and_remove_from_vrf_list(10, 1)
for i, vrf in enumerate(auto_vrf_id):
- self.reset_vrf_and_remove_from_vrf_list(vrf, i+2)
+ self.reset_vrf_and_remove_from_vrf_list(vrf, i + 2)
# Verify 5.1
self.assert_equal(self.verify_vrf(10, 1), VRFState.reset, VRFState)
for i, vrf in enumerate(auto_vrf_id):
- self.assert_equal(self.verify_vrf(vrf, i+2),
- VRFState.reset, VRFState)
+ self.assert_equal(self.verify_vrf(vrf, i + 2), VRFState.reset, VRFState)
vrf_list_length = len(self.vrf_list)
self.assertEqual(
- vrf_list_length, 0,
- "List of configured VRFs is not empty: %s != 0" % vrf_list_length)
+ vrf_list_length,
+ 0,
+ "List of configured VRFs is not empty: %s != 0" % vrf_list_length,
+ )
# Cleanup our extra created VRFs
for vrf in auto_vrf_id:
@@ -604,14 +617,12 @@ class TestIP6VrfMultiInst(VppTestCase):
self.delete_vrf(10)
def test_ip6_vrf_06(self):
- """ IP6 VRF Multi-instance test 6 - recreate 4 VRFs
- """
+ """IP6 VRF Multi-instance test 6 - recreate 4 VRFs"""
# Reconfigure all the VRFs
self.create_vrf_and_assign_interfaces(4)
# Verify
for vrf_id in self.vrf_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.configured, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.configured, VRFState)
# Test
self.run_verify_test()
self.run_crosswise_vrf_test()
@@ -620,16 +631,17 @@ class TestIP6VrfMultiInst(VppTestCase):
self.reset_vrf_and_remove_from_vrf_list(self.vrf_list[0])
# Verify
for vrf_id in self.vrf_reset_list:
- self.assert_equal(self.verify_vrf(vrf_id),
- VRFState.reset, VRFState)
+ self.assert_equal(self.verify_vrf(vrf_id), VRFState.reset, VRFState)
vrf_list_length = len(self.vrf_list)
self.assertEqual(
- vrf_list_length, 0,
- "List of configured VRFs is not empty: %s != 0" % vrf_list_length)
+ vrf_list_length,
+ 0,
+ "List of configured VRFs is not empty: %s != 0" % vrf_list_length,
+ )
# Test
self.run_verify_test()
self.run_crosswise_vrf_test()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ip_ecmp.py b/test/test_ip_ecmp.py
index 1d3e872e45e..d5347db2530 100644
--- a/test/test_ip_ecmp.py
+++ b/test/test_ip_ecmp.py
@@ -26,7 +26,7 @@ N_PKTS_IN_STREAM = 300
class TestECMP(VppTestCase):
- """ Equal-cost multi-path routing Test Case """
+ """Equal-cost multi-path routing Test Case"""
@classmethod
def setUpClass(cls):
@@ -92,11 +92,11 @@ class TestECMP(VppTestCase):
ip_addr = IPv6Address(text_type(ip_addr_start))
ip_max_len = 128
- return str(ip_addr +
- random.randint(0, 2 ** (ip_max_len - ip_prefix_len) - 2))
+ return str(ip_addr + random.randint(0, 2 ** (ip_max_len - ip_prefix_len) - 2))
- def create_stream(self, src_if, src_ip_start, dst_ip_start,
- ip_prefix_len, packet_sizes, ip_l=IP):
+ def create_stream(
+ self, src_if, src_ip_start, dst_ip_start, ip_prefix_len, packet_sizes, ip_l=IP
+ ):
"""Create input packet stream for defined interfaces.
:param VppInterface src_if: Source Interface for packet stream.
@@ -112,10 +112,12 @@ class TestECMP(VppTestCase):
payload = self.info_to_payload(info)
src_ip = self.get_ip_address(src_ip_start, ip_prefix_len)
dst_ip = self.get_ip_address(dst_ip_start, ip_prefix_len)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- ip_l(src=src_ip, dst=dst_ip) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / ip_l(src=src_ip, dst=dst_ip)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
size = random.choice(packet_sizes)
self.extend_packet(p, size)
@@ -142,12 +144,17 @@ class TestECMP(VppTestCase):
payload_info = self.payload_to_info(packet[Raw])
packet_index = payload_info.index
ip_sent = self._packet_infos[packet_index].data[ip_l]
- self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
- (rx_if.name, payload_info.src, packet_index))
+ self.logger.debug(
+ "Got packet on port %s: src=%u (id=%u)"
+ % (rx_if.name, payload_info.src, packet_index)
+ )
# Check standard fields
- self.assertIn(packet.dst, rx_if._hosts_by_mac,
- "Destination MAC address %s shouldn't be routed "
- "via interface %s" % (packet.dst, rx_if.name))
+ self.assertIn(
+ packet.dst,
+ rx_if._hosts_by_mac,
+ "Destination MAC address %s shouldn't be routed "
+ "via interface %s" % (packet.dst, rx_if.name),
+ )
self.assertEqual(packet.src, rx_if.local_mac)
self.assertEqual(ip_received.src, ip_sent.src)
self.assertEqual(ip_received.dst, ip_sent.dst)
@@ -161,13 +168,15 @@ class TestECMP(VppTestCase):
# We expect packet routed via all host of pg interface
for host_mac in host_counters:
nr = host_counters[host_mac]
- self.assertNotEqual(
- nr, 0, "No packet routed via host %s" % host_mac)
- self.logger.info("%u packets routed via host %s of %s interface" %
- (nr, host_mac, rx_if.name))
+ self.assertNotEqual(nr, 0, "No packet routed via host %s" % host_mac)
+ self.logger.info(
+ "%u packets routed via host %s of %s interface"
+ % (nr, host_mac, rx_if.name)
+ )
count += nr
- self.logger.info("Total amount of %u packets routed via %s interface" %
- (count, rx_if.name))
+ self.logger.info(
+ "Total amount of %u packets routed via %s interface" % (count, rx_if.name)
+ )
return count
@@ -184,28 +193,27 @@ class TestECMP(VppTestCase):
for pg_if in self.pg_interfaces[1:]:
for nh_host in pg_if.remote_hosts:
nh_host_ip = nh_host.ip4 if is_ipv6 == 0 else nh_host.ip6
- paths.append(VppRoutePath(nh_host_ip,
- pg_if.sw_if_index))
+ paths.append(VppRoutePath(nh_host_ip, pg_if.sw_if_index))
rip = VppIpRoute(self, dst_ip_net, dst_prefix_len, paths)
rip.add_vpp_config()
- self.logger.info("Route via %s on %s created" %
- (nh_host_ip, pg_if.name))
+ self.logger.info("Route via %s on %s created" % (nh_host_ip, pg_if.name))
self.logger.debug(self.vapi.ppcli("show ip fib"))
self.logger.debug(self.vapi.ppcli("show ip6 fib"))
def test_ip_ecmp(self):
- """ IP equal-cost multi-path routing test """
+ """IP equal-cost multi-path routing test"""
- src_ip_net = '16.0.0.1'
- dst_ip_net = '32.0.0.1'
+ src_ip_net = "16.0.0.1"
+ dst_ip_net = "32.0.0.1"
ip_prefix_len = 24
self.create_ip_routes(dst_ip_net, ip_prefix_len)
- pkts = self.create_stream(self.pg0, src_ip_net, dst_ip_net,
- ip_prefix_len, self.pg_if_packet_sizes)
+ pkts = self.create_stream(
+ self.pg0, src_ip_net, dst_ip_net, ip_prefix_len, self.pg_if_packet_sizes
+ )
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -216,7 +224,8 @@ class TestECMP(VppTestCase):
for pg_if in self.pg_interfaces[1:]:
capture = pg_if._get_capture(timeout=1)
self.assertNotEqual(
- len(capture), 0, msg="No packets captured on %s" % pg_if.name)
+ len(capture), 0, msg="No packets captured on %s" % pg_if.name
+ )
rx_count += self.verify_capture(pg_if, capture)
self.pg0.assert_nothing_captured(remark="IP packets forwarded on pg0")
@@ -224,17 +233,22 @@ class TestECMP(VppTestCase):
self.assertEqual(rx_count, len(pkts))
def test_ip6_ecmp(self):
- """ IPv6 equal-cost multi-path routing test """
+ """IPv6 equal-cost multi-path routing test"""
- src_ip_net = '3ffe:51::1'
- dst_ip_net = '3ffe:71::1'
+ src_ip_net = "3ffe:51::1"
+ dst_ip_net = "3ffe:71::1"
ip_prefix_len = 64
self.create_ip_routes(dst_ip_net, ip_prefix_len, is_ipv6=1)
pkts = self.create_stream(
- self.pg0, src_ip_net, dst_ip_net,
- ip_prefix_len, self.pg_if_packet_sizes, ip_l=IPv6)
+ self.pg0,
+ src_ip_net,
+ dst_ip_net,
+ ip_prefix_len,
+ self.pg_if_packet_sizes,
+ ip_l=IPv6,
+ )
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -245,7 +259,8 @@ class TestECMP(VppTestCase):
for pg_if in self.pg_interfaces[1:]:
capture = pg_if._get_capture(timeout=1)
self.assertNotEqual(
- len(capture), 0, msg="No packets captured on %s" % pg_if.name)
+ len(capture), 0, msg="No packets captured on %s" % pg_if.name
+ )
rx_count += self.verify_capture(pg_if, capture, ip_l=IPv6)
self.pg0.assert_nothing_captured(remark="IP packets forwarded on pg0")
@@ -253,5 +268,5 @@ class TestECMP(VppTestCase):
self.assertEqual(rx_count, len(pkts))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ip_mcast.py b/test/test_ip_mcast.py
index 50ac01b8844..c3ac16c6d85 100644
--- a/test/test_ip_mcast.py
+++ b/test/test_ip_mcast.py
@@ -5,8 +5,14 @@ import unittest
from framework import tag_fixme_vpp_workers
from framework import VppTestCase, VppTestRunner
from vpp_ip import DpoProto
-from vpp_ip_route import VppIpMRoute, VppMRoutePath, VppMFibSignal, \
- VppIpTable, FibPathProto, FibPathType
+from vpp_ip_route import (
+ VppIpMRoute,
+ VppMRoutePath,
+ VppMFibSignal,
+ VppIpTable,
+ FibPathProto,
+ FibPathType,
+)
from vpp_gre_interface import VppGreInterface
from vpp_papi import VppEnum
@@ -26,7 +32,7 @@ N_PKTS_IN_STREAM = 91
class TestMFIB(VppTestCase):
- """ MFIB Test Case """
+ """MFIB Test Case"""
@classmethod
def setUpClass(cls):
@@ -40,7 +46,7 @@ class TestMFIB(VppTestCase):
super(TestMFIB, self).setUp()
def test_mfib(self):
- """ MFIB Unit Tests """
+ """MFIB Unit Tests"""
error = self.vapi.cli("test mfib")
if error:
@@ -50,7 +56,7 @@ class TestMFIB(VppTestCase):
@tag_fixme_vpp_workers
class TestIPMcast(VppTestCase):
- """ IP Multicast Test Case """
+ """IP Multicast Test Case"""
@classmethod
def setUpClass(cls):
@@ -98,12 +104,14 @@ class TestIPMcast(VppTestCase):
def create_stream_ip4(self, src_if, src_ip, dst_ip, payload_size=0):
pkts = []
# default to small packet sizes
- p = (Ether(dst=getmacbyip(dst_ip), src=src_if.remote_mac) /
- IP(src=src_ip, dst=dst_ip) /
- UDP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=getmacbyip(dst_ip), src=src_if.remote_mac)
+ / IP(src=src_ip, dst=dst_ip)
+ / UDP(sport=1234, dport=1234)
+ )
if not payload_size:
payload_size = 64 - len(p)
- p = p / Raw(b'\xa5' * payload_size)
+ p = p / Raw(b"\xa5" * payload_size)
for i in range(0, N_PKTS_IN_STREAM):
pkts.append(p)
@@ -114,10 +122,12 @@ class TestIPMcast(VppTestCase):
for i in range(0, N_PKTS_IN_STREAM):
info = self.create_packet_info(src_if, src_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=getmacbyip6(dst_ip), src=src_if.remote_mac) /
- IPv6(src=src_ip, dst=dst_ip) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=getmacbyip6(dst_ip), src=src_if.remote_mac)
+ / IPv6(src=src_ip, dst=dst_ip)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
pkts.append(p)
return pkts
@@ -126,7 +136,7 @@ class TestIPMcast(VppTestCase):
if not len(capture) == len(sent):
# filter out any IPv6 RAs from the capture
for p in capture:
- if (p.haslayer(IPv6)):
+ if p.haslayer(IPv6):
capture.remove(p)
return capture
@@ -186,7 +196,7 @@ class TestIPMcast(VppTestCase):
self.assertEqual(rx_ip.hlim + 1, tx_ip.hlim)
def test_ip_mcast(self):
- """ IP Multicast Replication """
+ """IP Multicast Replication"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -210,9 +220,11 @@ class TestIPMcast(VppTestCase):
self.pg_start()
self.pg0.assert_nothing_captured(
- remark="IP multicast packets forwarded on default route")
+ remark="IP multicast packets forwarded on default route"
+ )
count = self.statistics.get_err_counter(
- "/err/ip4-input/Multicast RPF check failed")
+ "/err/ip4-input/Multicast RPF check failed"
+ )
self.assertEqual(count, len(tx))
#
@@ -224,24 +236,36 @@ class TestIPMcast(VppTestCase):
route_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg3.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg4.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg5.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg6.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg7.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ VppMRoutePath(
+ self.pg2.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ VppMRoutePath(
+ self.pg3.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ VppMRoutePath(
+ self.pg4.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ VppMRoutePath(
+ self.pg5.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ VppMRoutePath(
+ self.pg6.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ VppMRoutePath(
+ self.pg7.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_232_1_1_1.add_vpp_config()
#
@@ -251,14 +275,21 @@ class TestIPMcast(VppTestCase):
route_1_1_1_1_232_1_1_1 = VppIpMRoute(
self,
"1.1.1.1",
- "232.1.1.1", 27, # any grp-len is ok when src is set
+ "232.1.1.1",
+ 27, # any grp-len is ok when src is set
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ VppMRoutePath(
+ self.pg2.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_1_1_1_1_232_1_1_1.add_vpp_config()
#
@@ -269,16 +300,25 @@ class TestIPMcast(VppTestCase):
route_1_1_1_1_232_1_1_2 = VppIpMRoute(
self,
"1.1.1.1",
- "232.1.1.2", 64,
+ "232.1.1.2",
+ 64,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- nh=self.pg1.remote_ip4),
- VppMRoutePath(self.pg2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- nh=self.pg2.remote_ip4)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ nh=self.pg1.remote_ip4,
+ ),
+ VppMRoutePath(
+ self.pg2.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ nh=self.pg2.remote_ip4,
+ ),
+ ],
+ )
route_1_1_1_1_232_1_1_2.add_vpp_config()
#
@@ -288,12 +328,18 @@ class TestIPMcast(VppTestCase):
route_232 = VppIpMRoute(
self,
"0.0.0.0",
- "232.0.0.0", 8,
+ "232.0.0.0",
+ 8,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_232.add_vpp_config()
#
@@ -307,26 +353,22 @@ class TestIPMcast(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.assertEqual(route_1_1_1_1_232_1_1_1.get_stats()['packets'],
- len(tx))
+ self.assertEqual(route_1_1_1_1_232_1_1_1.get_stats()["packets"], len(tx))
# We expect replications on Pg1->7
self.verify_capture_ip4(self.pg1, tx)
self.verify_capture_ip4(self.pg2, tx)
# no replications on Pg0
- self.pg0.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG0")
- self.pg3.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG3")
+ self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0")
+ self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3")
#
# a stream that matches the route for (1.1.1.1,232.1.1.1)
# large packets
#
self.vapi.cli("clear trace")
- tx = self.create_stream_ip4(self.pg0, "1.1.1.1", "232.1.1.1",
- payload_size=1024)
+ tx = self.create_stream_ip4(self.pg0, "1.1.1.1", "232.1.1.1", payload_size=1024)
self.pg0.add_stream(tx)
self.pg_enable_capture(self.pg_interfaces)
@@ -336,14 +378,11 @@ class TestIPMcast(VppTestCase):
self.verify_capture_ip4(self.pg1, tx)
self.verify_capture_ip4(self.pg2, tx)
- self.assertEqual(route_1_1_1_1_232_1_1_1.get_stats()['packets'],
- 2*len(tx))
+ self.assertEqual(route_1_1_1_1_232_1_1_1.get_stats()["packets"], 2 * len(tx))
# no replications on Pg0
- self.pg0.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG0")
- self.pg3.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG3")
+ self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0")
+ self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3")
#
# a stream to the unicast next-hops
@@ -360,10 +399,8 @@ class TestIPMcast(VppTestCase):
self.verify_capture_ip4(self.pg2, tx, dst_mac=self.pg2.remote_mac)
# no replications on Pg0 nor pg3
- self.pg0.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG0")
- self.pg3.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG3")
+ self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0")
+ self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3")
#
# a stream that matches the route for (*,232.0.0.0/8)
@@ -379,15 +416,12 @@ class TestIPMcast(VppTestCase):
# We expect replications on Pg1 only
self.verify_capture_ip4(self.pg1, tx)
- self.assertEqual(route_232.get_stats()['packets'], len(tx))
+ self.assertEqual(route_232.get_stats()["packets"], len(tx))
# no replications on Pg0, Pg2 not Pg3
- self.pg0.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG0")
- self.pg2.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG2")
- self.pg3.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG3")
+ self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0")
+ self.pg2.assert_nothing_captured(remark="IP multicast packets forwarded on PG2")
+ self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3")
#
# a stream that matches the route for (*,232.1.1.1)
@@ -409,8 +443,7 @@ class TestIPMcast(VppTestCase):
self.verify_capture_ip4(self.pg7, tx)
# no replications on Pg0
- self.pg0.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG0")
+ self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0")
self.vapi.cli("packet mac-filter pg0 off")
self.vapi.cli("packet mac-filter pg1 off")
@@ -421,7 +454,7 @@ class TestIPMcast(VppTestCase):
self.vapi.cli("packet mac-filter pg7 off")
def test_ip6_mcast(self):
- """ IPv6 Multicast Replication """
+ """IPv6 Multicast Replication"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -444,7 +477,8 @@ class TestIPMcast(VppTestCase):
self.pg_start()
self.pg0.assert_nothing_captured(
- remark="IPv6 multicast packets forwarded on default route")
+ remark="IPv6 multicast packets forwarded on default route"
+ )
#
# A (*,G).
@@ -453,20 +487,32 @@ class TestIPMcast(VppTestCase):
route_ff01_1 = VppIpMRoute(
self,
"::",
- "ff01::1", 128,
+ "ff01::1",
+ 128,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
- VppMRoutePath(self.pg2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
- VppMRoutePath(self.pg3.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ VppMRoutePath(
+ self.pg2.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ VppMRoutePath(
+ self.pg3.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ ],
+ )
route_ff01_1.add_vpp_config()
#
@@ -476,17 +522,27 @@ class TestIPMcast(VppTestCase):
route_2001_ff01_1 = VppIpMRoute(
self,
"2001::1",
- "ff01::1", 0, # any grp-len is ok when src is set
+ "ff01::1",
+ 0, # any grp-len is ok when src is set
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
- VppMRoutePath(self.pg2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ VppMRoutePath(
+ self.pg2.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ ],
+ )
route_2001_ff01_1.add_vpp_config()
#
@@ -496,14 +552,22 @@ class TestIPMcast(VppTestCase):
route_ff01 = VppIpMRoute(
self,
"::",
- "ff01::", 16,
+ "ff01::",
+ 16,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ ],
+ )
route_ff01.add_vpp_config()
#
@@ -514,7 +578,8 @@ class TestIPMcast(VppTestCase):
tx = self.create_stream_ip6(self.pg1, "2002::1", "ff01:2::255")
self.send_and_assert_no_replies(self.pg1, tx, "RPF miss")
count = self.statistics.get_err_counter(
- "/err/ip6-input/Multicast RPF check failed")
+ "/err/ip6-input/Multicast RPF check failed"
+ )
self.assertEqual(count, 2 * len(tx))
#
@@ -532,12 +597,9 @@ class TestIPMcast(VppTestCase):
self.verify_capture_ip6(self.pg1, tx)
# no replications on Pg0, Pg3
- self.pg0.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG0")
- self.pg2.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG2")
- self.pg3.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG3")
+ self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0")
+ self.pg2.assert_nothing_captured(remark="IP multicast packets forwarded on PG2")
+ self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3")
#
# Bounce the interface and it should still work
@@ -547,7 +609,8 @@ class TestIPMcast(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
self.pg1.assert_nothing_captured(
- remark="IP multicast packets forwarded on down PG1")
+ remark="IP multicast packets forwarded on down PG1"
+ )
self.pg1.admin_up()
self.pg0.add_stream(tx)
@@ -572,7 +635,8 @@ class TestIPMcast(VppTestCase):
# no replications on Pg0
self.pg0.assert_nothing_captured(
- remark="IPv6 multicast packets forwarded on PG0")
+ remark="IPv6 multicast packets forwarded on PG0"
+ )
#
# a stream that matches the route for (2001::1, ff00::1)
@@ -589,10 +653,8 @@ class TestIPMcast(VppTestCase):
self.verify_capture_ip6(self.pg2, tx)
# no replications on Pg0, Pg3
- self.pg0.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG0")
- self.pg3.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG3")
+ self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0")
+ self.pg3.assert_nothing_captured(remark="IP multicast packets forwarded on PG3")
self.vapi.cli("packet mac-filter pg0 off")
self.vapi.cli("packet mac-filter pg1 off")
@@ -604,9 +666,7 @@ class TestIPMcast(VppTestCase):
def _mcast_connected_send_stream(self, dst_ip):
self.vapi.cli("clear trace")
- tx = self.create_stream_ip4(self.pg0,
- self.pg0.remote_ip4,
- dst_ip)
+ tx = self.create_stream_ip4(self.pg0, self.pg0.remote_ip4, dst_ip)
self.pg0.add_stream(tx)
self.pg_enable_capture(self.pg_interfaces)
@@ -618,7 +678,7 @@ class TestIPMcast(VppTestCase):
return tx
def test_ip_mcast_connected(self):
- """ IP Multicast Connected Source check """
+ """IP Multicast Connected Source check"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -630,16 +690,23 @@ class TestIPMcast(VppTestCase):
route_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_232_1_1_1.add_vpp_config()
route_232_1_1_1.update_entry_flags(
- MRouteEntryFlags.MFIB_API_ENTRY_FLAG_CONNECTED)
+ MRouteEntryFlags.MFIB_API_ENTRY_FLAG_CONNECTED
+ )
#
# Now the (*,G) is present, send from connected source
@@ -649,10 +716,9 @@ class TestIPMcast(VppTestCase):
#
# Constrct a representation of the signal we expect on pg0
#
- signal_232_1_1_1_itf_0 = VppMFibSignal(self,
- route_232_1_1_1,
- self.pg0.sw_if_index,
- tx[0])
+ signal_232_1_1_1_itf_0 = VppMFibSignal(
+ self, route_232_1_1_1, self.pg0.sw_if_index, tx[0]
+ )
#
# read the only expected signal
@@ -680,24 +746,30 @@ class TestIPMcast(VppTestCase):
route_232_1_1_2 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.2", 32,
+ "232.1.1.2",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_232_1_1_2.add_vpp_config()
route_232_1_1_2.update_entry_flags(
- MRouteEntryFlags.MFIB_API_ENTRY_FLAG_CONNECTED)
+ MRouteEntryFlags.MFIB_API_ENTRY_FLAG_CONNECTED
+ )
#
# Send traffic to both entries. One read should net us two signals
#
- signal_232_1_1_2_itf_0 = VppMFibSignal(self,
- route_232_1_1_2,
- self.pg0.sw_if_index,
- tx[0])
+ signal_232_1_1_2_itf_0 = VppMFibSignal(
+ self, route_232_1_1_2, self.pg0.sw_if_index, tx[0]
+ )
tx = self._mcast_connected_send_stream("232.1.1.1")
tx2 = self._mcast_connected_send_stream("232.1.1.2")
@@ -711,13 +783,11 @@ class TestIPMcast(VppTestCase):
signal_232_1_1_1_itf_0.compare(signals[1])
signal_232_1_1_2_itf_0.compare(signals[0])
- route_232_1_1_1.update_entry_flags(
- MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE)
- route_232_1_1_2.update_entry_flags(
- MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE)
+ route_232_1_1_1.update_entry_flags(MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE)
+ route_232_1_1_2.update_entry_flags(MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE)
def test_ip_mcast_signal(self):
- """ IP Multicast Signal """
+ """IP Multicast Signal"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -729,17 +799,22 @@ class TestIPMcast(VppTestCase):
route_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_232_1_1_1.add_vpp_config()
- route_232_1_1_1.update_entry_flags(
- MRouteEntryFlags.MFIB_API_ENTRY_FLAG_SIGNAL)
+ route_232_1_1_1.update_entry_flags(MRouteEntryFlags.MFIB_API_ENTRY_FLAG_SIGNAL)
#
# Now the (*,G) is present, send from connected source
@@ -749,10 +824,9 @@ class TestIPMcast(VppTestCase):
#
# Constrct a representation of the signal we expect on pg0
#
- signal_232_1_1_1_itf_0 = VppMFibSignal(self,
- route_232_1_1_1,
- self.pg0.sw_if_index,
- tx[0])
+ signal_232_1_1_1_itf_0 = VppMFibSignal(
+ self, route_232_1_1_1, self.pg0.sw_if_index, tx[0]
+ )
#
# read the only expected signal
@@ -779,8 +853,11 @@ class TestIPMcast(VppTestCase):
#
route_232_1_1_1.update_path_flags(
self.pg0.sw_if_index,
- (MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT |
- MRouteItfFlags.MFIB_API_ITF_FLAG_NEGATE_SIGNAL))
+ (
+ MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ | MRouteItfFlags.MFIB_API_ITF_FLAG_NEGATE_SIGNAL
+ ),
+ )
self.vapi.cli("clear trace")
tx = self._mcast_connected_send_stream("232.1.1.1")
@@ -792,8 +869,7 @@ class TestIPMcast(VppTestCase):
# Clear the SIGNAL flag on the entry and the signals should
# come back since the interface is still NEGATE-SIGNAL
#
- route_232_1_1_1.update_entry_flags(
- MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE)
+ route_232_1_1_1.update_entry_flags(MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE)
tx = self._mcast_connected_send_stream("232.1.1.1")
@@ -806,15 +882,15 @@ class TestIPMcast(VppTestCase):
# signals should stop
#
route_232_1_1_1.update_path_flags(
- self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT)
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ )
tx = self._mcast_connected_send_stream("232.1.1.1")
signals = self.vapi.mfib_signal_dump()
self.assertEqual(0, len(signals))
def test_ip_mcast_vrf(self):
- """ IP Multicast Replication in non-default table"""
+ """IP Multicast Replication in non-default table"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -826,15 +902,22 @@ class TestIPMcast(VppTestCase):
route_1_1_1_1_232_1_1_1 = VppIpMRoute(
self,
"1.1.1.1",
- "232.1.1.1", 64,
+ "232.1.1.1",
+ 64,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg8.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)],
- table_id=10)
+ [
+ VppMRoutePath(
+ self.pg8.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ VppMRoutePath(
+ self.pg2.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ table_id=10,
+ )
route_1_1_1_1_232_1_1_1.add_vpp_config()
#
@@ -858,14 +941,21 @@ class TestIPMcast(VppTestCase):
route_0_0_0_0_224_0_0_5 = VppIpMRoute(
self,
"0.0.0.0",
- "224.0.0.5", 32,
+ "224.0.0.5",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg8.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(0xffffffff,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- type=FibPathType.FIB_PATH_TYPE_LOCAL)],
- table_id=10)
+ [
+ VppMRoutePath(
+ self.pg8.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ 0xFFFFFFFF,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ type=FibPathType.FIB_PATH_TYPE_LOCAL,
+ ),
+ ],
+ table_id=10,
+ )
route_0_0_0_0_224_0_0_5.add_vpp_config()
#
@@ -879,34 +969,33 @@ class TestIPMcast(VppTestCase):
# send a ping to mcast address from peer on pg8
# expect a response
#
- icmp_id = 0xb
+ icmp_id = 0xB
icmp_seq = 5
- icmp_load = b'\x0a' * 18
- tx = (Ether(dst=getmacbyip("224.0.0.5"), src=self.pg8.remote_mac) /
- IP(src=self.pg8.remote_ip4, dst="224.0.0.5") /
- ICMP(id=icmp_id, seq=icmp_seq) /
- Raw(load=icmp_load)) * 2
+ icmp_load = b"\x0a" * 18
+ tx = (
+ Ether(dst=getmacbyip("224.0.0.5"), src=self.pg8.remote_mac)
+ / IP(src=self.pg8.remote_ip4, dst="224.0.0.5")
+ / ICMP(id=icmp_id, seq=icmp_seq)
+ / Raw(load=icmp_load)
+ ) * 2
self.send_and_expect(self.pg8, tx, self.pg8)
def test_ip_mcast_gre(self):
- """ IP Multicast Replication over GRE"""
+ """IP Multicast Replication over GRE"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
gre_if_1 = VppGreInterface(
- self,
- self.pg1.local_ip4,
- self.pg1.remote_ip4).add_vpp_config()
+ self, self.pg1.local_ip4, self.pg1.remote_ip4
+ ).add_vpp_config()
gre_if_2 = VppGreInterface(
- self,
- self.pg2.local_ip4,
- self.pg2.remote_ip4).add_vpp_config()
+ self, self.pg2.local_ip4, self.pg2.remote_ip4
+ ).add_vpp_config()
gre_if_3 = VppGreInterface(
- self,
- self.pg3.local_ip4,
- self.pg3.remote_ip4).add_vpp_config()
+ self, self.pg3.local_ip4, self.pg3.remote_ip4
+ ).add_vpp_config()
gre_if_1.admin_up()
gre_if_1.config_ip4()
@@ -922,28 +1011,35 @@ class TestIPMcast(VppTestCase):
route_1_1_1_1_232_1_1_1 = VppIpMRoute(
self,
"1.1.1.1",
- "232.2.2.2", 64,
+ "232.2.2.2",
+ 64,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(gre_if_1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(gre_if_2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(gre_if_3.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ gre_if_1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ gre_if_2.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ VppMRoutePath(
+ gre_if_3.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_1_1_1_1_232_1_1_1.add_vpp_config()
#
# a stream that matches the route for (1.1.1.1,232.2.2.2)
# small packets
#
- tx = (Ether(dst=self.pg1.local_mac,
- src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4,
- dst=self.pg1.local_ip4) /
- GRE() /
- IP(src="1.1.1.1", dst="232.2.2.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\a5' * 64)) * 63
+ tx = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4)
+ / GRE()
+ / IP(src="1.1.1.1", dst="232.2.2.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\a5" * 64)
+ ) * 63
self.vapi.cli("clear trace")
self.pg1.add_stream(tx)
@@ -966,23 +1062,20 @@ class TestIPMcast(VppTestCase):
self.assert_packet_checksums_valid(rx)
def test_ip6_mcast_gre(self):
- """ IP6 Multicast Replication over GRE"""
+ """IP6 Multicast Replication over GRE"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
gre_if_1 = VppGreInterface(
- self,
- self.pg1.local_ip4,
- self.pg1.remote_ip4).add_vpp_config()
+ self, self.pg1.local_ip4, self.pg1.remote_ip4
+ ).add_vpp_config()
gre_if_2 = VppGreInterface(
- self,
- self.pg2.local_ip4,
- self.pg2.remote_ip4).add_vpp_config()
+ self, self.pg2.local_ip4, self.pg2.remote_ip4
+ ).add_vpp_config()
gre_if_3 = VppGreInterface(
- self,
- self.pg3.local_ip4,
- self.pg3.remote_ip4).add_vpp_config()
+ self, self.pg3.local_ip4, self.pg3.remote_ip4
+ ).add_vpp_config()
gre_if_1.admin_up()
gre_if_1.config_ip6()
@@ -998,28 +1091,35 @@ class TestIPMcast(VppTestCase):
route_1_1_FF_1 = VppIpMRoute(
self,
"1::1",
- "FF00::1", 256,
+ "FF00::1",
+ 256,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(gre_if_1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(gre_if_2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(gre_if_3.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ gre_if_1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ gre_if_2.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ VppMRoutePath(
+ gre_if_3.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_1_1_FF_1.add_vpp_config()
#
# a stream that matches the route for (1::1, FF::1)
# small packets
#
- tx = (Ether(dst=self.pg1.local_mac,
- src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4,
- dst=self.pg1.local_ip4) /
- GRE() /
- IPv6(src="1::1", dst="FF00::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\a5' * 64)) * 63
+ tx = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4)
+ / GRE()
+ / IPv6(src="1::1", dst="FF00::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\a5" * 64)
+ ) * 63
self.vapi.cli("clear trace")
self.pg1.add_stream(tx)
@@ -1042,7 +1142,7 @@ class TestIPMcast(VppTestCase):
self.assert_packet_checksums_valid(rx)
def test_ip6_mcast_vrf(self):
- """ IPv6 Multicast Replication in non-default table"""
+ """IPv6 Multicast Replication in non-default table"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -1054,18 +1154,28 @@ class TestIPMcast(VppTestCase):
route_2001_ff01_1 = VppIpMRoute(
self,
"2001::1",
- "ff01::1", 256,
+ "ff01::1",
+ 256,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg8.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6),
- VppMRoutePath(self.pg2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)],
- table_id=10)
+ [
+ VppMRoutePath(
+ self.pg8.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ VppMRoutePath(
+ self.pg2.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ ),
+ ],
+ table_id=10,
+ )
route_2001_ff01_1.add_vpp_config()
#
@@ -1083,7 +1193,7 @@ class TestIPMcast(VppTestCase):
self.verify_capture_ip6(self.pg2, tx)
def test_bidir(self):
- """ IP Multicast Bi-directional """
+ """IP Multicast Bi-directional"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -1094,20 +1204,32 @@ class TestIPMcast(VppTestCase):
route_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT |
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT |
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg2.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT |
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD),
- VppMRoutePath(self.pg3.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT |
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ | MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ ),
+ VppMRoutePath(
+ self.pg1.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ | MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ ),
+ VppMRoutePath(
+ self.pg2.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ | MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ ),
+ VppMRoutePath(
+ self.pg3.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ | MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ ),
+ ],
+ )
route_232_1_1_1.add_vpp_config()
tx = self.create_stream_ip4(self.pg0, "1.1.1.1", "232.1.1.1")
@@ -1120,9 +1242,8 @@ class TestIPMcast(VppTestCase):
self.verify_capture_ip4(self.pg1, tx)
self.verify_capture_ip4(self.pg2, tx)
self.verify_capture_ip4(self.pg3, tx)
- self.pg0.assert_nothing_captured(
- remark="IP multicast packets forwarded on PG0")
+ self.pg0.assert_nothing_captured(remark="IP multicast packets forwarded on PG0")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ipfix_export.py b/test/test_ipfix_export.py
index be7476e67cf..f7b8be7e4d8 100644
--- a/test/test_ipfix_export.py
+++ b/test/test_ipfix_export.py
@@ -16,7 +16,7 @@ from socket import AF_INET, AF_INET6
class TestIpfixExporter(VppTestCase):
- """ Ipfix Exporter Tests """
+ """Ipfix Exporter Tests"""
def setUp(self):
super(TestIpfixExporter, self).setUp()
@@ -37,15 +37,16 @@ class TestIpfixExporter(VppTestCase):
i.admin_down()
def find_exp_by_collector_addr(self, exporters, addr):
- """ Find the exporter in the list of exportes with the given addr """
+ """Find the exporter in the list of exportes with the given addr"""
for exp in exporters:
if exp.collector_address == IPv4Address(addr):
return exp
return None
- def verify_exporter_detail(self, exp, collector_addr, src_addr,
- collector_port=4739, mtu=1400, interval=20):
+ def verify_exporter_detail(
+ self, exp, collector_addr, src_addr, collector_port=4739, mtu=1400, interval=20
+ ):
self.assertTrue(exp is not None)
self.assert_equal(exp.collector_address, collector_addr)
self.assert_equal(exp.src_address, src_addr)
@@ -54,7 +55,7 @@ class TestIpfixExporter(VppTestCase):
self.assert_equal(exp.template_interval, interval)
def test_create_multipe_exporters(self):
- """ test that we can create and dump multiple exporters """
+ """test that we can create and dump multiple exporters"""
mtu = 1400
interval = 20
@@ -66,20 +67,20 @@ class TestIpfixExporter(VppTestCase):
src_address=self.pg0.local_ip4,
collector_port=4739,
path_mtu=mtu,
- template_interval=interval)
+ template_interval=interval,
+ )
exporters = self.vapi.ipfix_exporter_dump()
exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg1.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
- exporters = list(self.vapi.vpp.details_iter(
- self.vapi.ipfix_all_exporter_get))
+ exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get))
exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg1.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
# create a 2nd exporter
self.vapi.ipfix_exporter_create_delete(
@@ -88,19 +89,19 @@ class TestIpfixExporter(VppTestCase):
collector_port=4739,
path_mtu=mtu,
template_interval=interval,
- is_create=True)
+ is_create=True,
+ )
- exporters = list(self.vapi.vpp.details_iter(
- self.vapi.ipfix_all_exporter_get))
+ exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get))
self.assertTrue(len(exporters) == 2)
exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg1.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
exp = self.find_exp_by_collector_addr(exporters, self.pg2.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg2.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg2.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
# Create a 3rd exporter
self.vapi.ipfix_exporter_create_delete(
@@ -109,49 +110,52 @@ class TestIpfixExporter(VppTestCase):
collector_port=4739,
path_mtu=mtu,
template_interval=interval,
- is_create=True)
+ is_create=True,
+ )
- exporters = list(self.vapi.vpp.details_iter(
- self.vapi.ipfix_all_exporter_get))
+ exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get))
self.assertTrue(len(exporters) == 3)
exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg1.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
exp = self.find_exp_by_collector_addr(exporters, self.pg2.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg2.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg2.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
exp = self.find_exp_by_collector_addr(exporters, self.pg3.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg3.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg3.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
# Modify the 2nd exporter.
self.vapi.ipfix_exporter_create_delete(
collector_address=self.pg2.remote_ip4,
src_address=self.pg0.local_ip4,
collector_port=4739,
- path_mtu=mtu+1,
- template_interval=interval+1,
- is_create=True)
+ path_mtu=mtu + 1,
+ template_interval=interval + 1,
+ is_create=True,
+ )
- exporters = list(self.vapi.vpp.details_iter(
- self.vapi.ipfix_all_exporter_get))
+ exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get))
self.assertTrue(len(exporters) == 3)
exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg1.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
exp = self.find_exp_by_collector_addr(exporters, self.pg2.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg2.remote_ip4),
- IPv4Address(self.pg0.local_ip4),
- mtu=mtu+1, interval=interval+1)
+ self.verify_exporter_detail(
+ exp,
+ IPv4Address(self.pg2.remote_ip4),
+ IPv4Address(self.pg0.local_ip4),
+ mtu=mtu + 1,
+ interval=interval + 1,
+ )
exp = self.find_exp_by_collector_addr(exporters, self.pg3.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg3.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg3.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
# Delete 2nd exporter
self.vapi.ipfix_exporter_create_delete(
@@ -160,19 +164,19 @@ class TestIpfixExporter(VppTestCase):
collector_port=4739,
path_mtu=mtu,
template_interval=interval,
- is_create=False)
+ is_create=False,
+ )
- exporters = list(self.vapi.vpp.details_iter(
- self.vapi.ipfix_all_exporter_get))
+ exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get))
self.assertTrue(len(exporters) == 2)
exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg1.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
exp = self.find_exp_by_collector_addr(exporters, self.pg3.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg3.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg3.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
# Delete final exporter (exporter in slot 0 can not be deleted)
self.vapi.ipfix_exporter_create_delete(
@@ -181,12 +185,12 @@ class TestIpfixExporter(VppTestCase):
collector_port=4739,
path_mtu=mtu,
template_interval=interval,
- is_create=False)
+ is_create=False,
+ )
- exporters = list(self.vapi.vpp.details_iter(
- self.vapi.ipfix_all_exporter_get))
+ exporters = list(self.vapi.vpp.details_iter(self.vapi.ipfix_all_exporter_get))
self.assertTrue(len(exporters) == 1)
exp = self.find_exp_by_collector_addr(exporters, self.pg1.remote_ip4)
- self.verify_exporter_detail(exp,
- IPv4Address(self.pg1.remote_ip4),
- IPv4Address(self.pg0.local_ip4))
+ self.verify_exporter_detail(
+ exp, IPv4Address(self.pg1.remote_ip4), IPv4Address(self.pg0.local_ip4)
+ )
diff --git a/test/test_ipip.py b/test/test_ipip.py
index b1ea57d7e12..cbaedd51273 100644
--- a/test/test_ipip.py
+++ b/test/test_ipip.py
@@ -7,8 +7,15 @@ from scapy.contrib.mpls import MPLS
from scapy.all import fragment, fragment6, RandShort, defragment6
from framework import VppTestCase, VppTestRunner
from vpp_ip import DpoProto
-from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpTable, FibPathProto, \
- VppMplsLabel, VppMplsRoute, VppMplsTable
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ VppIpTable,
+ FibPathProto,
+ VppMplsLabel,
+ VppMplsRoute,
+ VppMplsTable,
+)
from vpp_ipip_tun_interface import VppIpIpTunInterface
from vpp_teib import VppTeib
from vpp_papi import VppEnum
@@ -22,27 +29,27 @@ IPIP tests.
"""
-def ipip_add_tunnel(test, src, dst, table_id=0, dscp=0x0,
- flags=0):
- """ Add a IPIP tunnel """
+def ipip_add_tunnel(test, src, dst, table_id=0, dscp=0x0, flags=0):
+ """Add a IPIP tunnel"""
return test.vapi.ipip_add_tunnel(
tunnel={
- 'src': src,
- 'dst': dst,
- 'table_id': table_id,
- 'instance': 0xffffffff,
- 'dscp': dscp,
- 'flags': flags
+ "src": src,
+ "dst": dst,
+ "table_id": table_id,
+ "instance": 0xFFFFFFFF,
+ "dscp": dscp,
+ "flags": flags,
}
)
+
# the number of packets to send when injecting traffic.
# a multiple of 8 minus one, so we test all by 8/4/2/1 loops
N_PACKETS = 64 - 1
class TestIPIP(VppTestCase):
- """ IPIP Test Case """
+ """IPIP Test Case"""
@classmethod
def setUpClass(cls):
@@ -88,21 +95,24 @@ class TestIPIP(VppTestCase):
p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
p_payload = UDP(sport=1234, dport=1234) / self.payload(payload_length)
p_ip4 = IP(src="1.2.3.4", dst=self.pg0.remote_ip4)
- outer_ip4 = (p_ether / IP(src=self.pg1.remote_ip4,
- id=RandShort(),
- dst=self.pg0.local_ip4) / p_ip4 / p_payload)
+ outer_ip4 = (
+ p_ether
+ / IP(src=self.pg1.remote_ip4, id=RandShort(), dst=self.pg0.local_ip4)
+ / p_ip4
+ / p_payload
+ )
frags = fragment(outer_ip4, fragment_size)
- p4_reply = (p_ip4 / p_payload)
+ p4_reply = p_ip4 / p_payload
p4_reply.ttl -= 1
return frags, p4_reply
def verify_ip4ip4_encaps(self, a, p_ip4s, p_ip4_encaps):
for i, p_ip4 in enumerate(p_ip4s):
p_ip4.dst = a
- p4 = (self.p_ether / p_ip4 / self.p_payload)
+ p4 = self.p_ether / p_ip4 / self.p_payload
p_ip4_inner = p_ip4
p_ip4_inner.ttl -= 1
- p4_reply = (p_ip4_encaps[i] / p_ip4_inner / self.p_payload)
+ p4_reply = p_ip4_encaps[i] / p_ip4_inner / self.p_payload
p4_reply.ttl -= 1
p4_reply.id = 0
rx = self.send_and_expect(self.pg0, p4 * N_PACKETS, self.pg1)
@@ -113,10 +123,10 @@ class TestIPIP(VppTestCase):
def verify_ip6ip4_encaps(self, a, p_ip6s, p_ip4_encaps):
for i, p_ip6 in enumerate(p_ip6s):
p_ip6.dst = a
- p6 = (self.p_ether / p_ip6 / self.p_payload)
+ p6 = self.p_ether / p_ip6 / self.p_payload
p_inner_ip6 = p_ip6
p_inner_ip6.hlim -= 1
- p6_reply = (p_ip4_encaps[i] / p_inner_ip6 / self.p_payload)
+ p6_reply = p_ip4_encaps[i] / p_inner_ip6 / self.p_payload
p6_reply.ttl -= 1
rx = self.send_and_expect(self.pg0, p6 * N_PACKETS, self.pg1)
for p in rx:
@@ -124,14 +134,14 @@ class TestIPIP(VppTestCase):
self.assert_packet_checksums_valid(p)
def test_ipip4(self):
- """ ip{v4,v6} over ip4 test """
+ """ip{v4,v6} over ip4 test"""
self.pg1.generate_remote_hosts(5)
self.pg1.configure_ipv4_neighbors()
e = VppEnum.vl_api_tunnel_encap_decap_flags_t
d = VppEnum.vl_api_ip_dscp_t
self.p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
- self.p_payload = UDP(sport=1234, dport=1234) / Raw(b'X' * 100)
+ self.p_payload = UDP(sport=1234, dport=1234) / Raw(b"X" * 100)
# create a TOS byte by shifting a DSCP code point 2 bits. those 2 bits
# are for the ECN.
@@ -145,7 +155,8 @@ class TestIPIP(VppTestCase):
self.pg0,
self.pg0.local_ip4,
self.pg1.remote_hosts[0].ip4,
- flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP)
+ flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP,
+ )
tun_dscp.add_vpp_config()
# IPv4 transport that copies the DCSP and ECN from the payload
tun_dscp_ecn = VppIpIpTunInterface(
@@ -153,8 +164,11 @@ class TestIPIP(VppTestCase):
self.pg0,
self.pg0.local_ip4,
self.pg1.remote_hosts[1].ip4,
- flags=(e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP |
- e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN))
+ flags=(
+ e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP
+ | e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN
+ ),
+ )
tun_dscp_ecn.add_vpp_config()
# IPv4 transport that copies the ECN from the payload and sets the
# DF bit on encap. copies the ECN on decap
@@ -163,9 +177,12 @@ class TestIPIP(VppTestCase):
self.pg0,
self.pg0.local_ip4,
self.pg1.remote_hosts[2].ip4,
- flags=(e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN |
- e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_SET_DF |
- e.TUNNEL_API_ENCAP_DECAP_FLAG_DECAP_COPY_ECN))
+ flags=(
+ e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN
+ | e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_SET_DF
+ | e.TUNNEL_API_ENCAP_DECAP_FLAG_DECAP_COPY_ECN
+ ),
+ )
tun_ecn.add_vpp_config()
# IPv4 transport that sets a fixed DSCP in the encap and copies
# the DF bit
@@ -175,7 +192,8 @@ class TestIPIP(VppTestCase):
self.pg0.local_ip4,
self.pg1.remote_hosts[3].ip4,
dscp=d.IP_API_DSCP_AF11,
- flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DF)
+ flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DF,
+ )
tun.add_vpp_config()
# array of all the tunnels
@@ -186,22 +204,26 @@ class TestIPIP(VppTestCase):
a6s = ["" for i in range(len(tuns))]
# IP headers with each combination of DSCp/ECN tested
- p_ip6s = [IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=dscp),
- IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=dscp_ecn),
- IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=ecn),
- IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=0xff)]
- p_ip4s = [IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp, flags='DF'),
- IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp_ecn),
- IP(src="1.2.3.4", dst="130.67.0.1", tos=ecn),
- IP(src="1.2.3.4", dst="130.67.0.1", tos=0xff)]
+ p_ip6s = [
+ IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=dscp),
+ IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=dscp_ecn),
+ IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=ecn),
+ IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=0xFF),
+ ]
+ p_ip4s = [
+ IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp, flags="DF"),
+ IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp_ecn),
+ IP(src="1.2.3.4", dst="130.67.0.1", tos=ecn),
+ IP(src="1.2.3.4", dst="130.67.0.1", tos=0xFF),
+ ]
# Configure each tunnel
for i, t in enumerate(tuns):
# Set interface up and enable IP on it
self.vapi.sw_interface_set_flags(t.sw_if_index, 1)
self.vapi.sw_interface_set_unnumbered(
- sw_if_index=self.pg0.sw_if_index,
- unnumbered_sw_if_index=t.sw_if_index)
+ sw_if_index=self.pg0.sw_if_index, unnumbered_sw_if_index=t.sw_if_index
+ )
# prefix for route / destination address for packets
a4s[i] = "130.67.%d.0" % i
@@ -209,17 +231,29 @@ class TestIPIP(VppTestCase):
# Add IPv4 and IPv6 routes via tunnel interface
ip4_via_tunnel = VppIpRoute(
- self, a4s[i], 24,
- [VppRoutePath("0.0.0.0",
- t.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)])
+ self,
+ a4s[i],
+ 24,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ t.sw_if_index,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ )
+ ],
+ )
ip4_via_tunnel.add_vpp_config()
ip6_via_tunnel = VppIpRoute(
- self, a6s[i], 64,
- [VppRoutePath("::",
- t.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ self,
+ a6s[i],
+ 64,
+ [
+ VppRoutePath(
+ "::", t.sw_if_index, proto=FibPathProto.FIB_PATH_NH_PROTO_IP6
+ )
+ ],
+ )
ip6_via_tunnel.add_vpp_config()
#
@@ -229,13 +263,14 @@ class TestIPIP(VppTestCase):
# tun_dscp copies only the dscp
# expected TC values are thus only the DCSP value is present from the
# inner
- exp_tcs = [dscp, dscp, 0, 0xfc]
- p_ip44_encaps = [IP(src=self.pg0.local_ip4,
- dst=tun_dscp.dst,
- tos=tc) for tc in exp_tcs]
- p_ip64_encaps = [IP(src=self.pg0.local_ip4,
- dst=tun_dscp.dst,
- proto='ipv6', id=0, tos=tc) for tc in exp_tcs]
+ exp_tcs = [dscp, dscp, 0, 0xFC]
+ p_ip44_encaps = [
+ IP(src=self.pg0.local_ip4, dst=tun_dscp.dst, tos=tc) for tc in exp_tcs
+ ]
+ p_ip64_encaps = [
+ IP(src=self.pg0.local_ip4, dst=tun_dscp.dst, proto="ipv6", id=0, tos=tc)
+ for tc in exp_tcs
+ ]
# IPv4 in to IPv4 tunnel
self.verify_ip4ip4_encaps(a4s[0], p_ip4s, p_ip44_encaps)
@@ -243,41 +278,50 @@ class TestIPIP(VppTestCase):
self.verify_ip6ip4_encaps(a6s[0], p_ip6s, p_ip64_encaps)
# tun_dscp_ecn copies the dscp and the ecn
- exp_tcs = [dscp, dscp_ecn, ecn, 0xff]
- p_ip44_encaps = [IP(src=self.pg0.local_ip4,
- dst=tun_dscp_ecn.dst,
- tos=tc) for tc in exp_tcs]
- p_ip64_encaps = [IP(src=self.pg0.local_ip4,
- dst=tun_dscp_ecn.dst,
- proto='ipv6', id=0, tos=tc) for tc in exp_tcs]
+ exp_tcs = [dscp, dscp_ecn, ecn, 0xFF]
+ p_ip44_encaps = [
+ IP(src=self.pg0.local_ip4, dst=tun_dscp_ecn.dst, tos=tc) for tc in exp_tcs
+ ]
+ p_ip64_encaps = [
+ IP(src=self.pg0.local_ip4, dst=tun_dscp_ecn.dst, proto="ipv6", id=0, tos=tc)
+ for tc in exp_tcs
+ ]
self.verify_ip4ip4_encaps(a4s[1], p_ip4s, p_ip44_encaps)
self.verify_ip6ip4_encaps(a6s[1], p_ip6s, p_ip64_encaps)
# tun_ecn copies only the ecn and always sets DF
exp_tcs = [0, ecn, ecn, ecn]
- p_ip44_encaps = [IP(src=self.pg0.local_ip4,
- dst=tun_ecn.dst,
- flags='DF', tos=tc) for tc in exp_tcs]
- p_ip64_encaps = [IP(src=self.pg0.local_ip4,
- dst=tun_ecn.dst,
- flags='DF', proto='ipv6', id=0, tos=tc)
- for tc in exp_tcs]
+ p_ip44_encaps = [
+ IP(src=self.pg0.local_ip4, dst=tun_ecn.dst, flags="DF", tos=tc)
+ for tc in exp_tcs
+ ]
+ p_ip64_encaps = [
+ IP(
+ src=self.pg0.local_ip4,
+ dst=tun_ecn.dst,
+ flags="DF",
+ proto="ipv6",
+ id=0,
+ tos=tc,
+ )
+ for tc in exp_tcs
+ ]
self.verify_ip4ip4_encaps(a4s[2], p_ip4s, p_ip44_encaps)
self.verify_ip6ip4_encaps(a6s[2], p_ip6s, p_ip64_encaps)
# tun sets a fixed dscp and copies DF
fixed_dscp = tun.dscp << 2
- flags = ['DF', 0, 0, 0]
- p_ip44_encaps = [IP(src=self.pg0.local_ip4,
- dst=tun.dst,
- flags=f,
- tos=fixed_dscp) for f in flags]
- p_ip64_encaps = [IP(src=self.pg0.local_ip4,
- dst=tun.dst,
- proto='ipv6', id=0,
- tos=fixed_dscp) for i in range(len(p_ip4s))]
+ flags = ["DF", 0, 0, 0]
+ p_ip44_encaps = [
+ IP(src=self.pg0.local_ip4, dst=tun.dst, flags=f, tos=fixed_dscp)
+ for f in flags
+ ]
+ p_ip64_encaps = [
+ IP(src=self.pg0.local_ip4, dst=tun.dst, proto="ipv6", id=0, tos=fixed_dscp)
+ for i in range(len(p_ip4s))
+ ]
self.verify_ip4ip4_encaps(a4s[3], p_ip4s, p_ip44_encaps)
self.verify_ip6ip4_encaps(a6s[3], p_ip6s, p_ip64_encaps)
@@ -293,15 +337,13 @@ class TestIPIP(VppTestCase):
# one overlay packet and all combinations of its encap
p_ip4 = IP(src="1.2.3.4", dst=self.pg0.remote_ip4)
- p_ip4_encaps = [IP(src=tun.dst,
- dst=self.pg0.local_ip4,
- tos=tc) for tc in tcs]
+ p_ip4_encaps = [IP(src=tun.dst, dst=self.pg0.local_ip4, tos=tc) for tc in tcs]
# for each encap tun will produce the same inner packet because it does
# not copy up fields from the payload
for p_ip4_encap in p_ip4_encaps:
- p4 = (self.p_ether / p_ip4_encap / p_ip4 / self.p_payload)
- p4_reply = (p_ip4 / self.p_payload)
+ p4 = self.p_ether / p_ip4_encap / p_ip4 / self.p_payload
+ p4_reply = p_ip4 / self.p_payload
p4_reply.ttl -= 1
rx = self.send_and_expect(self.pg1, p4 * N_PACKETS, self.pg0)
n_packets_decapped += N_PACKETS
@@ -309,20 +351,19 @@ class TestIPIP(VppTestCase):
self.validate(p[1], p4_reply)
self.assert_packet_checksums_valid(p)
- err = self.statistics.get_err_counter(
- '/err/ipip4-input/packets decapsulated')
+ err = self.statistics.get_err_counter("/err/ipip4-input/packets decapsulated")
self.assertEqual(err, n_packets_decapped)
# tun_ecn copies the ECN bits from the encap to the inner
- p_ip4_encaps = [IP(src=tun_ecn.dst,
- dst=self.pg0.local_ip4,
- tos=tc) for tc in tcs]
+ p_ip4_encaps = [
+ IP(src=tun_ecn.dst, dst=self.pg0.local_ip4, tos=tc) for tc in tcs
+ ]
p_ip4_replys = [p_ip4.copy() for i in range(len(p_ip4_encaps))]
p_ip4_replys[2].tos = ecn
p_ip4_replys[3].tos = ecn
for i, p_ip4_encap in enumerate(p_ip4_encaps):
- p4 = (self.p_ether / p_ip4_encap / p_ip4 / self.p_payload)
- p4_reply = (p_ip4_replys[i] / self.p_payload)
+ p4 = self.p_ether / p_ip4_encap / p_ip4 / self.p_payload
+ p4_reply = p_ip4_replys[i] / self.p_payload
p4_reply.ttl -= 1
rx = self.send_and_expect(self.pg1, p4 * N_PACKETS, self.pg0)
n_packets_decapped += N_PACKETS
@@ -330,22 +371,17 @@ class TestIPIP(VppTestCase):
self.validate(p[1], p4_reply)
self.assert_packet_checksums_valid(p)
- err = self.statistics.get_err_counter(
- '/err/ipip4-input/packets decapsulated')
+ err = self.statistics.get_err_counter("/err/ipip4-input/packets decapsulated")
self.assertEqual(err, n_packets_decapped)
# IPv4 tunnel to IPv6
# for each encap tun will produce the same inner packet because it does
# not copy up fields from the payload
- p_ip4_encaps = [IP(src=tun.dst,
- dst=self.pg0.local_ip4,
- tos=tc) for tc in tcs]
+ p_ip4_encaps = [IP(src=tun.dst, dst=self.pg0.local_ip4, tos=tc) for tc in tcs]
p_ip6 = IPv6(src="1:2:3::4", dst=self.pg0.remote_ip6)
for p_ip4_encap in p_ip4_encaps:
- p6 = (self.p_ether /
- p_ip4_encap / p_ip6 /
- self.p_payload)
- p6_reply = (p_ip6 / self.p_payload)
+ p6 = self.p_ether / p_ip4_encap / p_ip6 / self.p_payload
+ p6_reply = p_ip6 / self.p_payload
p6_reply.hlim = 63
rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0)
n_packets_decapped += N_PACKETS
@@ -353,22 +389,21 @@ class TestIPIP(VppTestCase):
self.validate(p[1], p6_reply)
self.assert_packet_checksums_valid(p)
- err = self.statistics.get_err_counter(
- '/err/ipip4-input/packets decapsulated')
+ err = self.statistics.get_err_counter("/err/ipip4-input/packets decapsulated")
self.assertEqual(err, n_packets_decapped)
# IPv4 tunnel to IPv6
# tun_ecn copies the ECN bits from the encap to the inner
- p_ip4_encaps = [IP(src=tun_ecn.dst,
- dst=self.pg0.local_ip4,
- tos=tc) for tc in tcs]
+ p_ip4_encaps = [
+ IP(src=tun_ecn.dst, dst=self.pg0.local_ip4, tos=tc) for tc in tcs
+ ]
p_ip6 = IPv6(src="1:2:3::4", dst=self.pg0.remote_ip6)
p_ip6_replys = [p_ip6.copy() for i in range(len(p_ip4_encaps))]
p_ip6_replys[2].tc = ecn
p_ip6_replys[3].tc = ecn
for i, p_ip4_encap in enumerate(p_ip4_encaps):
- p6 = (self.p_ether / p_ip4_encap / p_ip6 / self.p_payload)
- p6_reply = (p_ip6_replys[i] / self.p_payload)
+ p6 = self.p_ether / p_ip4_encap / p_ip6 / self.p_payload
+ p6_reply = p_ip6_replys[i] / self.p_payload
p6_reply.hlim = 63
rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0)
n_packets_decapped += N_PACKETS
@@ -376,21 +411,23 @@ class TestIPIP(VppTestCase):
self.validate(p[1], p6_reply)
self.assert_packet_checksums_valid(p)
- err = self.statistics.get_err_counter(
- '/err/ipip4-input/packets decapsulated')
+ err = self.statistics.get_err_counter("/err/ipip4-input/packets decapsulated")
self.assertEqual(err, n_packets_decapped)
#
# Fragmentation / Reassembly and Re-fragmentation
#
rv = self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.pg1.sw_if_index,
- enable_ip4=1)
+ sw_if_index=self.pg1.sw_if_index, enable_ip4=1
+ )
- self.vapi.ip_reassembly_set(timeout_ms=1000, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10000,
- is_ip6=0)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=1000,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10000,
+ is_ip6=0,
+ )
# Send lots of fragments, verify reassembled packet
frags, p4_reply = self.generate_ip4_frags(3131, 1400)
@@ -406,8 +443,7 @@ class TestIPIP(VppTestCase):
for p in rx:
self.validate(p[1], p4_reply)
- err = self.statistics.get_err_counter(
- '/err/ipip4-input/packets decapsulated')
+ err = self.statistics.get_err_counter("/err/ipip4-input/packets decapsulated")
self.assertEqual(err, n_packets_decapped)
f = []
@@ -453,9 +489,12 @@ class TestIPIP(VppTestCase):
# send large packets through the tunnel, expect them to be fragmented
self.vapi.sw_interface_set_mtu(tun_dscp.sw_if_index, [600, 0, 0, 0])
- p4 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src="1.2.3.4", dst="130.67.0.1", tos=42) /
- UDP(sport=1234, dport=1234) / Raw(b'Q' * 1000))
+ p4 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="1.2.3.4", dst="130.67.0.1", tos=42)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"Q" * 1000)
+ )
rx = self.send_and_expect(self.pg0, p4 * 15, self.pg1, 30)
inners = []
for p in rx:
@@ -466,25 +505,25 @@ class TestIPIP(VppTestCase):
self.assertEqual(p[IP].ttl, 63)
def test_ipip_create(self):
- """ ipip create / delete interface test """
- rv = ipip_add_tunnel(self, '1.2.3.4', '2.3.4.5')
+ """ipip create / delete interface test"""
+ rv = ipip_add_tunnel(self, "1.2.3.4", "2.3.4.5")
sw_if_index = rv.sw_if_index
self.vapi.ipip_del_tunnel(sw_if_index)
def test_ipip_vrf_create(self):
- """ ipip create / delete interface VRF test """
+ """ipip create / delete interface VRF test"""
t = VppIpTable(self, 20)
t.add_vpp_config()
- rv = ipip_add_tunnel(self, '1.2.3.4', '2.3.4.5', table_id=20)
+ rv = ipip_add_tunnel(self, "1.2.3.4", "2.3.4.5", table_id=20)
sw_if_index = rv.sw_if_index
self.vapi.ipip_del_tunnel(sw_if_index)
def payload(self, len):
- return 'x' * len
+ return "x" * len
def test_mipip4(self):
- """ p2mp IPv4 tunnel Tests """
+ """p2mp IPv4 tunnel Tests"""
for itf in self.pg_interfaces[:2]:
#
@@ -499,11 +538,13 @@ class TestIPIP(VppTestCase):
# - assign an IP Addres
# - Add a route via the tunnel
#
- ipip_if = VppIpIpTunInterface(self, itf,
- itf.local_ip4,
- "0.0.0.0",
- mode=(VppEnum.vl_api_tunnel_mode_t.
- TUNNEL_API_MODE_MP))
+ ipip_if = VppIpIpTunInterface(
+ self,
+ itf,
+ itf.local_ip4,
+ "0.0.0.0",
+ mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP),
+ )
ipip_if.add_vpp_config()
ipip_if.admin_up()
ipip_if.config_ip4()
@@ -533,31 +574,40 @@ class TestIPIP(VppTestCase):
# route traffic via the peer
#
route_via_tun = VppIpRoute(
- self, route_addr, 32,
- [VppRoutePath(ipip_if._remote_hosts[ii].ip4,
- ipip_if.sw_if_index)])
+ self,
+ route_addr,
+ 32,
+ [VppRoutePath(ipip_if._remote_hosts[ii].ip4, ipip_if.sw_if_index)],
+ )
route_via_tun.add_vpp_config()
#
# Add a TEIB entry resolves the peer
#
- teib = VppTeib(self, ipip_if,
- ipip_if._remote_hosts[ii].ip4,
- itf._remote_hosts[ii].ip4)
+ teib = VppTeib(
+ self,
+ ipip_if,
+ ipip_if._remote_hosts[ii].ip4,
+ itf._remote_hosts[ii].ip4,
+ )
teib.add_vpp_config()
- self.logger.info(self.vapi.cli("sh adj nbr ipip0 %s" %
- ipip_if._remote_hosts[ii].ip4))
+ self.logger.info(
+ self.vapi.cli("sh adj nbr ipip0 %s" % ipip_if._remote_hosts[ii].ip4)
+ )
#
# Send a packet stream that is routed into the tunnel
# - packets are IPIP encapped
#
- inner = (IP(dst=route_addr, src="5.5.5.5") /
- UDP(sport=1234, dport=1234) /
- Raw(b'0x44' * 100))
- tx_e = [(Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- inner) for x in range(63)]
+ inner = (
+ IP(dst=route_addr, src="5.5.5.5")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"0x44" * 100)
+ )
+ tx_e = [
+ (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / inner)
+ for x in range(63)
+ ]
rxs = self.send_and_expect(self.pg0, tx_e, itf)
@@ -565,13 +615,16 @@ class TestIPIP(VppTestCase):
self.assertEqual(rx[IP].src, itf.local_ip4)
self.assertEqual(rx[IP].dst, itf._remote_hosts[ii].ip4)
- tx_i = [(Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=itf._remote_hosts[ii].ip4,
- dst=itf.local_ip4) /
- IP(src=self.pg0.local_ip4, dst=self.pg0.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'0x44' * 100)) for x in range(63)]
+ tx_i = [
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=itf._remote_hosts[ii].ip4, dst=itf.local_ip4)
+ / IP(src=self.pg0.local_ip4, dst=self.pg0.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"0x44" * 100)
+ )
+ for x in range(63)
+ ]
self.logger.info(self.vapi.cli("sh ipip tunnel-hash"))
rx = self.send_and_expect(self.pg0, tx_i, self.pg0)
@@ -593,12 +646,15 @@ class TestIPIP(VppTestCase):
#
# we can also send to the peer's address
#
- inner = (IP(dst=teib.peer, src="5.5.5.5") /
- UDP(sport=1234, dport=1234) /
- Raw(b'0x44' * 100))
- tx_e = [(Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- inner) for x in range(63)]
+ inner = (
+ IP(dst=teib.peer, src="5.5.5.5")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"0x44" * 100)
+ )
+ tx_e = [
+ (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / inner)
+ for x in range(63)
+ ]
rxs = self.send_and_expect(self.pg0, tx_e, itf)
@@ -616,12 +672,15 @@ class TestIPIP(VppTestCase):
#
# we should still be able to reach the peers from the new table
#
- inner = (IP(dst=teib.peer, src="5.5.5.5") /
- UDP(sport=1234, dport=1234) /
- Raw(b'0x44' * 100))
- tx_e = [(Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- inner) for x in range(63)]
+ inner = (
+ IP(dst=teib.peer, src="5.5.5.5")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"0x44" * 100)
+ )
+ tx_e = [
+ (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / inner)
+ for x in range(63)
+ ]
rxs = self.send_and_expect(self.pg2, tx_e, itf)
@@ -631,7 +690,7 @@ class TestIPIP(VppTestCase):
class TestIPIP6(VppTestCase):
- """ IPIP6 Test Case """
+ """IPIP6 Test Case"""
@classmethod
def setUpClass(cls):
@@ -665,30 +724,34 @@ class TestIPIP6(VppTestCase):
def setup_tunnel(self):
# IPv6 transport
- rv = ipip_add_tunnel(self,
- self.pg0.local_ip6,
- self.pg1.remote_ip6)
+ rv = ipip_add_tunnel(self, self.pg0.local_ip6, self.pg1.remote_ip6)
sw_if_index = rv.sw_if_index
self.tunnel_if_index = sw_if_index
self.vapi.sw_interface_set_flags(sw_if_index, 1)
self.vapi.sw_interface_set_unnumbered(
- sw_if_index=self.pg0.sw_if_index,
- unnumbered_sw_if_index=sw_if_index)
+ sw_if_index=self.pg0.sw_if_index, unnumbered_sw_if_index=sw_if_index
+ )
# Add IPv4 and IPv6 routes via tunnel interface
ip4_via_tunnel = VppIpRoute(
- self, "130.67.0.0", 16,
- [VppRoutePath("0.0.0.0",
- sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)])
+ self,
+ "130.67.0.0",
+ 16,
+ [
+ VppRoutePath(
+ "0.0.0.0", sw_if_index, proto=FibPathProto.FIB_PATH_NH_PROTO_IP4
+ )
+ ],
+ )
ip4_via_tunnel.add_vpp_config()
ip6_via_tunnel = VppIpRoute(
- self, "dead::", 16,
- [VppRoutePath("::",
- sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ self,
+ "dead::",
+ 16,
+ [VppRoutePath("::", sw_if_index, proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)],
+ )
ip6_via_tunnel.add_vpp_config()
self.tunnel_ip6_via_tunnel = ip6_via_tunnel
@@ -708,11 +771,15 @@ class TestIPIP6(VppTestCase):
p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
p_payload = UDP(sport=1234, dport=1234) / self.payload(payload_length)
p_ip6 = IPv6(src="1::1", dst=self.pg0.remote_ip6)
- outer_ip6 = (p_ether / IPv6(src=self.pg1.remote_ip6,
- dst=self.pg0.local_ip6) /
- IPv6ExtHdrFragment() / p_ip6 / p_payload)
+ outer_ip6 = (
+ p_ether
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.local_ip6)
+ / IPv6ExtHdrFragment()
+ / p_ip6
+ / p_payload
+ )
frags = fragment6(outer_ip6, fragment_size)
- p6_reply = (p_ip6 / p_payload)
+ p6_reply = p_ip6 / p_payload
p6_reply.hlim -= 1
return frags, p6_reply
@@ -720,58 +787,73 @@ class TestIPIP6(VppTestCase):
p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
p_payload = UDP(sport=1234, dport=1234) / self.payload(payload_length)
p_ip6 = IPv6(src="1::1", dst="dead::1")
- outer_ip6 = (p_ether / IPv6(src=self.pg1.remote_ip6,
- dst=self.pg0.local_ip6) /
- IPv6ExtHdrFragment() / p_ip6 / p_payload)
+ outer_ip6 = (
+ p_ether
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.local_ip6)
+ / IPv6ExtHdrFragment()
+ / p_ip6
+ / p_payload
+ )
frags = fragment6(outer_ip6, fragment_size)
p_ip6.hlim -= 1
- p6_reply = (IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6,
- hlim=63) / p_ip6 / p_payload)
+ p6_reply = (
+ IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6, hlim=63)
+ / p_ip6
+ / p_payload
+ )
return frags, p6_reply
def test_encap(self):
- """ ip{v4,v6} over ip6 test encap """
+ """ip{v4,v6} over ip6 test encap"""
p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
- p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh='UDP')
+ p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh="UDP")
p_ip4 = IP(src="1.2.3.4", dst="130.67.0.1", tos=42)
p_payload = UDP(sport=1234, dport=1234)
# Encapsulation
# IPv6 in to IPv6 tunnel
- p6 = (p_ether / p_ip6 / p_payload)
- p6_reply = (IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6,
- hlim=64) /
- p_ip6 / p_payload)
+ p6 = p_ether / p_ip6 / p_payload
+ p6_reply = (
+ IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6, hlim=64)
+ / p_ip6
+ / p_payload
+ )
p6_reply[1].hlim -= 1
rx = self.send_and_expect(self.pg0, p6 * 11, self.pg1)
for p in rx:
self.validate(p[1], p6_reply)
# IPv4 in to IPv6 tunnel
- p4 = (p_ether / p_ip4 / p_payload)
- p4_reply = (IPv6(src=self.pg0.local_ip6,
- dst=self.pg1.remote_ip6, hlim=64) /
- p_ip4 / p_payload)
+ p4 = p_ether / p_ip4 / p_payload
+ p4_reply = (
+ IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6, hlim=64)
+ / p_ip4
+ / p_payload
+ )
p4_reply[1].ttl -= 1
rx = self.send_and_expect(self.pg0, p4 * 11, self.pg1)
for p in rx:
self.validate(p[1], p4_reply)
def test_decap(self):
- """ ip{v4,v6} over ip6 test decap """
+ """ip{v4,v6} over ip6 test decap"""
p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
- p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh='UDP')
+ p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh="UDP")
p_ip4 = IP(src="1.2.3.4", dst=self.pg0.remote_ip4)
p_payload = UDP(sport=1234, dport=1234)
# Decapsulation
# IPv6 tunnel to IPv4
- p4 = (p_ether / IPv6(src=self.pg1.remote_ip6,
- dst=self.pg0.local_ip6) / p_ip4 / p_payload)
- p4_reply = (p_ip4 / p_payload)
+ p4 = (
+ p_ether
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.local_ip6)
+ / p_ip4
+ / p_payload
+ )
+ p4_reply = p_ip4 / p_payload
p4_reply.ttl -= 1
rx = self.send_and_expect(self.pg1, p4 * 11, self.pg0)
for p in rx:
@@ -779,9 +861,13 @@ class TestIPIP6(VppTestCase):
# IPv6 tunnel to IPv6
p_ip6 = IPv6(src="1:2:3::4", dst=self.pg0.remote_ip6)
- p6 = (p_ether / IPv6(src=self.pg1.remote_ip6,
- dst=self.pg0.local_ip6) / p_ip6 / p_payload)
- p6_reply = (p_ip6 / p_payload)
+ p6 = (
+ p_ether
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.local_ip6)
+ / p_ip6
+ / p_payload
+ )
+ p6_reply = p_ip6 / p_payload
p6_reply.hlim = 63
rx = self.send_and_expect(self.pg1, p6 * 11, self.pg0)
for p in rx:
@@ -790,10 +876,10 @@ class TestIPIP6(VppTestCase):
def verify_ip4ip6_encaps(self, a, p_ip4s, p_ip6_encaps):
for i, p_ip4 in enumerate(p_ip4s):
p_ip4.dst = a
- p4 = (self.p_ether / p_ip4 / self.p_payload)
+ p4 = self.p_ether / p_ip4 / self.p_payload
p_ip4_inner = p_ip4
p_ip4_inner.ttl -= 1
- p6_reply = (p_ip6_encaps[i] / p_ip4_inner / self.p_payload)
+ p6_reply = p_ip6_encaps[i] / p_ip4_inner / self.p_payload
rx = self.send_and_expect(self.pg0, p4 * N_PACKETS, self.pg1)
for p in rx:
self.validate(p[1], p6_reply)
@@ -802,17 +888,17 @@ class TestIPIP6(VppTestCase):
def verify_ip6ip6_encaps(self, a, p_ip6s, p_ip6_encaps):
for i, p_ip6 in enumerate(p_ip6s):
p_ip6.dst = a
- p6 = (self.p_ether / p_ip6 / self.p_payload)
+ p6 = self.p_ether / p_ip6 / self.p_payload
p_inner_ip6 = p_ip6
p_inner_ip6.hlim -= 1
- p6_reply = (p_ip6_encaps[i] / p_inner_ip6 / self.p_payload)
+ p6_reply = p_ip6_encaps[i] / p_inner_ip6 / self.p_payload
rx = self.send_and_expect(self.pg0, p6 * N_PACKETS, self.pg1)
for p in rx:
self.validate(p[1], p6_reply)
self.assert_packet_checksums_valid(p)
def test_ipip6(self):
- """ ip{v4,v6} over ip6 test """
+ """ip{v4,v6} over ip6 test"""
# that's annoying
self.destroy_tunnel()
@@ -822,7 +908,7 @@ class TestIPIP6(VppTestCase):
e = VppEnum.vl_api_tunnel_encap_decap_flags_t
d = VppEnum.vl_api_ip_dscp_t
self.p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
- self.p_payload = UDP(sport=1234, dport=1234) / Raw(b'X' * 100)
+ self.p_payload = UDP(sport=1234, dport=1234) / Raw(b"X" * 100)
# create a TOS byte by shifting a DSCP code point 2 bits. those 2 bits
# are for the ECN.
@@ -836,7 +922,8 @@ class TestIPIP6(VppTestCase):
self.pg0,
self.pg0.local_ip6,
self.pg1.remote_hosts[0].ip6,
- flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP)
+ flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP,
+ )
tun_dscp.add_vpp_config()
# IPv4 transport that copies the DCSP and ECN from the payload
tun_dscp_ecn = VppIpIpTunInterface(
@@ -844,8 +931,11 @@ class TestIPIP6(VppTestCase):
self.pg0,
self.pg0.local_ip6,
self.pg1.remote_hosts[1].ip6,
- flags=(e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP |
- e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN))
+ flags=(
+ e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP
+ | e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN
+ ),
+ )
tun_dscp_ecn.add_vpp_config()
# IPv4 transport that copies the ECN from the payload and sets the
# DF bit on encap. copies the ECN on decap
@@ -854,9 +944,12 @@ class TestIPIP6(VppTestCase):
self.pg0,
self.pg0.local_ip6,
self.pg1.remote_hosts[2].ip6,
- flags=(e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN |
- e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_SET_DF |
- e.TUNNEL_API_ENCAP_DECAP_FLAG_DECAP_COPY_ECN))
+ flags=(
+ e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN
+ | e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_SET_DF
+ | e.TUNNEL_API_ENCAP_DECAP_FLAG_DECAP_COPY_ECN
+ ),
+ )
tun_ecn.add_vpp_config()
# IPv4 transport that sets a fixed DSCP in the encap and copies
# the DF bit
@@ -866,7 +959,8 @@ class TestIPIP6(VppTestCase):
self.pg0.local_ip6,
self.pg1.remote_hosts[3].ip6,
dscp=d.IP_API_DSCP_AF11,
- flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DF)
+ flags=e.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DF,
+ )
tun.add_vpp_config()
# array of all the tunnels
@@ -877,22 +971,26 @@ class TestIPIP6(VppTestCase):
a6s = ["" for i in range(len(tuns))]
# IP headers for inner packets with each combination of DSCp/ECN tested
- p_ip6s = [IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=dscp),
- IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=dscp_ecn),
- IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=ecn),
- IPv6(src="1::1", dst="DEAD::1", nh='UDP', tc=0xff)]
- p_ip4s = [IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp, flags='DF'),
- IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp_ecn),
- IP(src="1.2.3.4", dst="130.67.0.1", tos=ecn),
- IP(src="1.2.3.4", dst="130.67.0.1", tos=0xff)]
+ p_ip6s = [
+ IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=dscp),
+ IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=dscp_ecn),
+ IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=ecn),
+ IPv6(src="1::1", dst="DEAD::1", nh="UDP", tc=0xFF),
+ ]
+ p_ip4s = [
+ IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp, flags="DF"),
+ IP(src="1.2.3.4", dst="130.67.0.1", tos=dscp_ecn),
+ IP(src="1.2.3.4", dst="130.67.0.1", tos=ecn),
+ IP(src="1.2.3.4", dst="130.67.0.1", tos=0xFF),
+ ]
# Configure each tunnel
for i, t in enumerate(tuns):
# Set interface up and enable IP on it
self.vapi.sw_interface_set_flags(t.sw_if_index, 1)
self.vapi.sw_interface_set_unnumbered(
- sw_if_index=self.pg0.sw_if_index,
- unnumbered_sw_if_index=t.sw_if_index)
+ sw_if_index=self.pg0.sw_if_index, unnumbered_sw_if_index=t.sw_if_index
+ )
# prefix for route / destination address for packets
a4s[i] = "130.67.%d.0" % i
@@ -900,17 +998,29 @@ class TestIPIP6(VppTestCase):
# Add IPv4 and IPv6 routes via tunnel interface
ip4_via_tunnel = VppIpRoute(
- self, a4s[i], 24,
- [VppRoutePath("0.0.0.0",
- t.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)])
+ self,
+ a4s[i],
+ 24,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ t.sw_if_index,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ )
+ ],
+ )
ip4_via_tunnel.add_vpp_config()
ip6_via_tunnel = VppIpRoute(
- self, a6s[i], 64,
- [VppRoutePath("::",
- t.sw_if_index,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ self,
+ a6s[i],
+ 64,
+ [
+ VppRoutePath(
+ "::", t.sw_if_index, proto=FibPathProto.FIB_PATH_NH_PROTO_IP6
+ )
+ ],
+ )
ip6_via_tunnel.add_vpp_config()
#
@@ -920,10 +1030,10 @@ class TestIPIP6(VppTestCase):
# tun_dscp copies only the dscp
# expected TC values are thus only the DCSP value is present from the
# inner
- exp_tcs = [dscp, dscp, 0, 0xfc]
- p_ip6_encaps = [IPv6(src=self.pg0.local_ip6,
- dst=tun_dscp.dst,
- tc=tc) for tc in exp_tcs]
+ exp_tcs = [dscp, dscp, 0, 0xFC]
+ p_ip6_encaps = [
+ IPv6(src=self.pg0.local_ip6, dst=tun_dscp.dst, tc=tc) for tc in exp_tcs
+ ]
# IPv4 in to IPv4 tunnel
self.verify_ip4ip6_encaps(a4s[0], p_ip4s, p_ip6_encaps)
@@ -931,28 +1041,29 @@ class TestIPIP6(VppTestCase):
self.verify_ip6ip6_encaps(a6s[0], p_ip6s, p_ip6_encaps)
# tun_dscp_ecn copies the dscp and the ecn
- exp_tcs = [dscp, dscp_ecn, ecn, 0xff]
- p_ip6_encaps = [IPv6(src=self.pg0.local_ip6,
- dst=tun_dscp_ecn.dst,
- tc=tc) for tc in exp_tcs]
+ exp_tcs = [dscp, dscp_ecn, ecn, 0xFF]
+ p_ip6_encaps = [
+ IPv6(src=self.pg0.local_ip6, dst=tun_dscp_ecn.dst, tc=tc) for tc in exp_tcs
+ ]
self.verify_ip4ip6_encaps(a4s[1], p_ip4s, p_ip6_encaps)
self.verify_ip6ip6_encaps(a6s[1], p_ip6s, p_ip6_encaps)
# tun_ecn copies only the ecn and always sets DF
exp_tcs = [0, ecn, ecn, ecn]
- p_ip6_encaps = [IPv6(src=self.pg0.local_ip6,
- dst=tun_ecn.dst,
- tc=tc) for tc in exp_tcs]
+ p_ip6_encaps = [
+ IPv6(src=self.pg0.local_ip6, dst=tun_ecn.dst, tc=tc) for tc in exp_tcs
+ ]
self.verify_ip4ip6_encaps(a4s[2], p_ip4s, p_ip6_encaps)
self.verify_ip6ip6_encaps(a6s[2], p_ip6s, p_ip6_encaps)
# tun sets a fixed dscp
fixed_dscp = tun.dscp << 2
- p_ip6_encaps = [IPv6(src=self.pg0.local_ip6,
- dst=tun.dst,
- tc=fixed_dscp) for i in range(len(p_ip4s))]
+ p_ip6_encaps = [
+ IPv6(src=self.pg0.local_ip6, dst=tun.dst, tc=fixed_dscp)
+ for i in range(len(p_ip4s))
+ ]
self.verify_ip4ip6_encaps(a4s[3], p_ip4s, p_ip6_encaps)
self.verify_ip6ip6_encaps(a6s[3], p_ip6s, p_ip6_encaps)
@@ -961,7 +1072,8 @@ class TestIPIP6(VppTestCase):
# Decapsulation
#
n_packets_decapped = self.statistics.get_err_counter(
- '/err/ipip6-input/packets decapsulated')
+ "/err/ipip6-input/packets decapsulated"
+ )
self.p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
@@ -970,15 +1082,13 @@ class TestIPIP6(VppTestCase):
# one overlay packet and all combinations of its encap
p_ip4 = IP(src="1.2.3.4", dst=self.pg0.remote_ip4)
- p_ip6_encaps = [IPv6(src=tun.dst,
- dst=self.pg0.local_ip6,
- tc=tc) for tc in tcs]
+ p_ip6_encaps = [IPv6(src=tun.dst, dst=self.pg0.local_ip6, tc=tc) for tc in tcs]
# for each encap tun will produce the same inner packet because it does
# not copy up fields from the payload
for p_ip6_encap in p_ip6_encaps:
- p6 = (self.p_ether / p_ip6_encap / p_ip4 / self.p_payload)
- p4_reply = (p_ip4 / self.p_payload)
+ p6 = self.p_ether / p_ip6_encap / p_ip4 / self.p_payload
+ p4_reply = p_ip4 / self.p_payload
p4_reply.ttl -= 1
rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0)
n_packets_decapped += N_PACKETS
@@ -986,20 +1096,19 @@ class TestIPIP6(VppTestCase):
self.validate(p[1], p4_reply)
self.assert_packet_checksums_valid(p)
- err = self.statistics.get_err_counter(
- '/err/ipip6-input/packets decapsulated')
+ err = self.statistics.get_err_counter("/err/ipip6-input/packets decapsulated")
self.assertEqual(err, n_packets_decapped)
# tun_ecn copies the ECN bits from the encap to the inner
- p_ip6_encaps = [IPv6(src=tun_ecn.dst,
- dst=self.pg0.local_ip6,
- tc=tc) for tc in tcs]
+ p_ip6_encaps = [
+ IPv6(src=tun_ecn.dst, dst=self.pg0.local_ip6, tc=tc) for tc in tcs
+ ]
p_ip4_replys = [p_ip4.copy() for i in range(len(p_ip6_encaps))]
p_ip4_replys[2].tos = ecn
p_ip4_replys[3].tos = ecn
for i, p_ip6_encap in enumerate(p_ip6_encaps):
- p6 = (self.p_ether / p_ip6_encap / p_ip4 / self.p_payload)
- p4_reply = (p_ip4_replys[i] / self.p_payload)
+ p6 = self.p_ether / p_ip6_encap / p_ip4 / self.p_payload
+ p4_reply = p_ip4_replys[i] / self.p_payload
p4_reply.ttl -= 1
rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0)
n_packets_decapped += N_PACKETS
@@ -1007,20 +1116,17 @@ class TestIPIP6(VppTestCase):
self.validate(p[1], p4_reply)
self.assert_packet_checksums_valid(p)
- err = self.statistics.get_err_counter(
- '/err/ipip6-input/packets decapsulated')
+ err = self.statistics.get_err_counter("/err/ipip6-input/packets decapsulated")
self.assertEqual(err, n_packets_decapped)
# IPv6 tunnel to IPv6
# for each encap tun will produce the same inner packet because it does
# not copy up fields from the payload
- p_ip6_encaps = [IPv6(src=tun.dst,
- dst=self.pg0.local_ip6,
- tc=tc) for tc in tcs]
+ p_ip6_encaps = [IPv6(src=tun.dst, dst=self.pg0.local_ip6, tc=tc) for tc in tcs]
p_ip6 = IPv6(src="1:2:3::4", dst=self.pg0.remote_ip6)
for p_ip6_encap in p_ip6_encaps:
- p6 = (self.p_ether / p_ip6_encap / p_ip6 / self.p_payload)
- p6_reply = (p_ip6 / self.p_payload)
+ p6 = self.p_ether / p_ip6_encap / p_ip6 / self.p_payload
+ p6_reply = p_ip6 / self.p_payload
p6_reply.hlim = 63
rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0)
n_packets_decapped += N_PACKETS
@@ -1028,22 +1134,21 @@ class TestIPIP6(VppTestCase):
self.validate(p[1], p6_reply)
self.assert_packet_checksums_valid(p)
- err = self.statistics.get_err_counter(
- '/err/ipip6-input/packets decapsulated')
+ err = self.statistics.get_err_counter("/err/ipip6-input/packets decapsulated")
self.assertEqual(err, n_packets_decapped)
# IPv6 tunnel to IPv6
# tun_ecn copies the ECN bits from the encap to the inner
- p_ip6_encaps = [IPv6(src=tun_ecn.dst,
- dst=self.pg0.local_ip6,
- tc=tc) for tc in tcs]
+ p_ip6_encaps = [
+ IPv6(src=tun_ecn.dst, dst=self.pg0.local_ip6, tc=tc) for tc in tcs
+ ]
p_ip6 = IPv6(src="1:2:3::4", dst=self.pg0.remote_ip6)
p_ip6_replys = [p_ip6.copy() for i in range(len(p_ip6_encaps))]
p_ip6_replys[2].tc = ecn
p_ip6_replys[3].tc = ecn
for i, p_ip6_encap in enumerate(p_ip6_encaps):
- p6 = (self.p_ether / p_ip6_encap / p_ip6 / self.p_payload)
- p6_reply = (p_ip6_replys[i] / self.p_payload)
+ p6 = self.p_ether / p_ip6_encap / p_ip6 / self.p_payload
+ p6_reply = p_ip6_replys[i] / self.p_payload
p6_reply.hlim = 63
rx = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0)
n_packets_decapped += N_PACKETS
@@ -1051,15 +1156,14 @@ class TestIPIP6(VppTestCase):
self.validate(p[1], p6_reply)
self.assert_packet_checksums_valid(p)
- err = self.statistics.get_err_counter(
- '/err/ipip6-input/packets decapsulated')
+ err = self.statistics.get_err_counter("/err/ipip6-input/packets decapsulated")
self.assertEqual(err, n_packets_decapped)
def test_frag(self):
- """ ip{v4,v6} over ip6 test frag """
+ """ip{v4,v6} over ip6 test frag"""
p_ether = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
- p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh='UDP')
+ p_ip6 = IPv6(src="1::1", dst="DEAD::1", tc=42, nh="UDP")
p_ip4 = IP(src="1.2.3.4", dst=self.pg0.remote_ip4)
p_payload = UDP(sport=1234, dport=1234)
@@ -1067,17 +1171,21 @@ class TestIPIP6(VppTestCase):
# Fragmentation / Reassembly and Re-fragmentation
#
rv = self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.pg1.sw_if_index,
- enable_ip6=1)
+ sw_if_index=self.pg1.sw_if_index, enable_ip6=1
+ )
- self.vapi.ip_reassembly_set(timeout_ms=1000, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10000,
- is_ip6=1)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=1000,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10000,
+ is_ip6=1,
+ )
# Send lots of fragments, verify reassembled packet
before_cnt = self.statistics.get_err_counter(
- '/err/ipip6-input/packets decapsulated')
+ "/err/ipip6-input/packets decapsulated"
+ )
frags, p6_reply = self.generate_ip6_frags(3131, 1400)
f = []
for i in range(0, 1000):
@@ -1090,8 +1198,7 @@ class TestIPIP6(VppTestCase):
for p in rx:
self.validate(p[1], p6_reply)
- cnt = self.statistics.get_err_counter(
- '/err/ipip6-input/packets decapsulated')
+ cnt = self.statistics.get_err_counter("/err/ipip6-input/packets decapsulated")
self.assertEqual(cnt, before_cnt + 1000)
f = []
@@ -1117,10 +1224,12 @@ class TestIPIP6(VppTestCase):
# IPv6 in to IPv6 tunnel
p_payload = UDP(sport=1234, dport=1234) / self.payload(1300)
- p6 = (p_ether / p_ip6 / p_payload)
- p6_reply = (IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6,
- hlim=63) /
- p_ip6 / p_payload)
+ p6 = p_ether / p_ip6 / p_payload
+ p6_reply = (
+ IPv6(src=self.pg0.local_ip6, dst=self.pg1.remote_ip6, hlim=63)
+ / p_ip6
+ / p_payload
+ )
p6_reply[1].hlim -= 1
self.pg_enable_capture()
self.pg0.add_stream(p6)
@@ -1151,47 +1260,49 @@ class TestIPIP6(VppTestCase):
self.validate(reass_pkt, p6_reply)
def test_ip6_mpls_frag(self):
- """ Test fragmenting IPv6 over MPLS """
+ """Test fragmenting IPv6 over MPLS"""
# IPv6 packets must be locally generated to be fragmented
# the use of tunnel encaps
tun_dst = VppIpRoute(
- self, "1000::1", 128,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index,
- labels=[VppMplsLabel(32)])]).add_vpp_config()
+ self,
+ "1000::1",
+ 128,
+ [
+ VppRoutePath(
+ self.pg1.remote_ip6, self.pg1.sw_if_index, labels=[VppMplsLabel(32)]
+ )
+ ],
+ ).add_vpp_config()
tun = VppIpIpTunInterface(
- self,
- self.pg0,
- self.pg0.local_ip6,
- "1000::1").add_vpp_config()
+ self, self.pg0, self.pg0.local_ip6, "1000::1"
+ ).add_vpp_config()
tun.admin_up()
tun.config_ip6()
tun.config_ip4()
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [2000, 0, 0, 0])
-
- p_6k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=tun.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 2000))
- p_2k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=tun.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 1000))
- p_1k = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=tun.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(b'0xa' * 600))
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [2000, 0, 0, 0])
+
+ p_6k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 2000)
+ )
+ p_2k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 1000)
+ )
+ p_1k = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=tun.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"0xa" * 600)
+ )
# this is now the interface MTU frags
rxs = self.send_and_expect(self.pg0, [p_6k], self.pg1, n_rx=4)
@@ -1204,26 +1315,26 @@ class TestIPIP6(VppTestCase):
self.send_and_expect(self.pg0, [p_1k], self.pg1)
def test_ipip_create(self):
- """ ipip create / delete interface test """
- rv = ipip_add_tunnel(self, '1.2.3.4', '2.3.4.5')
+ """ipip create / delete interface test"""
+ rv = ipip_add_tunnel(self, "1.2.3.4", "2.3.4.5")
sw_if_index = rv.sw_if_index
self.vapi.ipip_del_tunnel(sw_if_index)
def test_ipip_vrf_create(self):
- """ ipip create / delete interface VRF test """
+ """ipip create / delete interface VRF test"""
t = VppIpTable(self, 20)
t.add_vpp_config()
- rv = ipip_add_tunnel(self, '1.2.3.4', '2.3.4.5', table_id=20)
+ rv = ipip_add_tunnel(self, "1.2.3.4", "2.3.4.5", table_id=20)
sw_if_index = rv.sw_if_index
self.vapi.ipip_del_tunnel(sw_if_index)
def payload(self, len):
- return 'x' * len
+ return "x" * len
class TestIPIPMPLS(VppTestCase):
- """ MPLS Test Case """
+ """MPLS Test Case"""
@classmethod
def setUpClass(cls):
@@ -1254,62 +1365,69 @@ class TestIPIPMPLS(VppTestCase):
i.admin_down()
def test_mpls(self):
- """ MPLS over ip{6,4} test """
+ """MPLS over ip{6,4} test"""
tbl = VppMplsTable(self, 0)
tbl.add_vpp_config()
self.p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
- self.p_payload = UDP(sport=1234, dport=1234) / Raw(b'X' * 100)
+ self.p_payload = UDP(sport=1234, dport=1234) / Raw(b"X" * 100)
f = FibPathProto
# IPv4 transport
tun4 = VppIpIpTunInterface(
- self,
- self.pg1,
- self.pg1.local_ip4,
- self.pg1.remote_ip4).add_vpp_config()
+ self, self.pg1, self.pg1.local_ip4, self.pg1.remote_ip4
+ ).add_vpp_config()
tun4.admin_up()
tun4.config_ip4()
tun4.enable_mpls()
# IPv6 transport
tun6 = VppIpIpTunInterface(
- self,
- self.pg1,
- self.pg1.local_ip6,
- self.pg1.remote_ip6).add_vpp_config()
+ self, self.pg1, self.pg1.local_ip6, self.pg1.remote_ip6
+ ).add_vpp_config()
tun6.admin_up()
tun6.config_ip6()
tun6.enable_mpls()
# ip routes into the tunnels with output labels
- r4 = VppIpRoute(self, "1.1.1.1", 32,
- [VppRoutePath(
- tun4.remote_ip4,
- tun4.sw_if_index,
- labels=[VppMplsLabel(44)])]).add_vpp_config()
- r6 = VppIpRoute(self, "1::1", 128,
- [VppRoutePath(
- tun6.remote_ip6,
- tun6.sw_if_index,
- labels=[VppMplsLabel(66)])]).add_vpp_config()
+ r4 = VppIpRoute(
+ self,
+ "1.1.1.1",
+ 32,
+ [
+ VppRoutePath(
+ tun4.remote_ip4, tun4.sw_if_index, labels=[VppMplsLabel(44)]
+ )
+ ],
+ ).add_vpp_config()
+ r6 = VppIpRoute(
+ self,
+ "1::1",
+ 128,
+ [
+ VppRoutePath(
+ tun6.remote_ip6, tun6.sw_if_index, labels=[VppMplsLabel(66)]
+ )
+ ],
+ ).add_vpp_config()
# deag MPLS routes from the tunnel
- r4 = VppMplsRoute(self, 44, 1,
- [VppRoutePath(
- self.pg0.remote_ip4,
- self.pg0.sw_if_index)]).add_vpp_config()
- r6 = VppMplsRoute(self, 66, 1,
- [VppRoutePath(
- self.pg0.remote_ip6,
- self.pg0.sw_if_index)],
- eos_proto=f.FIB_PATH_NH_PROTO_IP6).add_vpp_config()
+ r4 = VppMplsRoute(
+ self, 44, 1, [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index)]
+ ).add_vpp_config()
+ r6 = VppMplsRoute(
+ self,
+ 66,
+ 1,
+ [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)],
+ eos_proto=f.FIB_PATH_NH_PROTO_IP6,
+ ).add_vpp_config()
#
# Tunnel Encap
#
- p4 = (self.p_ether / IP(src="2.2.2.2", dst="1.1.1.1") / self.p_payload)
+ p4 = self.p_ether / IP(src="2.2.2.2", dst="1.1.1.1") / self.p_payload
rxs = self.send_and_expect(self.pg0, p4 * N_PACKETS, self.pg1)
@@ -1321,7 +1439,7 @@ class TestIPIPMPLS(VppTestCase):
self.assertEqual(inner.src, "2.2.2.2")
self.assertEqual(inner.dst, "1.1.1.1")
- p6 = (self.p_ether / IPv6(src="2::2", dst="1::1") / self.p_payload)
+ p6 = self.p_ether / IPv6(src="2::2", dst="1::1") / self.p_payload
rxs = self.send_and_expect(self.pg0, p6 * N_PACKETS, self.pg1)
@@ -1336,13 +1454,13 @@ class TestIPIPMPLS(VppTestCase):
#
# Tunnel Decap
#
- p4 = (self.p_ether /
- IP(src=self.pg1.remote_ip4,
- dst=self.pg1.local_ip4) /
- MPLS(label=44, ttl=4) /
- IP(src="1.1.1.1",
- dst="2.2.2.2") /
- self.p_payload)
+ p4 = (
+ self.p_ether
+ / IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4)
+ / MPLS(label=44, ttl=4)
+ / IP(src="1.1.1.1", dst="2.2.2.2")
+ / self.p_payload
+ )
rxs = self.send_and_expect(self.pg1, p4 * N_PACKETS, self.pg0)
@@ -1350,13 +1468,13 @@ class TestIPIPMPLS(VppTestCase):
self.assertEqual(rx[IP].src, "1.1.1.1")
self.assertEqual(rx[IP].dst, "2.2.2.2")
- p6 = (self.p_ether /
- IPv6(src=self.pg1.remote_ip6,
- dst=self.pg1.local_ip6) /
- MPLS(label=66, ttl=4) /
- IPv6(src="1::1",
- dst="2::2") /
- self.p_payload)
+ p6 = (
+ self.p_ether
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.local_ip6)
+ / MPLS(label=66, ttl=4)
+ / IPv6(src="1::1", dst="2::2")
+ / self.p_payload
+ )
rxs = self.send_and_expect(self.pg1, p6 * N_PACKETS, self.pg0)
@@ -1368,5 +1486,5 @@ class TestIPIPMPLS(VppTestCase):
tun6.disable_mpls()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ipsec_ah.py b/test/test_ipsec_ah.py
index 8f8b2bf1550..190bde78f56 100644
--- a/test/test_ipsec_ah.py
+++ b/test/test_ipsec_ah.py
@@ -8,13 +8,23 @@ from scapy.layers.l2 import Ether
from scapy.packet import Raw
from framework import VppTestRunner
-from template_ipsec import TemplateIpsec, IpsecTra46Tests, IpsecTun46Tests, \
- config_tun_params, config_tra_params, IPsecIPv4Params, IPsecIPv6Params, \
- IpsecTra4, IpsecTun4, IpsecTra6, IpsecTun6, \
- IpsecTun6HandoffTests, IpsecTun4HandoffTests
+from template_ipsec import (
+ TemplateIpsec,
+ IpsecTra46Tests,
+ IpsecTun46Tests,
+ config_tun_params,
+ config_tra_params,
+ IPsecIPv4Params,
+ IPsecIPv6Params,
+ IpsecTra4,
+ IpsecTun4,
+ IpsecTra6,
+ IpsecTun6,
+ IpsecTun6HandoffTests,
+ IpsecTun4HandoffTests,
+)
from template_ipsec import IpsecTcpTests
-from vpp_ipsec import VppIpsecSA, VppIpsecSpd, VppIpsecSpdEntry,\
- VppIpsecSpdItfBinding
+from vpp_ipsec import VppIpsecSA, VppIpsecSpd, VppIpsecSpdEntry, VppIpsecSpdItfBinding
from vpp_ip_route import VppIpRoute, VppRoutePath
from vpp_ip import DpoProto
from vpp_papi import VppEnum
@@ -41,6 +51,7 @@ class ConfigIpsecAH(TemplateIpsec):
--- --- ---
"""
+
encryption_type = AH
net_objs = []
tra4_encrypt_node_name = "ah4-encrypt"
@@ -79,13 +90,11 @@ class ConfigIpsecAH(TemplateIpsec):
self.tun_spd.add_vpp_config()
self.net_objs.append(self.tun_spd)
- b = VppIpsecSpdItfBinding(self, self.tra_spd,
- self.tra_if)
+ b = VppIpsecSpdItfBinding(self, self.tra_spd, self.tra_if)
b.add_vpp_config()
self.net_objs.append(b)
- b = VppIpsecSpdItfBinding(self, self.tun_spd,
- self.tun_if)
+ b = VppIpsecSpdItfBinding(self, self.tun_spd, self.tun_if)
b.add_vpp_config()
self.net_objs.append(b)
@@ -97,10 +106,16 @@ class ConfigIpsecAH(TemplateIpsec):
config_tun_params(p, self.encryption_type, self.tun_if)
for p in params:
d = DpoProto.DPO_PROTO_IP6 if p.is_ipv6 else DpoProto.DPO_PROTO_IP4
- r = VppIpRoute(self, p.remote_tun_if_host, p.addr_len,
- [VppRoutePath(self.tun_if.remote_addr[p.addr_type],
- 0xffffffff,
- proto=d)])
+ r = VppIpRoute(
+ self,
+ p.remote_tun_if_host,
+ p.addr_len,
+ [
+ VppRoutePath(
+ self.tun_if.remote_addr[p.addr_type], 0xFFFFFFFF, proto=d
+ )
+ ],
+ )
r.add_vpp_config()
self.net_objs.append(r)
self.logger.info(self.vapi.ppcli("show ipsec all"))
@@ -130,74 +145,116 @@ class ConfigIpsecAH(TemplateIpsec):
params.outer_hop_limit = 253
params.outer_flow_label = 0x12345
- params.tun_sa_in = VppIpsecSA(self, scapy_tun_sa_id, scapy_tun_spi,
- auth_algo_vpp_id, auth_key,
- crypt_algo_vpp_id, crypt_key,
- self.vpp_ah_protocol,
- self.tun_if.local_addr[addr_type],
- self.tun_if.remote_addr[addr_type],
- tun_flags=tun_flags,
- flags=flags,
- dscp=params.dscp)
-
- params.tun_sa_out = VppIpsecSA(self, vpp_tun_sa_id, vpp_tun_spi,
- auth_algo_vpp_id, auth_key,
- crypt_algo_vpp_id, crypt_key,
- self.vpp_ah_protocol,
- self.tun_if.remote_addr[addr_type],
- self.tun_if.local_addr[addr_type],
- tun_flags=tun_flags,
- flags=flags,
- dscp=params.dscp)
+ params.tun_sa_in = VppIpsecSA(
+ self,
+ scapy_tun_sa_id,
+ scapy_tun_spi,
+ auth_algo_vpp_id,
+ auth_key,
+ crypt_algo_vpp_id,
+ crypt_key,
+ self.vpp_ah_protocol,
+ self.tun_if.local_addr[addr_type],
+ self.tun_if.remote_addr[addr_type],
+ tun_flags=tun_flags,
+ flags=flags,
+ dscp=params.dscp,
+ )
+
+ params.tun_sa_out = VppIpsecSA(
+ self,
+ vpp_tun_sa_id,
+ vpp_tun_spi,
+ auth_algo_vpp_id,
+ auth_key,
+ crypt_algo_vpp_id,
+ crypt_key,
+ self.vpp_ah_protocol,
+ self.tun_if.remote_addr[addr_type],
+ self.tun_if.local_addr[addr_type],
+ tun_flags=tun_flags,
+ flags=flags,
+ dscp=params.dscp,
+ )
objs.append(params.tun_sa_in)
objs.append(params.tun_sa_out)
- params.spd_policy_in_any = VppIpsecSpdEntry(self, self.tun_spd,
- vpp_tun_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_AH)
- params.spd_policy_out_any = VppIpsecSpdEntry(self, self.tun_spd,
- vpp_tun_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_AH,
- is_outbound=0)
+ params.spd_policy_in_any = VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ vpp_tun_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_AH,
+ )
+ params.spd_policy_out_any = VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ vpp_tun_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_AH,
+ is_outbound=0,
+ )
objs.append(params.spd_policy_out_any)
objs.append(params.spd_policy_in_any)
- e1 = VppIpsecSpdEntry(self, self.tun_spd, vpp_tun_sa_id,
- remote_tun_if_host,
- remote_tun_if_host,
- self.pg1.remote_addr[addr_type],
- self.pg1.remote_addr[addr_type],
- 0, priority=10,
- policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- is_outbound=0)
- e2 = VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
- self.pg1.remote_addr[addr_type],
- self.pg1.remote_addr[addr_type],
- remote_tun_if_host,
- remote_tun_if_host,
- 0, policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- priority=10)
- e3 = VppIpsecSpdEntry(self, self.tun_spd, vpp_tun_sa_id,
- remote_tun_if_host,
- remote_tun_if_host,
- self.pg0.local_addr[addr_type],
- self.pg0.local_addr[addr_type],
- 0, priority=20,
- policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- is_outbound=0)
- e4 = VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
- self.pg0.local_addr[addr_type],
- self.pg0.local_addr[addr_type],
- remote_tun_if_host,
- remote_tun_if_host,
- 0, policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- priority=20)
+ e1 = VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ vpp_tun_sa_id,
+ remote_tun_if_host,
+ remote_tun_if_host,
+ self.pg1.remote_addr[addr_type],
+ self.pg1.remote_addr[addr_type],
+ 0,
+ priority=10,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ is_outbound=0,
+ )
+ e2 = VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ scapy_tun_sa_id,
+ self.pg1.remote_addr[addr_type],
+ self.pg1.remote_addr[addr_type],
+ remote_tun_if_host,
+ remote_tun_if_host,
+ 0,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ priority=10,
+ )
+ e3 = VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ vpp_tun_sa_id,
+ remote_tun_if_host,
+ remote_tun_if_host,
+ self.pg0.local_addr[addr_type],
+ self.pg0.local_addr[addr_type],
+ 0,
+ priority=20,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ is_outbound=0,
+ )
+ e4 = VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ scapy_tun_sa_id,
+ self.pg0.local_addr[addr_type],
+ self.pg0.local_addr[addr_type],
+ remote_tun_if_host,
+ remote_tun_if_host,
+ 0,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ priority=20,
+ )
objs = objs + [e1, e2, e3, e4]
@@ -218,49 +275,92 @@ class ConfigIpsecAH(TemplateIpsec):
crypt_key = params.crypt_key
addr_any = params.addr_any
addr_bcast = params.addr_bcast
- flags = params.flags | (VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY)
+ flags = params.flags | (
+ VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY
+ )
e = VppEnum.vl_api_ipsec_spd_action_t
objs = []
- params.tra_sa_in = VppIpsecSA(self, scapy_tra_sa_id, scapy_tra_spi,
- auth_algo_vpp_id, auth_key,
- crypt_algo_vpp_id, crypt_key,
- self.vpp_ah_protocol,
- flags=flags)
- params.tra_sa_out = VppIpsecSA(self, vpp_tra_sa_id, vpp_tra_spi,
- auth_algo_vpp_id, auth_key,
- crypt_algo_vpp_id, crypt_key,
- self.vpp_ah_protocol,
- flags=flags)
+ params.tra_sa_in = VppIpsecSA(
+ self,
+ scapy_tra_sa_id,
+ scapy_tra_spi,
+ auth_algo_vpp_id,
+ auth_key,
+ crypt_algo_vpp_id,
+ crypt_key,
+ self.vpp_ah_protocol,
+ flags=flags,
+ )
+ params.tra_sa_out = VppIpsecSA(
+ self,
+ vpp_tra_sa_id,
+ vpp_tra_spi,
+ auth_algo_vpp_id,
+ auth_key,
+ crypt_algo_vpp_id,
+ crypt_key,
+ self.vpp_ah_protocol,
+ flags=flags,
+ )
objs.append(params.tra_sa_in)
objs.append(params.tra_sa_out)
- objs.append(VppIpsecSpdEntry(self, self.tra_spd, vpp_tra_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_AH))
- objs.append(VppIpsecSpdEntry(self, self.tra_spd, scapy_tra_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_AH,
- is_outbound=0))
- objs.append(VppIpsecSpdEntry(self, self.tra_spd, vpp_tra_sa_id,
- self.tra_if.local_addr[addr_type],
- self.tra_if.local_addr[addr_type],
- self.tra_if.remote_addr[addr_type],
- self.tra_if.remote_addr[addr_type],
- 0, priority=10,
- policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- is_outbound=0))
- objs.append(VppIpsecSpdEntry(self, self.tra_spd, scapy_tra_sa_id,
- self.tra_if.local_addr[addr_type],
- self.tra_if.local_addr[addr_type],
- self.tra_if.remote_addr[addr_type],
- self.tra_if.remote_addr[addr_type],
- 0, policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- priority=10))
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tra_spd,
+ vpp_tra_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_AH,
+ )
+ )
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tra_spd,
+ scapy_tra_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_AH,
+ is_outbound=0,
+ )
+ )
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tra_spd,
+ vpp_tra_sa_id,
+ self.tra_if.local_addr[addr_type],
+ self.tra_if.local_addr[addr_type],
+ self.tra_if.remote_addr[addr_type],
+ self.tra_if.remote_addr[addr_type],
+ 0,
+ priority=10,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ is_outbound=0,
+ )
+ )
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tra_spd,
+ scapy_tra_sa_id,
+ self.tra_if.local_addr[addr_type],
+ self.tra_if.local_addr[addr_type],
+ self.tra_if.remote_addr[addr_type],
+ self.tra_if.remote_addr[addr_type],
+ 0,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ priority=10,
+ )
+ )
for o in objs:
o.add_vpp_config()
@@ -288,6 +388,7 @@ class TemplateIpsecAh(ConfigIpsecAH):
--- --- ---
"""
+
@classmethod
def setUpClass(cls):
super(TemplateIpsecAh, cls).setUpClass()
@@ -306,26 +407,30 @@ class TemplateIpsecAh(ConfigIpsecAH):
class TestIpsecAh1(TemplateIpsecAh, IpsecTcpTests):
- """ Ipsec AH - TCP tests """
+ """Ipsec AH - TCP tests"""
+
pass
class TestIpsecAh2(TemplateIpsecAh, IpsecTra46Tests, IpsecTun46Tests):
- """ Ipsec AH w/ SHA1 """
+ """Ipsec AH w/ SHA1"""
+
pass
class TestIpsecAhTun(TemplateIpsecAh, IpsecTun46Tests):
- """ Ipsec AH - TUN encap tests """
+ """Ipsec AH - TUN encap tests"""
def setUp(self):
self.ipv4_params = IPsecIPv4Params()
self.ipv6_params = IPsecIPv6Params()
- c = (VppEnum.vl_api_tunnel_encap_decap_flags_t.
- TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP)
- c1 = c | (VppEnum.vl_api_tunnel_encap_decap_flags_t.
- TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN)
+ c = (
+ VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP
+ )
+ c1 = c | (
+ VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN
+ )
self.ipv4_params.tun_flags = c
self.ipv6_params.tun_flags = c1
@@ -334,19 +439,23 @@ class TestIpsecAhTun(TemplateIpsecAh, IpsecTun46Tests):
def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=54):
# set the DSCP + ECN - flags are set to copy only DSCP
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IP(src=src, dst=dst, tos=5) /
- UDP(sport=4444, dport=4444) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IP(src=src, dst=dst, tos=5)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=54):
# set the DSCP + ECN - flags are set to copy both
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IPv6(src=src, dst=dst, tc=5) /
- UDP(sport=4444, dport=4444) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IPv6(src=src, dst=dst, tc=5)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_encrypted(self, p, sa, rxs):
# just check that only the DSCP is copied
@@ -360,7 +469,7 @@ class TestIpsecAhTun(TemplateIpsecAh, IpsecTun46Tests):
class TestIpsecAhTun2(TemplateIpsecAh, IpsecTun46Tests):
- """ Ipsec AH - TUN encap tests """
+ """Ipsec AH - TUN encap tests"""
def setUp(self):
self.ipv4_params = IPsecIPv4Params()
@@ -373,24 +482,28 @@ class TestIpsecAhTun2(TemplateIpsecAh, IpsecTun46Tests):
def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=54):
# set the DSCP + ECN - flags are set to copy only DSCP
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IP(src=src, dst=dst, tos=0) /
- UDP(sport=4444, dport=4444) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IP(src=src, dst=dst, tos=0)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=54):
# set the DSCP + ECN - flags are set to copy both
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IPv6(src=src, dst=dst, tc=0) /
- UDP(sport=4444, dport=4444) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IPv6(src=src, dst=dst, tc=0)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_encrypted(self, p, sa, rxs):
# just check that only the DSCP is copied
for rx in rxs:
- self.assertEqual(rx[IP].tos, 0xc)
+ self.assertEqual(rx[IP].tos, 0xC)
def verify_encrypted6(self, p, sa, rxs):
# just check that the DSCP & ECN are copied
@@ -398,17 +511,14 @@ class TestIpsecAhTun2(TemplateIpsecAh, IpsecTun46Tests):
self.assertEqual(rx[IPv6].tc, 0x10)
-class TestIpsecAhHandoff(TemplateIpsecAh,
- IpsecTun6HandoffTests,
- IpsecTun4HandoffTests):
- """ Ipsec AH Handoff """
+class TestIpsecAhHandoff(TemplateIpsecAh, IpsecTun6HandoffTests, IpsecTun4HandoffTests):
+ """Ipsec AH Handoff"""
+
pass
-class TestIpsecAhAll(ConfigIpsecAH,
- IpsecTra4, IpsecTra6,
- IpsecTun4, IpsecTun6):
- """ Ipsec AH all Algos """
+class TestIpsecAhAll(ConfigIpsecAH, IpsecTra4, IpsecTra6, IpsecTun4, IpsecTun6):
+ """Ipsec AH all Algos"""
def setUp(self):
super(TestIpsecAhAll, self).setUp()
@@ -421,21 +531,26 @@ class TestIpsecAhAll(ConfigIpsecAH,
# foreach VPP crypto engine
engines = ["ia32", "ipsecmb", "openssl"]
- algos = [{'vpp': VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96,
- 'scapy': "HMAC-SHA1-96"},
- {'vpp': VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA_256_128,
- 'scapy': "SHA2-256-128"},
- {'vpp': VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA_384_192,
- 'scapy': "SHA2-384-192"},
- {'vpp': VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA_512_256,
- 'scapy': "SHA2-512-256"}]
-
- flags = [0, (VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_USE_ESN)]
+ algos = [
+ {
+ "vpp": VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96,
+ "scapy": "HMAC-SHA1-96",
+ },
+ {
+ "vpp": VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA_256_128,
+ "scapy": "SHA2-256-128",
+ },
+ {
+ "vpp": VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA_384_192,
+ "scapy": "SHA2-384-192",
+ },
+ {
+ "vpp": VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA_512_256,
+ "scapy": "SHA2-512-256",
+ },
+ ]
+
+ flags = [0, (VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ESN)]
#
# loop through the VPP engines
@@ -454,14 +569,14 @@ class TestIpsecAhAll(ConfigIpsecAH,
self.ipv4_params = IPsecIPv4Params()
self.ipv6_params = IPsecIPv6Params()
- self.params = {self.ipv4_params.addr_type:
- self.ipv4_params,
- self.ipv6_params.addr_type:
- self.ipv6_params}
+ self.params = {
+ self.ipv4_params.addr_type: self.ipv4_params,
+ self.ipv6_params.addr_type: self.ipv6_params,
+ }
for _, p in self.params.items():
- p.auth_algo_vpp_id = algo['vpp']
- p.auth_algo = algo['scapy']
+ p.auth_algo_vpp_id = algo["vpp"]
+ p.auth_algo = algo["scapy"]
p.flags = p.flags | flag
#
@@ -484,5 +599,5 @@ class TestIpsecAhAll(ConfigIpsecAH,
self.unconfig_network()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ipsec_api.py b/test/test_ipsec_api.py
index b5b4adac66b..9c62c87e16d 100644
--- a/test/test_ipsec_api.py
+++ b/test/test_ipsec_api.py
@@ -6,7 +6,7 @@ from vpp_papi import VppEnum
class IpsecApiTestCase(VppTestCase):
- """ IPSec API tests """
+ """IPSec API tests"""
@classmethod
def setUpClass(cls):
@@ -22,10 +22,8 @@ class IpsecApiTestCase(VppTestCase):
self.pg0.config_ip4()
self.pg0.admin_up()
- self.vpp_esp_protocol = (VppEnum.vl_api_ipsec_proto_t.
- IPSEC_API_PROTO_ESP)
- self.vpp_ah_protocol = (VppEnum.vl_api_ipsec_proto_t.
- IPSEC_API_PROTO_AH)
+ self.vpp_esp_protocol = VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_ESP
+ self.vpp_ah_protocol = VppEnum.vl_api_ipsec_proto_t.IPSEC_API_PROTO_AH
self.ipv4_params = IPsecIPv4Params()
def tearDown(self):
@@ -34,32 +32,34 @@ class IpsecApiTestCase(VppTestCase):
super(IpsecApiTestCase, self).tearDown()
def test_backend_dump(self):
- """ backend dump """
+ """backend dump"""
d = self.vapi.ipsec_backend_dump()
self.assert_equal(len(d), 2, "number of ipsec backends in dump")
- self.assert_equal(d[0].protocol, self.vpp_ah_protocol,
- "ipsec protocol in dump entry")
+ self.assert_equal(
+ d[0].protocol, self.vpp_ah_protocol, "ipsec protocol in dump entry"
+ )
self.assert_equal(d[0].index, 0, "index in dump entry")
self.assert_equal(d[0].active, 1, "active flag in dump entry")
- self.assert_equal(d[1].protocol, self.vpp_esp_protocol,
- "ipsec protocol in dump entry")
+ self.assert_equal(
+ d[1].protocol, self.vpp_esp_protocol, "ipsec protocol in dump entry"
+ )
self.assert_equal(d[1].index, 0, "index in dump entry")
self.assert_equal(d[1].active, 1, "active flag in dump entry")
def test_select_valid_backend(self):
- """ select valid backend """
+ """select valid backend"""
self.vapi.ipsec_select_backend(self.vpp_ah_protocol, 0)
self.vapi.ipsec_select_backend(self.vpp_esp_protocol, 0)
def test_select_invalid_backend(self):
- """ select invalid backend """
+ """select invalid backend"""
with self.vapi.assert_negative_api_retval():
self.vapi.ipsec_select_backend(self.vpp_ah_protocol, 200)
with self.vapi.assert_negative_api_retval():
self.vapi.ipsec_select_backend(self.vpp_esp_protocol, 200)
def test_select_backend_in_use(self):
- """ attempt to change backend while sad configured """
+ """attempt to change backend while sad configured"""
params = self.ipv4_params
addr_type = params.addr_type
is_ipv6 = params.is_ipv6
@@ -73,48 +73,48 @@ class IpsecApiTestCase(VppTestCase):
self.vapi.ipsec_sad_entry_add_del(
is_add=1,
entry={
- 'sad_id': scapy_tun_sa_id,
- 'spi': scapy_tun_spi,
- 'integrity_algorithm': auth_algo_vpp_id,
- 'integrity_key': {
- 'data': auth_key,
- 'length': len(auth_key),
+ "sad_id": scapy_tun_sa_id,
+ "spi": scapy_tun_spi,
+ "integrity_algorithm": auth_algo_vpp_id,
+ "integrity_key": {
+ "data": auth_key,
+ "length": len(auth_key),
},
- 'crypto_algorithm': crypt_algo_vpp_id,
- 'crypto_key': {
- 'data': crypt_key,
- 'length': len(crypt_key),
+ "crypto_algorithm": crypt_algo_vpp_id,
+ "crypto_key": {
+ "data": crypt_key,
+ "length": len(crypt_key),
},
- 'protocol': self.vpp_ah_protocol,
- 'tunnel_src': self.pg0.local_addr[addr_type],
- 'tunnel_dst': self.pg0.remote_addr[addr_type]
- })
+ "protocol": self.vpp_ah_protocol,
+ "tunnel_src": self.pg0.local_addr[addr_type],
+ "tunnel_dst": self.pg0.remote_addr[addr_type],
+ },
+ )
with self.vapi.assert_negative_api_retval():
- self.vapi.ipsec_select_backend(
- protocol=self.vpp_ah_protocol, index=0)
+ self.vapi.ipsec_select_backend(protocol=self.vpp_ah_protocol, index=0)
self.vapi.ipsec_sad_entry_add_del(
is_add=0,
entry={
- 'sad_id': scapy_tun_sa_id,
- 'spi': scapy_tun_spi,
- 'integrity_algorithm': auth_algo_vpp_id,
- 'integrity_key': {
- 'data': auth_key,
- 'length': len(auth_key),
+ "sad_id": scapy_tun_sa_id,
+ "spi": scapy_tun_spi,
+ "integrity_algorithm": auth_algo_vpp_id,
+ "integrity_key": {
+ "data": auth_key,
+ "length": len(auth_key),
},
- 'crypto_algorithm': crypt_algo_vpp_id,
- 'crypto_key': {
- 'data': crypt_key,
- 'length': len(crypt_key),
+ "crypto_algorithm": crypt_algo_vpp_id,
+ "crypto_key": {
+ "data": crypt_key,
+ "length": len(crypt_key),
},
- 'protocol': self.vpp_ah_protocol,
- 'tunnel_src': self.pg0.local_addr[addr_type],
- 'tunnel_dst': self.pg0.remote_addr[addr_type]
- })
- self.vapi.ipsec_select_backend(
- protocol=self.vpp_ah_protocol, index=0)
+ "protocol": self.vpp_ah_protocol,
+ "tunnel_src": self.pg0.local_addr[addr_type],
+ "tunnel_dst": self.pg0.remote_addr[addr_type],
+ },
+ )
+ self.vapi.ipsec_select_backend(protocol=self.vpp_ah_protocol, index=0)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ipsec_default.py b/test/test_ipsec_default.py
index 6ee6f7822a2..f9de210e6dc 100644
--- a/test/test_ipsec_default.py
+++ b/test/test_ipsec_default.py
@@ -33,7 +33,7 @@ packets are dropped as expected.
class IPSecInboundDefaultDrop(IPSecIPv4Fwd):
- """ IPSec: inbound packets drop by default with no matching rule """
+ """IPSec: inbound packets drop by default with no matching rule"""
def test_ipsec_inbound_default_drop(self):
# configure two interfaces and bind the same SPD to both
@@ -43,13 +43,26 @@ class IPSecInboundDefaultDrop(IPSecIPv4Fwd):
# catch-all inbound BYPASS policy, all interfaces
inbound_policy = self.spd_add_rem_policy(
- 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10,
- policy_type="bypass", all_ips=True)
+ 1,
+ None,
+ None,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ all_ips=True,
+ )
# outbound BYPASS policy allowing traffic from pg0->pg1
outbound_policy = self.spd_add_rem_policy(
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
# create a packet stream pg0->pg1 + add to pg0
packets0 = self.create_stream(self.pg0, self.pg1, pkt_count)
@@ -64,8 +77,7 @@ class IPSecInboundDefaultDrop(IPSecIPv4Fwd):
try:
self.logger.debug(ppp("SPD - Got packet:", packet))
except Exception:
- self.logger.error(
- ppp("Unexpected or invalid packet:", packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
self.logger.debug("SPD: Num packets: %s", len(cap1.res))
# verify captures on pg1
@@ -76,8 +88,16 @@ class IPSecInboundDefaultDrop(IPSecIPv4Fwd):
# remove inbound catch-all BYPASS rule, traffic should now be dropped
self.spd_add_rem_policy( # inbound, all interfaces
- 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10,
- policy_type="bypass", all_ips=True, remove=True)
+ 1,
+ None,
+ None,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ all_ips=True,
+ remove=True,
+ )
# create another packet stream pg0->pg1 + add to pg0
packets1 = self.create_stream(self.pg0, self.pg1, pkt_count)
@@ -85,8 +105,9 @@ class IPSecInboundDefaultDrop(IPSecIPv4Fwd):
self.pg_interfaces[1].enable_capture()
self.pg_start()
# confirm traffic has now been dropped
- self.pg1.assert_nothing_captured(remark="inbound pkts with no matching"
- "rules NOT dropped by default")
+ self.pg1.assert_nothing_captured(
+ remark="inbound pkts with no matching" "rules NOT dropped by default"
+ )
# both policies should not have matched any further packets
# since we've dropped at input stage
self.verify_policy_match(pkt_count, outbound_policy)
@@ -94,7 +115,7 @@ class IPSecInboundDefaultDrop(IPSecIPv4Fwd):
class IPSecOutboundDefaultDrop(IPSecIPv4Fwd):
- """ IPSec: outbound packets drop by default with no matching rule """
+ """IPSec: outbound packets drop by default with no matching rule"""
def test_ipsec_inbound_default_drop(self):
# configure two interfaces and bind the same SPD to both
@@ -104,13 +125,26 @@ class IPSecOutboundDefaultDrop(IPSecIPv4Fwd):
# catch-all inbound BYPASS policy, all interfaces
inbound_policy = self.spd_add_rem_policy(
- 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10,
- policy_type="bypass", all_ips=True)
+ 1,
+ None,
+ None,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ all_ips=True,
+ )
# outbound BYPASS policy allowing traffic from pg0->pg1
outbound_policy = self.spd_add_rem_policy(
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
# create a packet stream pg0->pg1 + add to pg0
packets0 = self.create_stream(self.pg0, self.pg1, pkt_count)
@@ -125,8 +159,7 @@ class IPSecOutboundDefaultDrop(IPSecIPv4Fwd):
try:
self.logger.debug(ppp("SPD - Got packet:", packet))
except Exception:
- self.logger.error(
- ppp("Unexpected or invalid packet:", packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
self.logger.debug("SPD: Num packets: %s", len(cap1.res))
# verify captures on pg1
@@ -137,9 +170,15 @@ class IPSecOutboundDefaultDrop(IPSecIPv4Fwd):
# remove outbound rule
self.spd_add_rem_policy(
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass",
- remove=True)
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ remove=True,
+ )
# create another packet stream pg0->pg1 + add to pg0
packets1 = self.create_stream(self.pg0, self.pg1, pkt_count)
@@ -148,13 +187,13 @@ class IPSecOutboundDefaultDrop(IPSecIPv4Fwd):
self.pg_start()
# confirm traffic was dropped and not forwarded
self.pg1.assert_nothing_captured(
- remark="outbound pkts with no matching rules NOT dropped "
- "by default")
+ remark="outbound pkts with no matching rules NOT dropped " "by default"
+ )
# inbound rule should have matched twice the # of pkts now
- self.verify_policy_match(pkt_count*2, inbound_policy)
+ self.verify_policy_match(pkt_count * 2, inbound_policy)
# as dropped at outbound, outbound policy is the same
self.verify_policy_match(pkt_count, outbound_policy)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ipsec_esp.py b/test/test_ipsec_esp.py
index 74d01cd5568..54b877112e9 100644
--- a/test/test_ipsec_esp.py
+++ b/test/test_ipsec_esp.py
@@ -8,14 +8,26 @@ from scapy.packet import Raw
from parameterized import parameterized
from framework import VppTestRunner
-from template_ipsec import IpsecTra46Tests, IpsecTun46Tests, TemplateIpsec, \
- IpsecTcpTests, IpsecTun4Tests, IpsecTra4Tests, config_tra_params, \
- config_tun_params, IPsecIPv4Params, IPsecIPv6Params, \
- IpsecTra4, IpsecTun4, IpsecTra6, IpsecTun6, \
- IpsecTun6HandoffTests, IpsecTun4HandoffTests, \
- IpsecTra6ExtTests
-from vpp_ipsec import VppIpsecSpd, VppIpsecSpdEntry, VppIpsecSA,\
- VppIpsecSpdItfBinding
+from template_ipsec import (
+ IpsecTra46Tests,
+ IpsecTun46Tests,
+ TemplateIpsec,
+ IpsecTcpTests,
+ IpsecTun4Tests,
+ IpsecTra4Tests,
+ config_tra_params,
+ config_tun_params,
+ IPsecIPv4Params,
+ IPsecIPv6Params,
+ IpsecTra4,
+ IpsecTun4,
+ IpsecTra6,
+ IpsecTun6,
+ IpsecTun6HandoffTests,
+ IpsecTun4HandoffTests,
+ IpsecTra6ExtTests,
+)
+from vpp_ipsec import VppIpsecSpd, VppIpsecSpdEntry, VppIpsecSA, VppIpsecSpdItfBinding
from vpp_ip_route import VppIpRoute, VppRoutePath
from vpp_ip import DpoProto
from vpp_papi import VppEnum
@@ -68,13 +80,11 @@ class ConfigIpsecESP(TemplateIpsec):
self.tun_spd.add_vpp_config()
self.net_objs.append(self.tun_spd)
- b = VppIpsecSpdItfBinding(self, self.tun_spd,
- self.tun_if)
+ b = VppIpsecSpdItfBinding(self, self.tun_spd, self.tun_if)
b.add_vpp_config()
self.net_objs.append(b)
- b = VppIpsecSpdItfBinding(self, self.tra_spd,
- self.tra_if)
+ b = VppIpsecSpdItfBinding(self, self.tra_spd, self.tra_if)
b.add_vpp_config()
self.net_objs.append(b)
@@ -87,10 +97,16 @@ class ConfigIpsecESP(TemplateIpsec):
for p in params:
d = DpoProto.DPO_PROTO_IP6 if p.is_ipv6 else DpoProto.DPO_PROTO_IP4
- r = VppIpRoute(self, p.remote_tun_if_host, p.addr_len,
- [VppRoutePath(self.tun_if.remote_addr[p.addr_type],
- 0xffffffff,
- proto=d)])
+ r = VppIpRoute(
+ self,
+ p.remote_tun_if_host,
+ p.addr_len,
+ [
+ VppRoutePath(
+ self.tun_if.remote_addr[p.addr_type], 0xFFFFFFFF, proto=d
+ )
+ ],
+ )
r.add_vpp_config()
self.net_objs.append(r)
@@ -120,75 +136,125 @@ class ConfigIpsecESP(TemplateIpsec):
salt = params.salt
objs = []
- params.tun_sa_in = VppIpsecSA(self, scapy_tun_sa_id, scapy_tun_spi,
- auth_algo_vpp_id, auth_key,
- crypt_algo_vpp_id, crypt_key,
- self.vpp_esp_protocol,
- self.tun_if.local_addr[addr_type],
- self.tun_if.remote_addr[addr_type],
- tun_flags=tun_flags,
- dscp=params.dscp,
- flags=flags,
- salt=salt,
- hop_limit=params.outer_hop_limit)
- params.tun_sa_out = VppIpsecSA(self, vpp_tun_sa_id, vpp_tun_spi,
- auth_algo_vpp_id, auth_key,
- crypt_algo_vpp_id, crypt_key,
- self.vpp_esp_protocol,
- self.tun_if.remote_addr[addr_type],
- self.tun_if.local_addr[addr_type],
- tun_flags=tun_flags,
- dscp=params.dscp,
- flags=flags,
- salt=salt,
- hop_limit=params.outer_hop_limit)
+ params.tun_sa_in = VppIpsecSA(
+ self,
+ scapy_tun_sa_id,
+ scapy_tun_spi,
+ auth_algo_vpp_id,
+ auth_key,
+ crypt_algo_vpp_id,
+ crypt_key,
+ self.vpp_esp_protocol,
+ self.tun_if.local_addr[addr_type],
+ self.tun_if.remote_addr[addr_type],
+ tun_flags=tun_flags,
+ dscp=params.dscp,
+ flags=flags,
+ salt=salt,
+ hop_limit=params.outer_hop_limit,
+ )
+ params.tun_sa_out = VppIpsecSA(
+ self,
+ vpp_tun_sa_id,
+ vpp_tun_spi,
+ auth_algo_vpp_id,
+ auth_key,
+ crypt_algo_vpp_id,
+ crypt_key,
+ self.vpp_esp_protocol,
+ self.tun_if.remote_addr[addr_type],
+ self.tun_if.local_addr[addr_type],
+ tun_flags=tun_flags,
+ dscp=params.dscp,
+ flags=flags,
+ salt=salt,
+ hop_limit=params.outer_hop_limit,
+ )
objs.append(params.tun_sa_in)
objs.append(params.tun_sa_out)
- params.spd_policy_in_any = VppIpsecSpdEntry(self, self.tun_spd,
- scapy_tun_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_ESP)
- params.spd_policy_out_any = VppIpsecSpdEntry(self, self.tun_spd,
- scapy_tun_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_ESP,
- is_outbound=0)
+ params.spd_policy_in_any = VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ scapy_tun_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_ESP,
+ )
+ params.spd_policy_out_any = VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ scapy_tun_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_ESP,
+ is_outbound=0,
+ )
objs.append(params.spd_policy_out_any)
objs.append(params.spd_policy_in_any)
- objs.append(VppIpsecSpdEntry(self, self.tun_spd, vpp_tun_sa_id,
- remote_tun_if_host, remote_tun_if_host,
- self.pg1.remote_addr[addr_type],
- self.pg1.remote_addr[addr_type],
- 0,
- priority=10,
- policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- is_outbound=0))
- objs.append(VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
- self.pg1.remote_addr[addr_type],
- self.pg1.remote_addr[addr_type],
- remote_tun_if_host, remote_tun_if_host,
- 0,
- policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- priority=10))
- objs.append(VppIpsecSpdEntry(self, self.tun_spd, vpp_tun_sa_id,
- remote_tun_if_host, remote_tun_if_host,
- self.pg0.local_addr[addr_type],
- self.pg0.local_addr[addr_type],
- 0,
- priority=20,
- policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- is_outbound=0))
- objs.append(VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
- self.pg0.local_addr[addr_type],
- self.pg0.local_addr[addr_type],
- remote_tun_if_host, remote_tun_if_host,
- 0,
- policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- priority=20))
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ vpp_tun_sa_id,
+ remote_tun_if_host,
+ remote_tun_if_host,
+ self.pg1.remote_addr[addr_type],
+ self.pg1.remote_addr[addr_type],
+ 0,
+ priority=10,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ is_outbound=0,
+ )
+ )
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ scapy_tun_sa_id,
+ self.pg1.remote_addr[addr_type],
+ self.pg1.remote_addr[addr_type],
+ remote_tun_if_host,
+ remote_tun_if_host,
+ 0,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ priority=10,
+ )
+ )
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ vpp_tun_sa_id,
+ remote_tun_if_host,
+ remote_tun_if_host,
+ self.pg0.local_addr[addr_type],
+ self.pg0.local_addr[addr_type],
+ 0,
+ priority=20,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ is_outbound=0,
+ )
+ )
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ scapy_tun_sa_id,
+ self.pg0.local_addr[addr_type],
+ self.pg0.local_addr[addr_type],
+ remote_tun_if_host,
+ remote_tun_if_host,
+ 0,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ priority=20,
+ )
+ )
for o in objs:
o.add_vpp_config()
self.net_objs = self.net_objs + objs
@@ -210,45 +276,87 @@ class ConfigIpsecESP(TemplateIpsec):
salt = params.salt
objs = []
- params.tra_sa_in = VppIpsecSA(self, scapy_tra_sa_id, scapy_tra_spi,
- auth_algo_vpp_id, auth_key,
- crypt_algo_vpp_id, crypt_key,
- self.vpp_esp_protocol,
- flags=flags,
- salt=salt)
- params.tra_sa_out = VppIpsecSA(self, vpp_tra_sa_id, vpp_tra_spi,
- auth_algo_vpp_id, auth_key,
- crypt_algo_vpp_id, crypt_key,
- self.vpp_esp_protocol,
- flags=flags,
- salt=salt)
+ params.tra_sa_in = VppIpsecSA(
+ self,
+ scapy_tra_sa_id,
+ scapy_tra_spi,
+ auth_algo_vpp_id,
+ auth_key,
+ crypt_algo_vpp_id,
+ crypt_key,
+ self.vpp_esp_protocol,
+ flags=flags,
+ salt=salt,
+ )
+ params.tra_sa_out = VppIpsecSA(
+ self,
+ vpp_tra_sa_id,
+ vpp_tra_spi,
+ auth_algo_vpp_id,
+ auth_key,
+ crypt_algo_vpp_id,
+ crypt_key,
+ self.vpp_esp_protocol,
+ flags=flags,
+ salt=salt,
+ )
objs.append(params.tra_sa_in)
objs.append(params.tra_sa_out)
- objs.append(VppIpsecSpdEntry(self, self.tra_spd, vpp_tra_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_ESP))
- objs.append(VppIpsecSpdEntry(self, self.tra_spd, vpp_tra_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_ESP,
- is_outbound=0))
- objs.append(VppIpsecSpdEntry(self, self.tra_spd, vpp_tra_sa_id,
- self.tra_if.local_addr[addr_type],
- self.tra_if.local_addr[addr_type],
- self.tra_if.remote_addr[addr_type],
- self.tra_if.remote_addr[addr_type],
- 0, priority=10,
- policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- is_outbound=0))
- objs.append(VppIpsecSpdEntry(self, self.tra_spd, scapy_tra_sa_id,
- self.tra_if.local_addr[addr_type],
- self.tra_if.local_addr[addr_type],
- self.tra_if.remote_addr[addr_type],
- self.tra_if.remote_addr[addr_type],
- 0, policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- priority=10))
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tra_spd,
+ vpp_tra_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_ESP,
+ )
+ )
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tra_spd,
+ vpp_tra_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_ESP,
+ is_outbound=0,
+ )
+ )
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tra_spd,
+ vpp_tra_sa_id,
+ self.tra_if.local_addr[addr_type],
+ self.tra_if.local_addr[addr_type],
+ self.tra_if.remote_addr[addr_type],
+ self.tra_if.remote_addr[addr_type],
+ 0,
+ priority=10,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ is_outbound=0,
+ )
+ )
+ objs.append(
+ VppIpsecSpdEntry(
+ self,
+ self.tra_spd,
+ scapy_tra_sa_id,
+ self.tra_if.local_addr[addr_type],
+ self.tra_if.local_addr[addr_type],
+ self.tra_if.remote_addr[addr_type],
+ self.tra_if.remote_addr[addr_type],
+ 0,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ priority=10,
+ )
+ )
for o in objs:
o.add_vpp_config()
self.net_objs = self.net_objs + objs
@@ -308,9 +416,10 @@ class TemplateIpsecEsp(ConfigIpsecESP):
super(TemplateIpsecEsp, self).tearDown()
-class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests,
- IpsecTun46Tests, IpsecTra6ExtTests):
- """ Ipsec ESP - TUN & TRA tests """
+class TestIpsecEsp1(
+ TemplateIpsecEsp, IpsecTra46Tests, IpsecTun46Tests, IpsecTra6ExtTests
+):
+ """Ipsec ESP - TUN & TRA tests"""
@classmethod
def setUpClass(cls):
@@ -327,7 +436,7 @@ class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests,
super(TestIpsecEsp1, self).tearDown()
def test_tun_46(self):
- """ ipsec 4o6 tunnel """
+ """ipsec 4o6 tunnel"""
# add an SPD entry to direct 2.2.2.2 to the v6 tunnel SA
p6 = self.ipv6_params
p4 = self.ipv4_params
@@ -335,20 +444,25 @@ class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests,
p6.remote_tun_if_host4 = "2.2.2.2"
e = VppEnum.vl_api_ipsec_spd_action_t
- VppIpsecSpdEntry(self,
- self.tun_spd,
- p6.scapy_tun_sa_id,
- self.pg1.remote_addr[p4.addr_type],
- self.pg1.remote_addr[p4.addr_type],
- p6.remote_tun_if_host4,
- p6.remote_tun_if_host4,
- 0,
- priority=10,
- policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- is_outbound=1).add_vpp_config()
- VppIpRoute(self, p6.remote_tun_if_host4, p4.addr_len,
- [VppRoutePath(self.tun_if.remote_addr[p4.addr_type],
- 0xffffffff)]).add_vpp_config()
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ p6.scapy_tun_sa_id,
+ self.pg1.remote_addr[p4.addr_type],
+ self.pg1.remote_addr[p4.addr_type],
+ p6.remote_tun_if_host4,
+ p6.remote_tun_if_host4,
+ 0,
+ priority=10,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ is_outbound=1,
+ ).add_vpp_config()
+ VppIpRoute(
+ self,
+ p6.remote_tun_if_host4,
+ p4.addr_len,
+ [VppRoutePath(self.tun_if.remote_addr[p4.addr_type], 0xFFFFFFFF)],
+ ).add_vpp_config()
old_name = self.tun6_encrypt_node_name
self.tun6_encrypt_node_name = "esp4-encrypt"
@@ -357,7 +471,7 @@ class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests,
self.tun6_encrypt_node_name = old_name
def test_tun_64(self):
- """ ipsec 6o4 tunnel """
+ """ipsec 6o4 tunnel"""
# add an SPD entry to direct 4444::4 to the v4 tunnel SA
p6 = self.ipv6_params
p4 = self.ipv4_params
@@ -365,22 +479,26 @@ class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests,
p4.remote_tun_if_host6 = "4444::4"
e = VppEnum.vl_api_ipsec_spd_action_t
- VppIpsecSpdEntry(self,
- self.tun_spd,
- p4.scapy_tun_sa_id,
- self.pg1.remote_addr[p6.addr_type],
- self.pg1.remote_addr[p6.addr_type],
- p4.remote_tun_if_host6,
- p4.remote_tun_if_host6,
- 0,
- priority=10,
- policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- is_outbound=1).add_vpp_config()
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ p4.scapy_tun_sa_id,
+ self.pg1.remote_addr[p6.addr_type],
+ self.pg1.remote_addr[p6.addr_type],
+ p4.remote_tun_if_host6,
+ p4.remote_tun_if_host6,
+ 0,
+ priority=10,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ is_outbound=1,
+ ).add_vpp_config()
d = DpoProto.DPO_PROTO_IP6
- VppIpRoute(self, p4.remote_tun_if_host6, p6.addr_len,
- [VppRoutePath(self.tun_if.remote_addr[p6.addr_type],
- 0xffffffff,
- proto=d)]).add_vpp_config()
+ VppIpRoute(
+ self,
+ p4.remote_tun_if_host6,
+ p6.addr_len,
+ [VppRoutePath(self.tun_if.remote_addr[p6.addr_type], 0xFFFFFFFF, proto=d)],
+ ).add_vpp_config()
old_name = self.tun4_encrypt_node_name
self.tun4_encrypt_node_name = "esp6-encrypt"
@@ -389,16 +507,18 @@ class TestIpsecEsp1(TemplateIpsecEsp, IpsecTra46Tests,
class TestIpsecEspTun(TemplateIpsecEsp, IpsecTun46Tests):
- """ Ipsec ESP - TUN encap tests """
+ """Ipsec ESP - TUN encap tests"""
def setUp(self):
self.ipv4_params = IPsecIPv4Params()
self.ipv6_params = IPsecIPv6Params()
- c = (VppEnum.vl_api_tunnel_encap_decap_flags_t.
- TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP)
- c1 = c | (VppEnum.vl_api_tunnel_encap_decap_flags_t.
- TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN)
+ c = (
+ VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_DSCP
+ )
+ c1 = c | (
+ VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_ECN
+ )
self.ipv4_params.tun_flags = c
self.ipv6_params.tun_flags = c1
@@ -407,19 +527,23 @@ class TestIpsecEspTun(TemplateIpsecEsp, IpsecTun46Tests):
def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=54):
# set the DSCP + ECN - flags are set to copy only DSCP
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IP(src=src, dst=dst, tos=5) /
- UDP(sport=4444, dport=4444) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IP(src=src, dst=dst, tos=5)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=54):
# set the DSCP + ECN - flags are set to copy both
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IPv6(src=src, dst=dst, tc=5) /
- UDP(sport=4444, dport=4444) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IPv6(src=src, dst=dst, tc=5)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_encrypted(self, p, sa, rxs):
# just check that only the DSCP is copied
@@ -433,7 +557,7 @@ class TestIpsecEspTun(TemplateIpsecEsp, IpsecTun46Tests):
class TestIpsecEspTun2(TemplateIpsecEsp, IpsecTun46Tests):
- """ Ipsec ESP - TUN DSCP tests """
+ """Ipsec ESP - TUN DSCP tests"""
def setUp(self):
self.ipv4_params = IPsecIPv4Params()
@@ -445,39 +569,44 @@ class TestIpsecEspTun2(TemplateIpsecEsp, IpsecTun46Tests):
super(TestIpsecEspTun2, self).setUp()
def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=54):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IP(src=src, dst=dst) /
- UDP(sport=4444, dport=4444) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IP(src=src, dst=dst)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=54):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IPv6(src=src, dst=dst) /
- UDP(sport=4444, dport=4444) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IPv6(src=src, dst=dst)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_encrypted(self, p, sa, rxs):
# just check that only the DSCP is set
for rx in rxs:
- self.assertEqual(rx[IP].tos,
- VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF << 2)
+ self.assertEqual(rx[IP].tos, VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF << 2)
def verify_encrypted6(self, p, sa, rxs):
# just check that the DSCP is set
for rx in rxs:
- self.assertEqual(rx[IPv6].tc,
- VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_AF11 << 2)
+ self.assertEqual(
+ rx[IPv6].tc, VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_AF11 << 2
+ )
class TestIpsecEsp2(TemplateIpsecEsp, IpsecTcpTests):
- """ Ipsec ESP - TCP tests """
+ """Ipsec ESP - TCP tests"""
+
pass
class TestIpsecEspAsync(TemplateIpsecEsp):
- """ Ipsec ESP - Aysnc tests """
+ """Ipsec ESP - Aysnc tests"""
vpp_worker_count = 2
@@ -486,15 +615,16 @@ class TestIpsecEspAsync(TemplateIpsecEsp):
self.p_sync = IPsecIPv4Params()
- self.p_sync.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CBC_256)
- self.p_sync.crypt_algo = 'AES-CBC' # scapy name
- self.p_sync.crypt_key = b'JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h'
+ self.p_sync.crypt_algo_vpp_id = (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_256
+ )
+ self.p_sync.crypt_algo = "AES-CBC" # scapy name
+ self.p_sync.crypt_key = b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h"
- self.p_sync.scapy_tun_sa_id += 0xf0000
- self.p_sync.scapy_tun_spi += 0xf0000
- self.p_sync.vpp_tun_sa_id += 0xf0000
- self.p_sync.vpp_tun_spi += 0xf0000
+ self.p_sync.scapy_tun_sa_id += 0xF0000
+ self.p_sync.scapy_tun_spi += 0xF0000
+ self.p_sync.vpp_tun_sa_id += 0xF0000
+ self.p_sync.vpp_tun_spi += 0xF0000
self.p_sync.remote_tun_if_host = "2.2.2.2"
e = VppEnum.vl_api_ipsec_spd_action_t
@@ -508,7 +638,8 @@ class TestIpsecEspAsync(TemplateIpsecEsp):
self.p_sync.crypt_key,
self.vpp_esp_protocol,
self.tun_if.local_addr[self.p_sync.addr_type],
- self.tun_if.remote_addr[self.p_sync.addr_type]).add_vpp_config()
+ self.tun_if.remote_addr[self.p_sync.addr_type],
+ ).add_vpp_config()
self.p_sync.spd = VppIpsecSpdEntry(
self,
self.tun_spd,
@@ -520,35 +651,40 @@ class TestIpsecEspAsync(TemplateIpsecEsp):
0,
priority=1,
policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- is_outbound=1).add_vpp_config()
- VppIpRoute(self,
- self.p_sync.remote_tun_if_host,
- self.p_sync.addr_len,
- [VppRoutePath(
- self.tun_if.remote_addr[self.p_sync.addr_type],
- 0xffffffff)]).add_vpp_config()
+ is_outbound=1,
+ ).add_vpp_config()
+ VppIpRoute(
+ self,
+ self.p_sync.remote_tun_if_host,
+ self.p_sync.addr_len,
+ [VppRoutePath(self.tun_if.remote_addr[self.p_sync.addr_type], 0xFFFFFFFF)],
+ ).add_vpp_config()
config_tun_params(self.p_sync, self.encryption_type, self.tun_if)
self.p_async = IPsecIPv4Params()
- self.p_async.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_GCM_256)
- self.p_async.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_NONE)
- self.p_async.crypt_algo = 'AES-GCM' # scapy name
- self.p_async.crypt_key = b'JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h'
- self.p_async.auth_algo = 'NULL'
-
- self.p_async.scapy_tun_sa_id += 0xe0000
- self.p_async.scapy_tun_spi += 0xe0000
- self.p_async.vpp_tun_sa_id += 0xe0000
- self.p_async.vpp_tun_spi += 0xe0000
+ self.p_async.crypt_algo_vpp_id = (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_256
+ )
+ self.p_async.auth_algo_vpp_id = (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE
+ )
+ self.p_async.crypt_algo = "AES-GCM" # scapy name
+ self.p_async.crypt_key = b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h"
+ self.p_async.auth_algo = "NULL"
+
+ self.p_async.scapy_tun_sa_id += 0xE0000
+ self.p_async.scapy_tun_spi += 0xE0000
+ self.p_async.vpp_tun_sa_id += 0xE0000
+ self.p_async.vpp_tun_spi += 0xE0000
self.p_async.remote_tun_if_host = "2.2.2.3"
iflags = VppEnum.vl_api_ipsec_sad_flags_t
- self.p_async.flags = (iflags.IPSEC_API_SAD_FLAG_USE_ESN |
- iflags.IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY |
- iflags.IPSEC_API_SAD_FLAG_ASYNC)
+ self.p_async.flags = (
+ iflags.IPSEC_API_SAD_FLAG_USE_ESN
+ | iflags.IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY
+ | iflags.IPSEC_API_SAD_FLAG_ASYNC
+ )
self.p_async.sa = VppIpsecSA(
self,
@@ -561,7 +697,8 @@ class TestIpsecEspAsync(TemplateIpsecEsp):
self.vpp_esp_protocol,
self.tun_if.local_addr[self.p_async.addr_type],
self.tun_if.remote_addr[self.p_async.addr_type],
- flags=self.p_async.flags).add_vpp_config()
+ flags=self.p_async.flags,
+ ).add_vpp_config()
self.p_async.spd = VppIpsecSpdEntry(
self,
self.tun_spd,
@@ -573,30 +710,35 @@ class TestIpsecEspAsync(TemplateIpsecEsp):
0,
priority=2,
policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- is_outbound=1).add_vpp_config()
- VppIpRoute(self,
- self.p_async.remote_tun_if_host,
- self.p_async.addr_len,
- [VppRoutePath(
- self.tun_if.remote_addr[self.p_async.addr_type],
- 0xffffffff)]).add_vpp_config()
+ is_outbound=1,
+ ).add_vpp_config()
+ VppIpRoute(
+ self,
+ self.p_async.remote_tun_if_host,
+ self.p_async.addr_len,
+ [VppRoutePath(self.tun_if.remote_addr[self.p_async.addr_type], 0xFFFFFFFF)],
+ ).add_vpp_config()
config_tun_params(self.p_async, self.encryption_type, self.tun_if)
def test_dual_stream(self):
- """ Alternating SAs """
+ """Alternating SAs"""
p = self.params[self.p_sync.addr_type]
self.vapi.ipsec_set_async_mode(async_enable=True)
- pkts = [(Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4,
- dst=self.p_sync.remote_tun_if_host) /
- UDP(sport=4444, dport=4444) /
- Raw(b'0x0' * 200)),
- (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4,
- dst=p.remote_tun_if_host) /
- UDP(sport=4444, dport=4444) /
- Raw(b'0x0' * 200))]
+ pkts = [
+ (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.p_sync.remote_tun_if_host)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"0x0" * 200)
+ ),
+ (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=p.remote_tun_if_host)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"0x0" * 200)
+ ),
+ ]
pkts *= 1023
rxs = self.send_and_expect(self.pg1, pkts, self.pg0)
@@ -619,15 +761,18 @@ class TestIpsecEspAsync(TemplateIpsecEsp):
self.vapi.ipsec_set_async_mode(async_enable=False)
def test_sync_async_noop_stream(self):
- """ Alternating SAs sync/async/noop """
+ """Alternating SAs sync/async/noop"""
p = self.params[self.p_sync.addr_type]
# first pin the default/noop SA to worker 0
- pkts = [(Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4,
- dst=p.remote_tun_if_host) /
- UDP(sport=4444, dport=4444) /
- Raw(b'0x0' * 200))]
+ pkts = [
+ (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=p.remote_tun_if_host)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"0x0" * 200)
+ )
+ ]
rxs = self.send_and_expect(self.pg1, pkts, self.pg0, worker=0)
self.logger.info(self.vapi.cli("sh ipsec sa"))
@@ -635,21 +780,26 @@ class TestIpsecEspAsync(TemplateIpsecEsp):
# then use all the other SAs on worker 1.
# some will handoff, other take the sync and async paths
- pkts = [(Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4,
- dst=self.p_sync.remote_tun_if_host) /
- UDP(sport=4444, dport=4444) /
- Raw(b'0x0' * 200)),
- (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4,
- dst=p.remote_tun_if_host) /
- UDP(sport=4444, dport=4444) /
- Raw(b'0x0' * 200)),
- (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4,
- dst=self.p_async.remote_tun_if_host) /
- UDP(sport=4444, dport=4444) /
- Raw(b'0x0' * 200))]
+ pkts = [
+ (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.p_sync.remote_tun_if_host)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"0x0" * 200)
+ ),
+ (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=p.remote_tun_if_host)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"0x0" * 200)
+ ),
+ (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.p_async.remote_tun_if_host)
+ / UDP(sport=4444, dport=4444)
+ / Raw(b"0x0" * 200)
+ ),
+ ]
pkts *= 1023
rxs = self.send_and_expect(self.pg1, pkts, self.pg0, worker=1)
@@ -678,10 +828,11 @@ class TestIpsecEspAsync(TemplateIpsecEsp):
self.assertTrue("DISABLED" in self.vapi.cli("sh crypto async status"))
-class TestIpsecEspHandoff(TemplateIpsecEsp,
- IpsecTun6HandoffTests,
- IpsecTun4HandoffTests):
- """ Ipsec ESP - handoff tests """
+class TestIpsecEspHandoff(
+ TemplateIpsecEsp, IpsecTun6HandoffTests, IpsecTun4HandoffTests
+):
+ """Ipsec ESP - handoff tests"""
+
pass
@@ -706,33 +857,33 @@ class TemplateIpsecEspUdp(ConfigIpsecESP):
self.logger.info(self.vapi.ppcli("show int addr"))
p = self.ipv4_params
- p.flags = (VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_UDP_ENCAP |
- VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY)
+ p.flags = (
+ VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_UDP_ENCAP
+ | VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ANTI_REPLAY
+ )
p.nat_header = UDP(sport=5454, dport=4500)
self.tra_spd = VppIpsecSpd(self, self.tra_spd_id)
self.tra_spd.add_vpp_config()
- VppIpsecSpdItfBinding(self, self.tra_spd,
- self.tra_if).add_vpp_config()
+ VppIpsecSpdItfBinding(self, self.tra_spd, self.tra_if).add_vpp_config()
self.config_esp_tra(p)
config_tra_params(p, self.encryption_type)
self.tun_spd = VppIpsecSpd(self, self.tun_spd_id)
self.tun_spd.add_vpp_config()
- VppIpsecSpdItfBinding(self, self.tun_spd,
- self.tun_if).add_vpp_config()
+ VppIpsecSpdItfBinding(self, self.tun_spd, self.tun_if).add_vpp_config()
self.config_esp_tun(p)
self.logger.info(self.vapi.ppcli("show ipsec all"))
d = DpoProto.DPO_PROTO_IP4
- VppIpRoute(self, p.remote_tun_if_host, p.addr_len,
- [VppRoutePath(self.tun_if.remote_addr[p.addr_type],
- 0xffffffff,
- proto=d)]).add_vpp_config()
+ VppIpRoute(
+ self,
+ p.remote_tun_if_host,
+ p.addr_len,
+ [VppRoutePath(self.tun_if.remote_addr[p.addr_type], 0xFFFFFFFF, proto=d)],
+ ).add_vpp_config()
def tearDown(self):
super(TemplateIpsecEspUdp, self).tearDown()
@@ -742,11 +893,12 @@ class TemplateIpsecEspUdp(ConfigIpsecESP):
class TestIpsecEspUdp(TemplateIpsecEspUdp, IpsecTra4Tests):
- """ Ipsec NAT-T ESP UDP tests """
+ """Ipsec NAT-T ESP UDP tests"""
+
pass
-class MyParameters():
+class MyParameters:
def __init__(self):
saf = VppEnum.vl_api_ipsec_sad_flags_t
flag_esn = saf.IPSEC_API_SAD_FLAG_USE_ESN
@@ -754,111 +906,143 @@ class MyParameters():
self.flags = [0, flag_esn, flag_ar]
# foreach crypto algorithm
self.algos = {
- 'AES-GCM-128/NONE': {
- 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_GCM_128),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_NONE),
- 'scapy-crypto': "AES-GCM",
- 'scapy-integ': "NULL",
- 'key': b"JPjyOWBeVEQiMe7h",
- 'salt': 0},
- 'AES-GCM-192/NONE': {
- 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_GCM_192),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_NONE),
- 'scapy-crypto': "AES-GCM",
- 'scapy-integ': "NULL",
- 'key': b"JPjyOWBeVEQiMe7h01234567",
- 'salt': 1010},
- 'AES-GCM-256/NONE': {
- 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_GCM_256),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_NONE),
- 'scapy-crypto': "AES-GCM",
- 'scapy-integ': "NULL",
- 'key': b"JPjyOWBeVEQiMe7h0123456787654321",
- 'salt': 2020},
- 'AES-CBC-128/MD5-96': {
- 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CBC_128),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_MD5_96),
- 'scapy-crypto': "AES-CBC",
- 'scapy-integ': "HMAC-MD5-96",
- 'salt': 0,
- 'key': b"JPjyOWBeVEQiMe7h"},
- 'AES-CBC-192/SHA1-96': {
- 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CBC_192),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96),
- 'scapy-crypto': "AES-CBC",
- 'scapy-integ': "HMAC-SHA1-96",
- 'salt': 0,
- 'key': b"JPjyOWBeVEQiMe7hJPjyOWBe"},
- 'AES-CBC-256/SHA1-96': {
- 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CBC_256),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96),
- 'scapy-crypto': "AES-CBC",
- 'scapy-integ': "HMAC-SHA1-96",
- 'salt': 0,
- 'key': b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h"},
- '3DES-CBC/SHA1-96': {
- 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_3DES_CBC),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96),
- 'scapy-crypto': "3DES",
- 'scapy-integ': "HMAC-SHA1-96",
- 'salt': 0,
- 'key': b"JPjyOWBeVEQiMe7h00112233"},
- 'NONE/SHA1-96': {
- 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_NONE),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96),
- 'scapy-crypto': "NULL",
- 'scapy-integ': "HMAC-SHA1-96",
- 'salt': 0,
- 'key': b"JPjyOWBeVEQiMe7h00112233"},
- 'AES-CTR-128/SHA1-96': {
- 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CTR_128),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96),
- 'scapy-crypto': "AES-CTR",
- 'scapy-integ': "HMAC-SHA1-96",
- 'salt': 0,
- 'key': b"JPjyOWBeVEQiMe7h"},
- 'AES-CTR-192/SHA1-96': {
- 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CTR_192),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96),
- 'scapy-crypto': "AES-CTR",
- 'scapy-integ': "HMAC-SHA1-96",
- 'salt': 1010,
- 'key': b"JPjyOWBeVEQiMe7hJPjyOWBe"},
- 'AES-CTR-256/SHA1-96': {
- 'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CTR_256),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96),
- 'scapy-crypto': "AES-CTR",
- 'scapy-integ': "HMAC-SHA1-96",
- 'salt': 2020,
- 'key': b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h"}}
-
-
-class RunTestIpsecEspAll(ConfigIpsecESP,
- IpsecTra4, IpsecTra6,
- IpsecTun4, IpsecTun6):
- """ Ipsec ESP all Algos """
+ "AES-GCM-128/NONE": {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_128
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE
+ ),
+ "scapy-crypto": "AES-GCM",
+ "scapy-integ": "NULL",
+ "key": b"JPjyOWBeVEQiMe7h",
+ "salt": 0,
+ },
+ "AES-GCM-192/NONE": {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_192
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE
+ ),
+ "scapy-crypto": "AES-GCM",
+ "scapy-integ": "NULL",
+ "key": b"JPjyOWBeVEQiMe7h01234567",
+ "salt": 1010,
+ },
+ "AES-GCM-256/NONE": {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_256
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE
+ ),
+ "scapy-crypto": "AES-GCM",
+ "scapy-integ": "NULL",
+ "key": b"JPjyOWBeVEQiMe7h0123456787654321",
+ "salt": 2020,
+ },
+ "AES-CBC-128/MD5-96": {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_MD5_96
+ ),
+ "scapy-crypto": "AES-CBC",
+ "scapy-integ": "HMAC-MD5-96",
+ "salt": 0,
+ "key": b"JPjyOWBeVEQiMe7h",
+ },
+ "AES-CBC-192/SHA1-96": {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_192
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96
+ ),
+ "scapy-crypto": "AES-CBC",
+ "scapy-integ": "HMAC-SHA1-96",
+ "salt": 0,
+ "key": b"JPjyOWBeVEQiMe7hJPjyOWBe",
+ },
+ "AES-CBC-256/SHA1-96": {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_256
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96
+ ),
+ "scapy-crypto": "AES-CBC",
+ "scapy-integ": "HMAC-SHA1-96",
+ "salt": 0,
+ "key": b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h",
+ },
+ "3DES-CBC/SHA1-96": {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_3DES_CBC
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96
+ ),
+ "scapy-crypto": "3DES",
+ "scapy-integ": "HMAC-SHA1-96",
+ "salt": 0,
+ "key": b"JPjyOWBeVEQiMe7h00112233",
+ },
+ "NONE/SHA1-96": {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_NONE
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96
+ ),
+ "scapy-crypto": "NULL",
+ "scapy-integ": "HMAC-SHA1-96",
+ "salt": 0,
+ "key": b"JPjyOWBeVEQiMe7h00112233",
+ },
+ "AES-CTR-128/SHA1-96": {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CTR_128
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96
+ ),
+ "scapy-crypto": "AES-CTR",
+ "scapy-integ": "HMAC-SHA1-96",
+ "salt": 0,
+ "key": b"JPjyOWBeVEQiMe7h",
+ },
+ "AES-CTR-192/SHA1-96": {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CTR_192
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96
+ ),
+ "scapy-crypto": "AES-CTR",
+ "scapy-integ": "HMAC-SHA1-96",
+ "salt": 1010,
+ "key": b"JPjyOWBeVEQiMe7hJPjyOWBe",
+ },
+ "AES-CTR-256/SHA1-96": {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CTR_256
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96
+ ),
+ "scapy-crypto": "AES-CTR",
+ "scapy-integ": "HMAC-SHA1-96",
+ "salt": 2020,
+ "key": b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h",
+ },
+ }
+
+
+class RunTestIpsecEspAll(ConfigIpsecESP, IpsecTra4, IpsecTra6, IpsecTun4, IpsecTun6):
+ """Ipsec ESP all Algos"""
@classmethod
def setUpConstants(cls):
@@ -875,9 +1059,9 @@ class RunTestIpsecEspAll(ConfigIpsecESP,
params = MyParameters()
self.engine = test_args[0]
self.flag = params.flags[0]
- if test_args[1] == 'ESNon':
+ if test_args[1] == "ESNon":
self.flag |= params.flags[1]
- if test_args[2] == 'ARon':
+ if test_args[2] == "ARon":
self.flag |= params.flags[2]
self.algo = params.algos[test_args[3]]
@@ -901,18 +1085,18 @@ class RunTestIpsecEspAll(ConfigIpsecESP,
self.ipv4_params = IPsecIPv4Params()
self.ipv6_params = IPsecIPv6Params()
- self.params = {self.ipv4_params.addr_type:
- self.ipv4_params,
- self.ipv6_params.addr_type:
- self.ipv6_params}
+ self.params = {
+ self.ipv4_params.addr_type: self.ipv4_params,
+ self.ipv6_params.addr_type: self.ipv6_params,
+ }
for _, p in self.params.items():
- p.auth_algo_vpp_id = algo['vpp-integ']
- p.crypt_algo_vpp_id = algo['vpp-crypto']
- p.crypt_algo = algo['scapy-crypto']
- p.auth_algo = algo['scapy-integ']
- p.crypt_key = algo['key']
- p.salt = algo['salt']
+ p.auth_algo_vpp_id = algo["vpp-integ"]
+ p.crypt_algo_vpp_id = algo["vpp-crypto"]
+ p.crypt_algo = algo["scapy-crypto"]
+ p.auth_algo = algo["scapy-integ"]
+ p.crypt_key = algo["key"]
+ p.salt = algo["salt"]
p.flags = flag
p.outer_flow_label = 243224
p.async_mode = self.async_mode
@@ -931,8 +1115,7 @@ class RunTestIpsecEspAll(ConfigIpsecESP,
#
self.verify_tra_basic6(count=NUM_PKTS)
self.verify_tra_basic4(count=NUM_PKTS)
- self.verify_tun_66(self.params[socket.AF_INET6],
- count=NUM_PKTS)
+ self.verify_tun_66(self.params[socket.AF_INET6], count=NUM_PKTS)
#
# Use an odd-byte payload size to check for correct padding.
#
@@ -940,26 +1123,29 @@ class RunTestIpsecEspAll(ConfigIpsecESP,
# to 56 for 8 byte alignment, and +13 to 64 for 64 byte alignment.
# This should catch bugs where the code is incorrectly over-padding
# for algorithms that don't require it
- psz = 49 - len(IP()/ICMP()) if payload_size is None else payload_size
- self.verify_tun_44(self.params[socket.AF_INET],
- count=NUM_PKTS, payload_size=psz)
+ psz = 49 - len(IP() / ICMP()) if payload_size is None else payload_size
+ self.verify_tun_44(
+ self.params[socket.AF_INET], count=NUM_PKTS, payload_size=psz
+ )
LARGE_PKT_SZ = [
1970, # results in 2 chained buffers entering decrypt node
- # but leaving as simple buffer due to ICV removal (tra4)
+ # but leaving as simple buffer due to ICV removal (tra4)
2004, # footer+ICV will be added to 2nd buffer (tun4)
4010, # ICV ends up splitted across 2 buffers in esp_decrypt
- # for transport4; transport6 takes normal path
+ # for transport4; transport6 takes normal path
4020, # same as above but tra4 and tra6 are switched
]
if self.engine in engines_supporting_chain_bufs:
for sz in LARGE_PKT_SZ:
self.verify_tra_basic4(count=NUM_PKTS, payload_size=sz)
self.verify_tra_basic6(count=NUM_PKTS, payload_size=sz)
- self.verify_tun_66(self.params[socket.AF_INET6],
- count=NUM_PKTS, payload_size=sz)
- self.verify_tun_44(self.params[socket.AF_INET],
- count=NUM_PKTS, payload_size=sz)
+ self.verify_tun_66(
+ self.params[socket.AF_INET6], count=NUM_PKTS, payload_size=sz
+ )
+ self.verify_tun_44(
+ self.params[socket.AF_INET], count=NUM_PKTS, payload_size=sz
+ )
#
# reconfigure the network and SA to run the
@@ -990,6 +1176,7 @@ class RunTestIpsecEspAll(ConfigIpsecESP,
self.unconfig_network()
+
#
# To generate test classes, do:
# grep '# GEN' test_ipsec_esp.py | sed -e 's/# GEN //g' | bash
@@ -1026,6 +1213,7 @@ class RunTestIpsecEspAll(ConfigIpsecESP,
class Test_native_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""native ESNon ARon AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARon AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1033,6 +1221,7 @@ class Test_native_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_native_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""native ESNon ARon AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARon AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1040,6 +1229,7 @@ class Test_native_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_native_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""native ESNon ARon AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARon AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1047,6 +1237,7 @@ class Test_native_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_native_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""native ESNon ARon AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARon AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1054,6 +1245,7 @@ class Test_native_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARon AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARon AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1061,6 +1253,7 @@ class Test_native_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARon AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARon AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1068,6 +1261,7 @@ class Test_native_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARon 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARon 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1075,6 +1269,7 @@ class Test_native_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARon NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARon NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1082,6 +1277,7 @@ class Test_native_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARon AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARon AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1089,6 +1285,7 @@ class Test_native_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARon AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARon AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1096,6 +1293,7 @@ class Test_native_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARon AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARon AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1103,6 +1301,7 @@ class Test_native_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""native ESNon ARoff AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARoff AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1110,6 +1309,7 @@ class Test_native_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_native_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""native ESNon ARoff AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARoff AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1117,6 +1317,7 @@ class Test_native_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_native_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""native ESNon ARoff AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARoff AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1124,6 +1325,7 @@ class Test_native_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_native_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""native ESNon ARoff AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARoff AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1131,6 +1333,7 @@ class Test_native_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARoff AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARoff AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1138,6 +1341,7 @@ class Test_native_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARoff AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARoff AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1145,6 +1349,7 @@ class Test_native_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARoff 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARoff 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1152,6 +1357,7 @@ class Test_native_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARoff NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARoff NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1159,6 +1365,7 @@ class Test_native_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARoff AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARoff AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1166,6 +1373,7 @@ class Test_native_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARoff AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARoff AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1173,6 +1381,7 @@ class Test_native_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""native ESNon ARoff AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNon ARoff AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1180,6 +1389,7 @@ class Test_native_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""native ESNoff ARon AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARon AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1187,6 +1397,7 @@ class Test_native_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_native_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""native ESNoff ARon AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARon AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1194,6 +1405,7 @@ class Test_native_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_native_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""native ESNoff ARon AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARon AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1201,6 +1413,7 @@ class Test_native_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_native_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""native ESNoff ARon AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARon AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1208,6 +1421,7 @@ class Test_native_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARon AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARon AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1215,6 +1429,7 @@ class Test_native_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARon AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARon AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1222,6 +1437,7 @@ class Test_native_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARon 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARon 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1229,6 +1445,7 @@ class Test_native_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARon NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARon NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1236,6 +1453,7 @@ class Test_native_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARon AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARon AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1243,6 +1461,7 @@ class Test_native_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARon AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARon AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1250,6 +1469,7 @@ class Test_native_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARon AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARon AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1257,6 +1477,7 @@ class Test_native_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""native ESNoff ARoff AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARoff AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1264,6 +1485,7 @@ class Test_native_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_native_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""native ESNoff ARoff AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARoff AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1271,6 +1493,7 @@ class Test_native_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_native_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""native ESNoff ARoff AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARoff AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1278,6 +1501,7 @@ class Test_native_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_native_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""native ESNoff ARoff AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARoff AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1285,6 +1509,7 @@ class Test_native_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1292,6 +1517,7 @@ class Test_native_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1299,6 +1525,7 @@ class Test_native_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1306,6 +1533,7 @@ class Test_native_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARoff NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARoff NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1313,6 +1541,7 @@ class Test_native_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1320,6 +1549,7 @@ class Test_native_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1327,6 +1557,7 @@ class Test_native_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_native_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""native ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""native ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1334,6 +1565,7 @@ class Test_native_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNon ARon AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARon AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1341,6 +1573,7 @@ class Test_ipsecmb_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNon ARon AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARon AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1348,6 +1581,7 @@ class Test_ipsecmb_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNon ARon AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARon AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1355,6 +1589,7 @@ class Test_ipsecmb_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARon AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARon AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1362,6 +1597,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARon AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARon AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1369,6 +1605,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARon AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARon AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1376,6 +1613,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARon 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARon 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1383,6 +1621,7 @@ class Test_ipsecmb_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARon NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARon NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1390,6 +1629,7 @@ class Test_ipsecmb_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARon AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARon AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1397,6 +1637,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARon AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARon AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1404,6 +1645,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARon AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARon AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1411,6 +1653,7 @@ class Test_ipsecmb_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNon ARoff AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARoff AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1418,6 +1661,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNon ARoff AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARoff AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1425,6 +1669,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNon ARoff AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARoff AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1432,6 +1677,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARoff AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARoff AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1439,6 +1685,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARoff AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARoff AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1446,6 +1693,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARoff AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARoff AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1453,6 +1701,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARoff 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARoff 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1460,6 +1709,7 @@ class Test_ipsecmb_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARoff NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARoff NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1467,6 +1717,7 @@ class Test_ipsecmb_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARoff AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARoff AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1474,6 +1725,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARoff AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARoff AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1481,6 +1733,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNon ARoff AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNon ARoff AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1488,6 +1741,7 @@ class Test_ipsecmb_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARon AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARon AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1495,6 +1749,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARon AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARon AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1502,6 +1757,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARon AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARon AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1509,6 +1765,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARon AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARon AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1516,6 +1773,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARon AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARon AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1523,6 +1781,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARon AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARon AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1530,6 +1789,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARon 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARon 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1537,6 +1797,7 @@ class Test_ipsecmb_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARon NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARon NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1544,6 +1805,7 @@ class Test_ipsecmb_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARon AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARon AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1551,6 +1813,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARon AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARon AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1558,6 +1821,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARon AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARon AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1565,6 +1829,7 @@ class Test_ipsecmb_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARoff AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARoff AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1572,6 +1837,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARoff AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARoff AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1579,6 +1845,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARoff AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARoff AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1586,6 +1853,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARoff AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARoff AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1593,6 +1861,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1600,6 +1869,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1607,6 +1877,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1614,6 +1885,7 @@ class Test_ipsecmb_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARoff NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARoff NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1621,6 +1893,7 @@ class Test_ipsecmb_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1628,6 +1901,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1635,6 +1909,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_ipsecmb_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""ipsecmb ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""ipsecmb ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1642,6 +1917,7 @@ class Test_ipsecmb_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""openssl ESNon ARon AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARon AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1649,6 +1925,7 @@ class Test_openssl_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""openssl ESNon ARon AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARon AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1656,6 +1933,7 @@ class Test_openssl_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""openssl ESNon ARon AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARon AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1663,6 +1941,7 @@ class Test_openssl_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""openssl ESNon ARon AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARon AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1670,6 +1949,7 @@ class Test_openssl_ESNon_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARon AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARon AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1677,6 +1957,7 @@ class Test_openssl_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARon AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARon AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1684,6 +1965,7 @@ class Test_openssl_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARon 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARon 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1691,6 +1973,7 @@ class Test_openssl_ESNon_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARon NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARon NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1698,6 +1981,7 @@ class Test_openssl_ESNon_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARon AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARon AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1705,6 +1989,7 @@ class Test_openssl_ESNon_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARon AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARon AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1712,6 +1997,7 @@ class Test_openssl_ESNon_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARon AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARon AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1719,6 +2005,7 @@ class Test_openssl_ESNon_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""openssl ESNon ARoff AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARoff AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1726,6 +2013,7 @@ class Test_openssl_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""openssl ESNon ARoff AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARoff AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1733,6 +2021,7 @@ class Test_openssl_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""openssl ESNon ARoff AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARoff AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1740,6 +2029,7 @@ class Test_openssl_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""openssl ESNon ARoff AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARoff AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1747,6 +2037,7 @@ class Test_openssl_ESNon_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARoff AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARoff AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1754,6 +2045,7 @@ class Test_openssl_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARoff AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARoff AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1761,6 +2053,7 @@ class Test_openssl_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARoff 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARoff 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1768,6 +2061,7 @@ class Test_openssl_ESNon_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARoff NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARoff NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1775,6 +2069,7 @@ class Test_openssl_ESNon_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARoff AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARoff AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1782,6 +2077,7 @@ class Test_openssl_ESNon_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARoff AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARoff AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1789,6 +2085,7 @@ class Test_openssl_ESNon_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNon ARoff AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNon ARoff AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1796,6 +2093,7 @@ class Test_openssl_ESNon_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""openssl ESNoff ARon AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARon AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1803,6 +2101,7 @@ class Test_openssl_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""openssl ESNoff ARon AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARon AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1810,6 +2109,7 @@ class Test_openssl_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""openssl ESNoff ARon AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARon AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1817,6 +2117,7 @@ class Test_openssl_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""openssl ESNoff ARon AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARon AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1824,6 +2125,7 @@ class Test_openssl_ESNoff_ARon_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARon AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARon AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1831,6 +2133,7 @@ class Test_openssl_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARon AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARon AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1838,6 +2141,7 @@ class Test_openssl_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARon 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARon 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1845,6 +2149,7 @@ class Test_openssl_ESNoff_ARon_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARon NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARon NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1852,6 +2157,7 @@ class Test_openssl_ESNoff_ARon_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARon AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARon AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1859,6 +2165,7 @@ class Test_openssl_ESNoff_ARon_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARon AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARon AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1866,6 +2173,7 @@ class Test_openssl_ESNoff_ARon_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARon AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARon AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1873,6 +2181,7 @@ class Test_openssl_ESNoff_ARon_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""openssl ESNoff ARoff AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARoff AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1880,6 +2189,7 @@ class Test_openssl_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""openssl ESNoff ARoff AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARoff AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1887,6 +2197,7 @@ class Test_openssl_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""openssl ESNoff ARoff AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARoff AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1894,6 +2205,7 @@ class Test_openssl_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
"""openssl ESNoff ARoff AES-CBC-128/MD5-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARoff AES-CBC-128/MD5-96 IPSec test"""
self.run_test()
@@ -1901,6 +2213,7 @@ class Test_openssl_ESNoff_ARoff_AES_CBC_128_MD5_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1908,6 +2221,7 @@ class Test_openssl_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1915,6 +2229,7 @@ class Test_openssl_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARoff 3DES-CBC/SHA1-96 IPSec test"""
self.run_test()
@@ -1922,6 +2237,7 @@ class Test_openssl_ESNoff_ARoff_3DES_CBC_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARoff NONE/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARoff NONE/SHA1-96 IPSec test"""
self.run_test()
@@ -1929,6 +2245,7 @@ class Test_openssl_ESNoff_ARoff_NONE_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARoff AES-CTR-128/SHA1-96 IPSec test"""
self.run_test()
@@ -1936,6 +2253,7 @@ class Test_openssl_ESNoff_ARoff_AES_CTR_128_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARoff AES-CTR-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1943,6 +2261,7 @@ class Test_openssl_ESNoff_ARoff_AES_CTR_192_SHA1_96(RunTestIpsecEspAll):
class Test_openssl_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
"""openssl ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""openssl ESNoff ARoff AES-CTR-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1950,6 +2269,7 @@ class Test_openssl_ESNoff_ARoff_AES_CTR_256_SHA1_96(RunTestIpsecEspAll):
class Test_async_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""async ESNon ARon AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNon ARon AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1957,6 +2277,7 @@ class Test_async_ESNon_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_async_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""async ESNon ARon AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNon ARon AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1964,6 +2285,7 @@ class Test_async_ESNon_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_async_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""async ESNon ARon AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNon ARon AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -1971,6 +2293,7 @@ class Test_async_ESNon_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_async_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""async ESNon ARon AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""async ESNon ARon AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -1978,6 +2301,7 @@ class Test_async_ESNon_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_async_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""async ESNon ARon AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""async ESNon ARon AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -1985,6 +2309,7 @@ class Test_async_ESNon_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_async_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""async ESNon ARoff AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNon ARoff AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -1992,6 +2317,7 @@ class Test_async_ESNon_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_async_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""async ESNon ARoff AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNon ARoff AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -1999,6 +2325,7 @@ class Test_async_ESNon_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_async_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""async ESNon ARoff AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNon ARoff AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -2006,6 +2333,7 @@ class Test_async_ESNon_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_async_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""async ESNon ARoff AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""async ESNon ARoff AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -2013,6 +2341,7 @@ class Test_async_ESNon_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_async_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""async ESNon ARoff AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""async ESNon ARoff AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -2020,6 +2349,7 @@ class Test_async_ESNon_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_async_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""async ESNoff ARon AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNoff ARon AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -2027,6 +2357,7 @@ class Test_async_ESNoff_ARon_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_async_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""async ESNoff ARon AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNoff ARon AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -2034,6 +2365,7 @@ class Test_async_ESNoff_ARon_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_async_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""async ESNoff ARon AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNoff ARon AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -2041,6 +2373,7 @@ class Test_async_ESNoff_ARon_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_async_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""async ESNoff ARon AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""async ESNoff ARon AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -2048,6 +2381,7 @@ class Test_async_ESNoff_ARon_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_async_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""async ESNoff ARon AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""async ESNoff ARon AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
@@ -2055,6 +2389,7 @@ class Test_async_ESNoff_ARon_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
class Test_async_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
"""async ESNoff ARoff AES-GCM-128/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNoff ARoff AES-GCM-128/NONE IPSec test"""
self.run_test()
@@ -2062,6 +2397,7 @@ class Test_async_ESNoff_ARoff_AES_GCM_128_NONE(RunTestIpsecEspAll):
class Test_async_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
"""async ESNoff ARoff AES-GCM-192/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNoff ARoff AES-GCM-192/NONE IPSec test"""
self.run_test()
@@ -2069,6 +2405,7 @@ class Test_async_ESNoff_ARoff_AES_GCM_192_NONE(RunTestIpsecEspAll):
class Test_async_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
"""async ESNoff ARoff AES-GCM-256/NONE IPSec test"""
+
def test_ipsec(self):
"""async ESNoff ARoff AES-GCM-256/NONE IPSec test"""
self.run_test()
@@ -2076,6 +2413,7 @@ class Test_async_ESNoff_ARoff_AES_GCM_256_NONE(RunTestIpsecEspAll):
class Test_async_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
"""async ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""async ESNoff ARoff AES-CBC-192/SHA1-96 IPSec test"""
self.run_test()
@@ -2083,6 +2421,7 @@ class Test_async_ESNoff_ARoff_AES_CBC_192_SHA1_96(RunTestIpsecEspAll):
class Test_async_ESNoff_ARoff_AES_CBC_256_SHA1_96(RunTestIpsecEspAll):
"""async ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test"""
+
def test_ipsec(self):
"""async ESNoff ARoff AES-CBC-256/SHA1-96 IPSec test"""
self.run_test()
diff --git a/test/test_ipsec_nat.py b/test/test_ipsec_nat.py
index b7ccb2befdc..64a2725dda6 100644
--- a/test/test_ipsec_nat.py
+++ b/test/test_ipsec_nat.py
@@ -9,15 +9,14 @@ from scapy.layers.ipsec import SecurityAssociation, ESP
from util import ppp, ppc
from template_ipsec import TemplateIpsec
-from vpp_ipsec import VppIpsecSA, VppIpsecSpd, VppIpsecSpdEntry,\
- VppIpsecSpdItfBinding
+from vpp_ipsec import VppIpsecSA, VppIpsecSpd, VppIpsecSpdEntry, VppIpsecSpdItfBinding
from vpp_ip_route import VppIpRoute, VppRoutePath
from vpp_ip import DpoProto
from vpp_papi import VppEnum
class IPSecNATTestCase(TemplateIpsec):
- """ IPSec/NAT
+ """IPSec/NAT
TUNNEL MODE::
@@ -53,18 +52,19 @@ class IPSecNATTestCase(TemplateIpsec):
self.tun_spd = VppIpsecSpd(self, self.tun_spd_id)
self.tun_spd.add_vpp_config()
- VppIpsecSpdItfBinding(self, self.tun_spd,
- self.tun_if).add_vpp_config()
+ VppIpsecSpdItfBinding(self, self.tun_spd, self.tun_if).add_vpp_config()
p = self.ipv4_params
self.config_esp_tun(p)
self.logger.info(self.vapi.ppcli("show ipsec all"))
d = DpoProto.DPO_PROTO_IP6 if p.is_ipv6 else DpoProto.DPO_PROTO_IP4
- VppIpRoute(self, p.remote_tun_if_host, p.addr_len,
- [VppRoutePath(self.tun_if.remote_addr[p.addr_type],
- 0xffffffff,
- proto=d)]).add_vpp_config()
+ VppIpRoute(
+ self,
+ p.remote_tun_if_host,
+ p.addr_len,
+ [VppRoutePath(self.tun_if.remote_addr[p.addr_type], 0xFFFFFFFF, proto=d)],
+ ).add_vpp_config()
def tearDown(self):
super(IPSecNATTestCase, self).tearDown()
@@ -72,65 +72,84 @@ class IPSecNATTestCase(TemplateIpsec):
def create_stream_plain(self, src_mac, dst_mac, src_ip, dst_ip):
return [
# TCP
- Ether(src=src_mac, dst=dst_mac) /
- IP(src=src_ip, dst=dst_ip) /
- TCP(sport=self.tcp_port_in, dport=20),
+ Ether(src=src_mac, dst=dst_mac)
+ / IP(src=src_ip, dst=dst_ip)
+ / TCP(sport=self.tcp_port_in, dport=20),
# UDP
- Ether(src=src_mac, dst=dst_mac) /
- IP(src=src_ip, dst=dst_ip) /
- UDP(sport=self.udp_port_in, dport=20),
+ Ether(src=src_mac, dst=dst_mac)
+ / IP(src=src_ip, dst=dst_ip)
+ / UDP(sport=self.udp_port_in, dport=20),
# ICMP
- Ether(src=src_mac, dst=dst_mac) /
- IP(src=src_ip, dst=dst_ip) /
- ICMP(id=self.icmp_id_in, type='echo-request')
+ Ether(src=src_mac, dst=dst_mac)
+ / IP(src=src_ip, dst=dst_ip)
+ / ICMP(id=self.icmp_id_in, type="echo-request"),
]
def create_stream_encrypted(self, src_mac, dst_mac, src_ip, dst_ip, sa):
return [
# TCP
- Ether(src=src_mac, dst=dst_mac) /
- sa.encrypt(IP(src=src_ip, dst=dst_ip) /
- TCP(dport=self.tcp_port_out, sport=20)),
+ Ether(src=src_mac, dst=dst_mac)
+ / sa.encrypt(
+ IP(src=src_ip, dst=dst_ip) / TCP(dport=self.tcp_port_out, sport=20)
+ ),
# UDP
- Ether(src=src_mac, dst=dst_mac) /
- sa.encrypt(IP(src=src_ip, dst=dst_ip) /
- UDP(dport=self.udp_port_out, sport=20)),
+ Ether(src=src_mac, dst=dst_mac)
+ / sa.encrypt(
+ IP(src=src_ip, dst=dst_ip) / UDP(dport=self.udp_port_out, sport=20)
+ ),
# ICMP
- Ether(src=src_mac, dst=dst_mac) /
- sa.encrypt(IP(src=src_ip, dst=dst_ip) /
- ICMP(id=self.icmp_id_out, type='echo-request'))
+ Ether(src=src_mac, dst=dst_mac)
+ / sa.encrypt(
+ IP(src=src_ip, dst=dst_ip)
+ / ICMP(id=self.icmp_id_out, type="echo-request")
+ ),
]
def verify_capture_plain(self, capture):
for packet in capture:
try:
self.assert_packet_checksums_valid(packet)
- self.assert_equal(packet[IP].src, self.tun_if.remote_ip4,
- "decrypted packet source address")
- self.assert_equal(packet[IP].dst, self.pg1.remote_ip4,
- "decrypted packet destination address")
+ self.assert_equal(
+ packet[IP].src,
+ self.tun_if.remote_ip4,
+ "decrypted packet source address",
+ )
+ self.assert_equal(
+ packet[IP].dst,
+ self.pg1.remote_ip4,
+ "decrypted packet destination address",
+ )
if packet.haslayer(TCP):
self.assertFalse(
packet.haslayer(UDP),
- "unexpected UDP header in decrypted packet")
- self.assert_equal(packet[TCP].dport, self.tcp_port_in,
- "decrypted packet TCP destination port")
+ "unexpected UDP header in decrypted packet",
+ )
+ self.assert_equal(
+ packet[TCP].dport,
+ self.tcp_port_in,
+ "decrypted packet TCP destination port",
+ )
elif packet.haslayer(UDP):
if packet[UDP].payload:
self.assertFalse(
packet[UDP][1].haslayer(UDP),
- "unexpected UDP header in decrypted packet")
- self.assert_equal(packet[UDP].dport, self.udp_port_in,
- "decrypted packet UDP destination port")
+ "unexpected UDP header in decrypted packet",
+ )
+ self.assert_equal(
+ packet[UDP].dport,
+ self.udp_port_in,
+ "decrypted packet UDP destination port",
+ )
else:
self.assertFalse(
packet.haslayer(UDP),
- "unexpected UDP header in decrypted packet")
- self.assert_equal(packet[ICMP].id, self.icmp_id_in,
- "decrypted packet ICMP ID")
+ "unexpected UDP header in decrypted packet",
+ )
+ self.assert_equal(
+ packet[ICMP].id, self.icmp_id_in, "decrypted packet ICMP ID"
+ )
except Exception:
- self.logger.error(
- ppp("Unexpected or invalid plain packet:", packet))
+ self.logger.error(ppp("Unexpected or invalid plain packet:", packet))
raise
def verify_capture_encrypted(self, capture, sa):
@@ -139,19 +158,25 @@ class IPSecNATTestCase(TemplateIpsec):
copy = packet.__class__(scapy.compat.raw(packet))
del copy[UDP].len
copy = packet.__class__(scapy.compat.raw(copy))
- self.assert_equal(packet[UDP].len, copy[UDP].len,
- "UDP header length")
+ self.assert_equal(packet[UDP].len, copy[UDP].len, "UDP header length")
self.assert_packet_checksums_valid(packet)
self.assertIn(ESP, packet[IP])
decrypt_pkt = sa.decrypt(packet[IP])
self.assert_packet_checksums_valid(decrypt_pkt)
- self.assert_equal(decrypt_pkt[IP].src, self.pg1.remote_ip4,
- "encrypted packet source address")
- self.assert_equal(decrypt_pkt[IP].dst, self.tun_if.remote_ip4,
- "encrypted packet destination address")
+ self.assert_equal(
+ decrypt_pkt[IP].src,
+ self.pg1.remote_ip4,
+ "encrypted packet source address",
+ )
+ self.assert_equal(
+ decrypt_pkt[IP].dst,
+ self.tun_if.remote_ip4,
+ "encrypted packet destination address",
+ )
except Exception:
self.logger.error(
- ppp("Unexpected or invalid encrypted packet:", packet))
+ ppp("Unexpected or invalid encrypted packet:", packet)
+ )
raise
def config_esp_tun(self, params):
@@ -166,104 +191,153 @@ class IPSecNATTestCase(TemplateIpsec):
crypt_key = params.crypt_key
addr_any = params.addr_any
addr_bcast = params.addr_bcast
- flags = (VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_UDP_ENCAP)
+ flags = VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_UDP_ENCAP
e = VppEnum.vl_api_ipsec_spd_action_t
- VppIpsecSA(self, scapy_tun_sa_id, scapy_tun_spi,
- auth_algo_vpp_id, auth_key,
- crypt_algo_vpp_id, crypt_key,
- self.vpp_esp_protocol,
- self.pg1.remote_addr[addr_type],
- self.tun_if.remote_addr[addr_type],
- flags=flags).add_vpp_config()
- VppIpsecSA(self, vpp_tun_sa_id, vpp_tun_spi,
- auth_algo_vpp_id, auth_key,
- crypt_algo_vpp_id, crypt_key,
- self.vpp_esp_protocol,
- self.tun_if.remote_addr[addr_type],
- self.pg1.remote_addr[addr_type],
- flags=flags).add_vpp_config()
+ VppIpsecSA(
+ self,
+ scapy_tun_sa_id,
+ scapy_tun_spi,
+ auth_algo_vpp_id,
+ auth_key,
+ crypt_algo_vpp_id,
+ crypt_key,
+ self.vpp_esp_protocol,
+ self.pg1.remote_addr[addr_type],
+ self.tun_if.remote_addr[addr_type],
+ flags=flags,
+ ).add_vpp_config()
+ VppIpsecSA(
+ self,
+ vpp_tun_sa_id,
+ vpp_tun_spi,
+ auth_algo_vpp_id,
+ auth_key,
+ crypt_algo_vpp_id,
+ crypt_key,
+ self.vpp_esp_protocol,
+ self.tun_if.remote_addr[addr_type],
+ self.pg1.remote_addr[addr_type],
+ flags=flags,
+ ).add_vpp_config()
- VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_ESP).add_vpp_config()
- VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_ESP,
- is_outbound=0).add_vpp_config()
- VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_UDP,
- remote_port_start=4500,
- remote_port_stop=4500).add_vpp_config()
- VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
- addr_any, addr_bcast,
- addr_any, addr_bcast,
- socket.IPPROTO_UDP,
- remote_port_start=4500,
- remote_port_stop=4500,
- is_outbound=0).add_vpp_config()
- VppIpsecSpdEntry(self, self.tun_spd, vpp_tun_sa_id,
- self.tun_if.remote_addr[addr_type],
- self.tun_if.remote_addr[addr_type],
- self.pg1.remote_addr[addr_type],
- self.pg1.remote_addr[addr_type],
- 0, priority=10,
- policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- is_outbound=0).add_vpp_config()
- VppIpsecSpdEntry(self, self.tun_spd, scapy_tun_sa_id,
- self.pg1.remote_addr[addr_type],
- self.pg1.remote_addr[addr_type],
- self.tun_if.remote_addr[addr_type],
- self.tun_if.remote_addr[addr_type],
- 0, policy=e.IPSEC_API_SPD_ACTION_PROTECT,
- priority=10).add_vpp_config()
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ scapy_tun_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_ESP,
+ ).add_vpp_config()
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ scapy_tun_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_ESP,
+ is_outbound=0,
+ ).add_vpp_config()
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ scapy_tun_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_UDP,
+ remote_port_start=4500,
+ remote_port_stop=4500,
+ ).add_vpp_config()
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ scapy_tun_sa_id,
+ addr_any,
+ addr_bcast,
+ addr_any,
+ addr_bcast,
+ socket.IPPROTO_UDP,
+ remote_port_start=4500,
+ remote_port_stop=4500,
+ is_outbound=0,
+ ).add_vpp_config()
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ vpp_tun_sa_id,
+ self.tun_if.remote_addr[addr_type],
+ self.tun_if.remote_addr[addr_type],
+ self.pg1.remote_addr[addr_type],
+ self.pg1.remote_addr[addr_type],
+ 0,
+ priority=10,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ is_outbound=0,
+ ).add_vpp_config()
+ VppIpsecSpdEntry(
+ self,
+ self.tun_spd,
+ scapy_tun_sa_id,
+ self.pg1.remote_addr[addr_type],
+ self.pg1.remote_addr[addr_type],
+ self.tun_if.remote_addr[addr_type],
+ self.tun_if.remote_addr[addr_type],
+ 0,
+ policy=e.IPSEC_API_SPD_ACTION_PROTECT,
+ priority=10,
+ ).add_vpp_config()
def test_ipsec_nat_tun(self):
- """ IPSec/NAT tunnel test case """
+ """IPSec/NAT tunnel test case"""
p = self.ipv4_params
- scapy_tun_sa = SecurityAssociation(ESP, spi=p.scapy_tun_spi,
- crypt_algo=p.crypt_algo,
- crypt_key=p.crypt_key,
- auth_algo=p.auth_algo,
- auth_key=p.auth_key,
- tunnel_header=IP(
- src=self.pg1.remote_ip4,
- dst=self.tun_if.remote_ip4),
- nat_t_header=UDP(
- sport=4500,
- dport=4500))
+ scapy_tun_sa = SecurityAssociation(
+ ESP,
+ spi=p.scapy_tun_spi,
+ crypt_algo=p.crypt_algo,
+ crypt_key=p.crypt_key,
+ auth_algo=p.auth_algo,
+ auth_key=p.auth_key,
+ tunnel_header=IP(src=self.pg1.remote_ip4, dst=self.tun_if.remote_ip4),
+ nat_t_header=UDP(sport=4500, dport=4500),
+ )
# in2out - from private network to public
pkts = self.create_stream_plain(
- self.pg1.remote_mac, self.pg1.local_mac,
- self.pg1.remote_ip4, self.tun_if.remote_ip4)
+ self.pg1.remote_mac,
+ self.pg1.local_mac,
+ self.pg1.remote_ip4,
+ self.tun_if.remote_ip4,
+ )
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.tun_if.get_capture(len(pkts))
self.verify_capture_encrypted(capture, scapy_tun_sa)
- vpp_tun_sa = SecurityAssociation(ESP,
- spi=p.vpp_tun_spi,
- crypt_algo=p.crypt_algo,
- crypt_key=p.crypt_key,
- auth_algo=p.auth_algo,
- auth_key=p.auth_key,
- tunnel_header=IP(
- src=self.tun_if.remote_ip4,
- dst=self.pg1.remote_ip4),
- nat_t_header=UDP(
- sport=4500,
- dport=4500))
+ vpp_tun_sa = SecurityAssociation(
+ ESP,
+ spi=p.vpp_tun_spi,
+ crypt_algo=p.crypt_algo,
+ crypt_key=p.crypt_key,
+ auth_algo=p.auth_algo,
+ auth_key=p.auth_key,
+ tunnel_header=IP(src=self.tun_if.remote_ip4, dst=self.pg1.remote_ip4),
+ nat_t_header=UDP(sport=4500, dport=4500),
+ )
# out2in - from public network to private
pkts = self.create_stream_encrypted(
- self.tun_if.remote_mac, self.tun_if.local_mac,
- self.tun_if.remote_ip4, self.pg1.remote_ip4, vpp_tun_sa)
+ self.tun_if.remote_mac,
+ self.tun_if.local_mac,
+ self.tun_if.remote_ip4,
+ self.pg1.remote_ip4,
+ vpp_tun_sa,
+ )
self.logger.info(ppc("Sending packets:", pkts))
self.tun_if.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
diff --git a/test/test_ipsec_spd_flow_cache_input.py b/test/test_ipsec_spd_flow_cache_input.py
index 2d70d1540b8..02ecb5625ce 100644
--- a/test/test_ipsec_spd_flow_cache_input.py
+++ b/test/test_ipsec_spd_flow_cache_input.py
@@ -12,16 +12,14 @@ class SpdFlowCacheInbound(SpdFlowCacheTemplate):
@classmethod
def setUpConstants(cls):
super(SpdFlowCacheInbound, cls).setUpConstants()
- cls.vpp_cmdline.extend(["ipsec", "{",
- "ipv4-inbound-spd-flow-cache on",
- "}"])
- cls.logger.info("VPP modified cmdline is %s" % " "
- .join(cls.vpp_cmdline))
+ cls.vpp_cmdline.extend(["ipsec", "{", "ipv4-inbound-spd-flow-cache on", "}"])
+ cls.logger.info("VPP modified cmdline is %s" % " ".join(cls.vpp_cmdline))
class IPSec4SpdTestCaseBypass(SpdFlowCacheInbound):
""" IPSec/IPv4 inbound: Policy mode test case with flow cache \
(add bypass)"""
+
def test_ipsec_spd_inbound_bypass(self):
# In this test case, packets in IPv4 FWD path are configured
# to go through IPSec inbound SPD policy lookup.
@@ -42,16 +40,34 @@ class IPSec4SpdTestCaseBypass(SpdFlowCacheInbound):
# bypass rule should take precedence over discard rule,
# even though it's lower priority
policy_0 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
policy_1 = self.spd_add_rem_policy( # inbound, priority 15
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=15, policy_type="discard")
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=15,
+ policy_type="discard",
+ )
# create output rule so we can capture forwarded packets
policy_2 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
# check flow cache is empty before sending traffic
self.verify_num_inbound_flow_cache_entries(0)
@@ -85,6 +101,7 @@ class IPSec4SpdTestCaseBypass(SpdFlowCacheInbound):
class IPSec4SpdTestCaseDiscard(SpdFlowCacheInbound):
""" IPSec/IPv4 inbound: Policy mode test case with flow cache \
(add discard)"""
+
def test_ipsec_spd_inbound_discard(self):
# In this test case, packets in IPv4 FWD path are configured
# to go through IPSec inbound SPD policy lookup.
@@ -96,13 +113,25 @@ class IPSec4SpdTestCaseDiscard(SpdFlowCacheInbound):
# create input rule
policy_0 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="discard")
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="discard",
+ )
# create output rule so we can capture forwarded packets
policy_1 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
# check flow cache is empty before sending traffic
self.verify_num_inbound_flow_cache_entries(0)
@@ -124,6 +153,7 @@ class IPSec4SpdTestCaseDiscard(SpdFlowCacheInbound):
class IPSec4SpdTestCaseRemove(SpdFlowCacheInbound):
""" IPSec/IPv4 inbound: Policy mode test case with flow cache \
(remove bypass)"""
+
def test_ipsec_spd_inbound_remove(self):
# In this test case, packets in IPv4 FWD path are configured
# to go through IPSec inbound SPD policy lookup.
@@ -147,16 +177,34 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheInbound):
# bypass rule should take precedence over discard rule,
# even though it's lower priority
policy_0 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
policy_1 = self.spd_add_rem_policy( # inbound, priority 15
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=15, policy_type="discard")
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=15,
+ policy_type="discard",
+ )
# create output rule so we can capture forwarded packets
policy_2 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
# check flow cache is empty before sending traffic
self.verify_num_inbound_flow_cache_entries(0)
@@ -188,9 +236,15 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheInbound):
# remove the input bypass rule
self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass",
- remove=True)
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ remove=True,
+ )
# verify flow cache counter has been reset by rule removal
self.verify_num_inbound_flow_cache_entries(0)
@@ -213,6 +267,7 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheInbound):
class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound):
""" IPSec/IPv4 inbound: Policy mode test case with flow cache \
(add, remove, re-add bypass)"""
+
def test_ipsec_spd_inbound_readd(self):
# In this test case, packets in IPv4 FWD path are configured
# to go through IPSec inbound SPD policy lookup.
@@ -239,16 +294,34 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound):
# bypass rule should take precedence over discard rule,
# even though it's lower priority
policy_0 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
policy_1 = self.spd_add_rem_policy( # inbound, priority 15
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=15, policy_type="discard")
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=15,
+ policy_type="discard",
+ )
# create output rule so we can capture forwarded packets
policy_2 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
# check flow cache is empty before sending traffic
self.verify_num_inbound_flow_cache_entries(0)
@@ -280,9 +353,15 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound):
# remove the input bypass rule
self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass",
- remove=True)
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ remove=True,
+ )
# verify flow cache counter has been reset by rule removal
self.verify_num_inbound_flow_cache_entries(0)
@@ -303,8 +382,14 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound):
# readd the input bypass rule
policy_0 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
# verify flow cache counter has been reset by rule addition
self.verify_num_inbound_flow_cache_entries(0)
@@ -327,7 +412,7 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound):
# verify all policies matched the expected number of times
self.verify_policy_match(pkt_count, policy_0)
self.verify_policy_match(pkt_count, policy_1)
- self.verify_policy_match(pkt_count*2, policy_2)
+ self.verify_policy_match(pkt_count * 2, policy_2)
# by readding the bypass rule, we reset the flow cache
# we only expect the bypass rule to now be in the flow cache
self.verify_num_inbound_flow_cache_entries(1)
@@ -336,6 +421,7 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheInbound):
class IPSec4SpdTestCaseMultiple(SpdFlowCacheInbound):
""" IPSec/IPv4 inbound: Policy mode test case with flow cache \
(multiple interfaces, multiple rules)"""
+
def test_ipsec_spd_inbound_multiple(self):
# In this test case, packets in IPv4 FWD path are configured to go
# through IPSec outbound SPD policy lookup.
@@ -353,23 +439,47 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheInbound):
# add input rules on all interfaces
# pg0 -> pg1
policy_0 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
# pg1 -> pg2
policy_1 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg2, self.pg1, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg2,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
# pg2 -> pg0
policy_2 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg0, self.pg2, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="discard")
+ 1,
+ self.pg0,
+ self.pg2,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="discard",
+ )
# create output rules covering the the full ip range
# 0.0.0.0 -> 255.255.255.255, so we can capture forwarded packets
policy_3 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg0, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass",
- all_ips=True)
+ 1,
+ self.pg0,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ all_ips=True,
+ )
# check flow cache is empty (0 active elements) before sending traffic
self.verify_num_inbound_flow_cache_entries(0)
@@ -396,8 +506,7 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheInbound):
try:
self.logger.debug(ppp("SPD Add - Got packet:", packet))
except Exception:
- self.logger.error(
- ppp("Unexpected or invalid packet:", packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
# verify captures that matched BYPASS rules
@@ -416,6 +525,7 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheInbound):
class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound):
""" IPSec/IPv4 inbound: Policy mode test case with flow cache \
(overwrite stale entries)"""
+
def test_ipsec_spd_inbound_overwrite(self):
# The operation of the flow cache is setup so that the entire cache
# is invalidated when adding or removing an SPD policy rule.
@@ -436,23 +546,47 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound):
# add input rules on all interfaces
# pg0 -> pg1
policy_0 = self.spd_add_rem_policy( # inbound
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
# pg1 -> pg2
policy_1 = self.spd_add_rem_policy( # inbound
- 1, self.pg2, self.pg1, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg2,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
# pg2 -> pg0
policy_2 = self.spd_add_rem_policy( # inbound
- 1, self.pg0, self.pg2, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="discard")
+ 1,
+ self.pg0,
+ self.pg2,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="discard",
+ )
# create output rules covering the the full ip range
# 0.0.0.0 -> 255.255.255.255, so we can capture forwarded packets
policy_3 = self.spd_add_rem_policy( # outbound
- 1, self.pg0, self.pg0, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass",
- all_ips=True)
+ 1,
+ self.pg0,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ all_ips=True,
+ )
# check flow cache is empty (0 active elements) before sending traffic
self.verify_num_inbound_flow_cache_entries(0)
@@ -479,8 +613,7 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound):
try:
self.logger.debug(ppp("SPD Add - Got packet:", packet))
except Exception:
- self.logger.error(
- ppp("Unexpected or invalid packet:", packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
# verify captures that matched BYPASS rules
@@ -497,22 +630,40 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound):
# adding an outbound policy should not invalidate output flow cache
self.spd_add_rem_policy( # outbound
- 1, self.pg0, self.pg0, socket.IPPROTO_UDP,
- is_out=1, priority=1, policy_type="bypass",
- all_ips=True)
+ 1,
+ self.pg0,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=1,
+ policy_type="bypass",
+ all_ips=True,
+ )
# check inbound flow cache counter has not been reset
self.verify_num_inbound_flow_cache_entries(3)
# remove + readd bypass policy - flow cache counter will be reset,
# and there will be 3x stale entries in flow cache
self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass",
- remove=True)
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ remove=True,
+ )
# readd policy
policy_0 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
# check counter was reset
self.verify_num_inbound_flow_cache_entries(0)
@@ -532,8 +683,7 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound):
try:
self.logger.debug(ppp("SPD Add - Got packet:", packet))
except Exception:
- self.logger.error(
- ppp("Unexpected or invalid packet:", packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
# verify captures that matched BYPASS rules
@@ -543,8 +693,8 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound):
self.pg0.assert_nothing_captured()
# verify all policies matched the expected number of times
self.verify_policy_match(pkt_count, policy_0)
- self.verify_policy_match(pkt_count*2, policy_1)
- self.verify_policy_match(pkt_count*2, policy_2)
+ self.verify_policy_match(pkt_count * 2, policy_1)
+ self.verify_policy_match(pkt_count * 2, policy_2)
# we are overwriting 3x stale entries - check flow cache counter
# is correct
self.verify_num_inbound_flow_cache_entries(3)
@@ -553,18 +703,23 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheInbound):
class IPSec4SpdTestCaseCollision(SpdFlowCacheInbound):
""" IPSec/IPv4 inbound: Policy mode test case with flow cache \
(hash collision)"""
+
# Override class setup to restrict hash table size to 16 buckets.
# This forces using only the lower 4 bits of the hash as a key,
# making hash collisions easy to find.
@classmethod
def setUpConstants(cls):
super(SpdFlowCacheInbound, cls).setUpConstants()
- cls.vpp_cmdline.extend(["ipsec", "{",
- "ipv4-inbound-spd-flow-cache on",
- "ipv4-inbound-spd-hash-buckets 16",
- "}"])
- cls.logger.info("VPP modified cmdline is %s" % " "
- .join(cls.vpp_cmdline))
+ cls.vpp_cmdline.extend(
+ [
+ "ipsec",
+ "{",
+ "ipv4-inbound-spd-flow-cache on",
+ "ipv4-inbound-spd-hash-buckets 16",
+ "}",
+ ]
+ )
+ cls.logger.info("VPP modified cmdline is %s" % " ".join(cls.vpp_cmdline))
def test_ipsec_spd_inbound_collision(self):
# The flow cache operation is setup to overwrite an entry
@@ -588,20 +743,38 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheInbound):
# create output rules covering the the full ip range
# 0.0.0.0 -> 255.255.255.255, so we can capture forwarded packets
policy_0 = self.spd_add_rem_policy( # outbound
- 1, self.pg0, self.pg0, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass",
- all_ips=True)
+ 1,
+ self.pg0,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ all_ips=True,
+ )
capture_intfs = []
if self.crc32_supported(): # create crc32 collision on last 4 bits
hashed_with_crc32 = True
# add matching rules
policy_1 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg2, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg2,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
policy_2 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg3, self.pg0, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg3,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
# we expect to get captures on pg1 + pg3
capture_intfs.append(self.pg1)
@@ -623,11 +796,23 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheInbound):
hashed_with_crc32 = False
# add matching rules
policy_1 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg1, self.pg2, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg2,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
policy_2 = self.spd_add_rem_policy( # inbound, priority 10
- 1, self.pg2, self.pg3, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg2,
+ self.pg3,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
capture_intfs.append(self.pg1)
capture_intfs.append(self.pg2)
@@ -655,15 +840,13 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheInbound):
if_caps.append(pg.get_capture())
for packet in if_caps[-1]:
try:
- self.logger.debug(ppp(
- "SPD Add - Got packet:", packet))
+ self.logger.debug(ppp("SPD Add - Got packet:", packet))
except Exception:
- self.logger.error(ppp(
- "Unexpected or invalid packet:", packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
# verify captures that matched BYPASS rule
- if(hashed_with_crc32):
+ if hashed_with_crc32:
self.verify_capture(self.pg2, self.pg1, if_caps[0])
self.verify_capture(self.pg0, self.pg3, if_caps[1])
else: # hashed with xxhash
@@ -673,11 +856,11 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheInbound):
# verify all policies matched the expected number of times
self.verify_policy_match(pkt_count, policy_1)
self.verify_policy_match(pkt_count, policy_2)
- self.verify_policy_match(pkt_count*2, policy_0) # output policy
+ self.verify_policy_match(pkt_count * 2, policy_0) # output policy
# we have matched 2 policies, but due to the hash collision
# one active entry is expected
self.verify_num_inbound_flow_cache_entries(1)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ipsec_spd_flow_cache_output.py b/test/test_ipsec_spd_flow_cache_output.py
index 54571c6741a..9852b375a82 100644
--- a/test/test_ipsec_spd_flow_cache_output.py
+++ b/test/test_ipsec_spd_flow_cache_output.py
@@ -11,16 +11,14 @@ class SpdFlowCacheOutbound(SpdFlowCacheTemplate):
@classmethod
def setUpConstants(cls):
super(SpdFlowCacheOutbound, cls).setUpConstants()
- cls.vpp_cmdline.extend(["ipsec", "{",
- "ipv4-outbound-spd-flow-cache on",
- "}"])
- cls.logger.info("VPP modified cmdline is %s" % " "
- .join(cls.vpp_cmdline))
+ cls.vpp_cmdline.extend(["ipsec", "{", "ipv4-outbound-spd-flow-cache on", "}"])
+ cls.logger.info("VPP modified cmdline is %s" % " ".join(cls.vpp_cmdline))
class IPSec4SpdTestCaseAdd(SpdFlowCacheOutbound):
""" IPSec/IPv4 outbound: Policy mode test case with flow cache \
(add rule)"""
+
def test_ipsec_spd_outbound_add(self):
# In this test case, packets in IPv4 FWD path are configured
# to go through IPSec outbound SPD policy lookup.
@@ -33,11 +31,23 @@ class IPSec4SpdTestCaseAdd(SpdFlowCacheOutbound):
pkt_count = 5
self.spd_create_and_intf_add(1, [self.pg1])
policy_0 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
policy_1 = self.spd_add_rem_policy( # outbound, priority 5
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=5, policy_type="discard")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=5,
+ policy_type="discard",
+ )
# check flow cache is empty before sending traffic
self.verify_num_outbound_flow_cache_entries(0)
@@ -75,6 +85,7 @@ class IPSec4SpdTestCaseAdd(SpdFlowCacheOutbound):
class IPSec4SpdTestCaseRemove(SpdFlowCacheOutbound):
""" IPSec/IPv4 outbound: Policy mode test case with flow cache \
(remove rule)"""
+
def test_ipsec_spd_outbound_remove(self):
# In this test case, packets in IPv4 FWD path are configured
# to go through IPSec outbound SPD policy lookup.
@@ -88,11 +99,23 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheOutbound):
pkt_count = 5
self.spd_create_and_intf_add(1, [self.pg1])
policy_0 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
policy_1 = self.spd_add_rem_policy( # outbound, priority 5
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=5, policy_type="discard")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=5,
+ policy_type="discard",
+ )
# check flow cache is empty before sending traffic
self.verify_num_outbound_flow_cache_entries(0)
@@ -128,9 +151,15 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheOutbound):
# now remove the bypass rule
self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass",
- remove=True)
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ remove=True,
+ )
# verify flow cache counter has been reset by rule removal
self.verify_num_outbound_flow_cache_entries(0)
@@ -154,6 +183,7 @@ class IPSec4SpdTestCaseRemove(SpdFlowCacheOutbound):
class IPSec4SpdTestCaseReadd(SpdFlowCacheOutbound):
""" IPSec/IPv4 outbound: Policy mode test case with flow cache \
(add, remove, re-add)"""
+
def test_ipsec_spd_outbound_readd(self):
# In this test case, packets in IPv4 FWD path are configured
# to go through IPSec outbound SPD policy lookup.
@@ -172,11 +202,23 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheOutbound):
pkt_count = 5
self.spd_create_and_intf_add(1, [self.pg1])
policy_0 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
policy_1 = self.spd_add_rem_policy( # outbound, priority 5
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=5, policy_type="discard")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=5,
+ policy_type="discard",
+ )
# check flow cache is empty before sending traffic
self.verify_num_outbound_flow_cache_entries(0)
@@ -212,9 +254,15 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheOutbound):
# now remove the bypass rule, leaving only the discard rule
self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass",
- remove=True)
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ remove=True,
+ )
# verify flow cache counter has been reset by rule removal
self.verify_num_outbound_flow_cache_entries(0)
@@ -236,8 +284,14 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheOutbound):
# now readd the bypass rule
policy_0 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
# verify flow cache counter has been reset by rule addition
self.verify_num_outbound_flow_cache_entries(0)
@@ -271,6 +325,7 @@ class IPSec4SpdTestCaseReadd(SpdFlowCacheOutbound):
class IPSec4SpdTestCaseMultiple(SpdFlowCacheOutbound):
""" IPSec/IPv4 outbound: Policy mode test case with flow cache \
(multiple interfaces, multiple rules)"""
+
def test_ipsec_spd_outbound_multiple(self):
# In this test case, packets in IPv4 FWD path are configured to go
# through IPSec outbound SPD policy lookup.
@@ -286,32 +341,75 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheOutbound):
self.spd_create_and_intf_add(1, self.pg_interfaces)
# add rules on all interfaces
policy_01 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
policy_02 = self.spd_add_rem_policy( # outbound, priority 5
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=5, policy_type="discard")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=5,
+ policy_type="discard",
+ )
policy_11 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg1, self.pg2, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg2,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
policy_12 = self.spd_add_rem_policy( # outbound, priority 5
- 1, self.pg1, self.pg2, socket.IPPROTO_UDP,
- is_out=1, priority=5, policy_type="discard")
+ 1,
+ self.pg1,
+ self.pg2,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=5,
+ policy_type="discard",
+ )
policy_21 = self.spd_add_rem_policy( # outbound, priority 5
- 1, self.pg2, self.pg0, socket.IPPROTO_UDP,
- is_out=1, priority=5, policy_type="bypass")
+ 1,
+ self.pg2,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=5,
+ policy_type="bypass",
+ )
policy_22 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg2, self.pg0, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="discard")
+ 1,
+ self.pg2,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="discard",
+ )
# interfaces bound to an SPD, will by default drop inbound
# traffic with no matching policies. add catch-all inbound
# bypass rule to SPD:
self.spd_add_rem_policy( # inbound, all interfaces
- 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10,
- policy_type="bypass", all_ips=True)
+ 1,
+ None,
+ None,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ all_ips=True,
+ )
# check flow cache is empty (0 active elements) before sending traffic
self.verify_num_outbound_flow_cache_entries(0)
@@ -338,8 +436,7 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheOutbound):
try:
self.logger.debug(ppp("SPD - Got packet:", packet))
except Exception:
- self.logger.error(
- ppp("Unexpected or invalid packet:", packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
self.logger.debug("SPD: Num packets: %s", len(if_caps[0].res))
self.logger.debug("SPD: Num packets: %s", len(if_caps[1].res))
@@ -366,6 +463,7 @@ class IPSec4SpdTestCaseMultiple(SpdFlowCacheOutbound):
class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound):
""" IPSec/IPv4 outbound: Policy mode test case with flow cache \
(overwrite stale entries)"""
+
def test_ipsec_spd_outbound_overwrite(self):
# The operation of the flow cache is setup so that the entire cache
# is invalidated when adding or removing an SPD policy rule.
@@ -386,23 +484,48 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound):
# add output rules on all interfaces
# pg0 -> pg1
policy_0 = self.spd_add_rem_policy( # outbound
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
# pg1 -> pg2
policy_1 = self.spd_add_rem_policy( # outbound
- 1, self.pg1, self.pg2, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg2,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
# pg2 -> pg0
policy_2 = self.spd_add_rem_policy( # outbound
- 1, self.pg2, self.pg0, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="discard")
+ 1,
+ self.pg2,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="discard",
+ )
# interfaces bound to an SPD, will by default drop inbound
# traffic with no matching policies. add catch-all inbound
# bypass rule to SPD:
self.spd_add_rem_policy( # inbound, all interfaces
- 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10,
- policy_type="bypass", all_ips=True)
+ 1,
+ None,
+ None,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ all_ips=True,
+ )
# check flow cache is empty (0 active elements) before sending traffic
self.verify_num_outbound_flow_cache_entries(0)
@@ -429,8 +552,7 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound):
try:
self.logger.debug(ppp("SPD Add - Got packet:", packet))
except Exception:
- self.logger.error(
- ppp("Unexpected or invalid packet:", packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
# verify captures that matched BYPASS rules
@@ -447,21 +569,39 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound):
# adding an inbound policy should not invalidate output flow cache
self.spd_add_rem_policy( # inbound
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=0, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ )
# check flow cache counter has not been reset
self.verify_num_outbound_flow_cache_entries(3)
# remove a bypass policy - flow cache counter will be reset, and
# there will be 3x stale entries in flow cache
self.spd_add_rem_policy( # outbound
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass",
- remove=True)
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ remove=True,
+ )
# readd policy
policy_0 = self.spd_add_rem_policy( # outbound
- 1, self.pg0, self.pg1, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg0,
+ self.pg1,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
# check counter was reset with flow cache invalidation
self.verify_num_outbound_flow_cache_entries(0)
@@ -481,8 +621,7 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound):
try:
self.logger.debug(ppp("SPD Add - Got packet:", packet))
except Exception:
- self.logger.error(
- ppp("Unexpected or invalid packet:", packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
# verify captures that matched BYPASS rules
@@ -492,8 +631,8 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound):
self.pg0.assert_nothing_captured()
# verify all policies matched the expected number of times
self.verify_policy_match(pkt_count, policy_0)
- self.verify_policy_match(pkt_count*2, policy_1)
- self.verify_policy_match(pkt_count*2, policy_2)
+ self.verify_policy_match(pkt_count * 2, policy_1)
+ self.verify_policy_match(pkt_count * 2, policy_2)
# we are overwriting 3x stale entries - check flow cache counter
# is correct
self.verify_num_outbound_flow_cache_entries(3)
@@ -502,18 +641,23 @@ class IPSec4SpdTestCaseOverwriteStale(SpdFlowCacheOutbound):
class IPSec4SpdTestCaseCollision(SpdFlowCacheOutbound):
""" IPSec/IPv4 outbound: Policy mode test case with flow cache \
(hash collision)"""
+
# Override class setup to restrict vector size to 16 elements.
# This forces using only the lower 4 bits of the hash as a key,
# making hash collisions easy to find.
@classmethod
def setUpConstants(cls):
super(SpdFlowCacheOutbound, cls).setUpConstants()
- cls.vpp_cmdline.extend(["ipsec", "{",
- "ipv4-outbound-spd-flow-cache on",
- "ipv4-outbound-spd-hash-buckets 16",
- "}"])
- cls.logger.info("VPP modified cmdline is %s" % " "
- .join(cls.vpp_cmdline))
+ cls.vpp_cmdline.extend(
+ [
+ "ipsec",
+ "{",
+ "ipv4-outbound-spd-flow-cache on",
+ "ipv4-outbound-spd-hash-buckets 16",
+ "}",
+ ]
+ )
+ cls.logger.info("VPP modified cmdline is %s" % " ".join(cls.vpp_cmdline))
def test_ipsec_spd_outbound_collision(self):
# The flow cache operation is setup to overwrite an entry
@@ -535,18 +679,37 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheOutbound):
self.spd_create_and_intf_add(1, self.pg_interfaces)
# add rules
policy_0 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg1, self.pg2, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg1,
+ self.pg2,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
policy_1 = self.spd_add_rem_policy( # outbound, priority 10
- 1, self.pg2, self.pg0, socket.IPPROTO_UDP,
- is_out=1, priority=10, policy_type="bypass")
+ 1,
+ self.pg2,
+ self.pg0,
+ socket.IPPROTO_UDP,
+ is_out=1,
+ priority=10,
+ policy_type="bypass",
+ )
# interfaces bound to an SPD, will by default drop inbound
# traffic with no matching policies. add catch-all inbound
# bypass rule to SPD:
self.spd_add_rem_policy( # inbound, all interfaces
- 1, None, None, socket.IPPROTO_UDP, is_out=0, priority=10,
- policy_type="bypass", all_ips=True)
+ 1,
+ None,
+ None,
+ socket.IPPROTO_UDP,
+ is_out=0,
+ priority=10,
+ policy_type="bypass",
+ all_ips=True,
+ )
# check flow cache is empty (0 active elements) before sending traffic
self.verify_num_outbound_flow_cache_entries(0)
@@ -580,11 +743,9 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheOutbound):
if_caps.append(pg.get_capture())
for packet in if_caps[-1]:
try:
- self.logger.debug(ppp(
- "SPD - Got packet:", packet))
+ self.logger.debug(ppp("SPD - Got packet:", packet))
except Exception:
- self.logger.error(ppp(
- "Unexpected or invalid packet:", packet))
+ self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
self.logger.debug("SPD: Num packets: %s", len(if_caps[0].res))
self.logger.debug("SPD: Num packets: %s", len(if_caps[1].res))
@@ -600,5 +761,5 @@ class IPSec4SpdTestCaseCollision(SpdFlowCacheOutbound):
self.verify_num_outbound_flow_cache_entries(1)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ipsec_tun_if_esp.py b/test/test_ipsec_tun_if_esp.py
index 14c9b3e3f11..9da75f0a4aa 100644
--- a/test/test_ipsec_tun_if_esp.py
+++ b/test/test_ipsec_tun_if_esp.py
@@ -10,13 +10,29 @@ from scapy.layers.inet6 import IPv6
from scapy.contrib.mpls import MPLS
from framework import tag_fixme_vpp_workers
from framework import VppTestRunner
-from template_ipsec import TemplateIpsec, IpsecTun4Tests, IpsecTun6Tests, \
- IpsecTun4, IpsecTun6, IpsecTcpTests, mk_scapy_crypt_key, \
- IpsecTun6HandoffTests, IpsecTun4HandoffTests, config_tun_params
+from template_ipsec import (
+ TemplateIpsec,
+ IpsecTun4Tests,
+ IpsecTun6Tests,
+ IpsecTun4,
+ IpsecTun6,
+ IpsecTcpTests,
+ mk_scapy_crypt_key,
+ IpsecTun6HandoffTests,
+ IpsecTun4HandoffTests,
+ config_tun_params,
+)
from vpp_gre_interface import VppGreInterface
from vpp_ipip_tun_interface import VppIpIpTunInterface
-from vpp_ip_route import VppIpRoute, VppRoutePath, DpoProto, VppMplsLabel, \
- VppMplsTable, VppMplsRoute, FibPathProto
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ DpoProto,
+ VppMplsLabel,
+ VppMplsTable,
+ VppMplsRoute,
+ FibPathProto,
+)
from vpp_ipsec import VppIpsecSA, VppIpsecTunProtect, VppIpsecInterface
from vpp_l2 import VppBridgeDomain, VppBridgeDomainPort
from vpp_sub_interface import L2_VTR_OP, VppDot1QSubint
@@ -30,8 +46,9 @@ from vpp_policer import PolicerAction, VppPolicer, Dir
def config_tun_params(p, encryption_type, tun_if, src=None, dst=None):
ip_class_by_addr_type = {socket.AF_INET: IP, socket.AF_INET6: IPv6}
- esn_en = bool(p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_USE_ESN))
+ esn_en = bool(
+ p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ESN)
+ )
crypt_key = mk_scapy_crypt_key(p)
if tun_if:
p.tun_dst = tun_if.remote_ip
@@ -41,77 +58,84 @@ def config_tun_params(p, encryption_type, tun_if, src=None, dst=None):
p.tun_src = src
if p.nat_header:
- is_default_port = (p.nat_header.dport == 4500)
+ is_default_port = p.nat_header.dport == 4500
else:
is_default_port = True
if is_default_port:
outbound_nat_header = p.nat_header
else:
- outbound_nat_header = UDP(sport=p.nat_header.dport,
- dport=p.nat_header.sport)
+ outbound_nat_header = UDP(sport=p.nat_header.dport, dport=p.nat_header.sport)
bind_layers(UDP, ESP, dport=p.nat_header.dport)
p.scapy_tun_sa = SecurityAssociation(
- encryption_type, spi=p.vpp_tun_spi,
+ encryption_type,
+ spi=p.vpp_tun_spi,
crypt_algo=p.crypt_algo,
crypt_key=crypt_key,
- auth_algo=p.auth_algo, auth_key=p.auth_key,
- tunnel_header=ip_class_by_addr_type[p.addr_type](
- src=p.tun_dst,
- dst=p.tun_src),
+ auth_algo=p.auth_algo,
+ auth_key=p.auth_key,
+ tunnel_header=ip_class_by_addr_type[p.addr_type](src=p.tun_dst, dst=p.tun_src),
nat_t_header=outbound_nat_header,
- esn_en=esn_en)
+ esn_en=esn_en,
+ )
p.vpp_tun_sa = SecurityAssociation(
- encryption_type, spi=p.scapy_tun_spi,
+ encryption_type,
+ spi=p.scapy_tun_spi,
crypt_algo=p.crypt_algo,
crypt_key=crypt_key,
- auth_algo=p.auth_algo, auth_key=p.auth_key,
- tunnel_header=ip_class_by_addr_type[p.addr_type](
- dst=p.tun_dst,
- src=p.tun_src),
+ auth_algo=p.auth_algo,
+ auth_key=p.auth_key,
+ tunnel_header=ip_class_by_addr_type[p.addr_type](dst=p.tun_dst, src=p.tun_src),
nat_t_header=p.nat_header,
- esn_en=esn_en)
+ esn_en=esn_en,
+ )
def config_tra_params(p, encryption_type, tun_if):
ip_class_by_addr_type = {socket.AF_INET: IP, socket.AF_INET6: IPv6}
- esn_en = bool(p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_USE_ESN))
+ esn_en = bool(
+ p.flags & (VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_USE_ESN)
+ )
crypt_key = mk_scapy_crypt_key(p)
p.tun_dst = tun_if.remote_ip
p.tun_src = tun_if.local_ip
if p.nat_header:
- is_default_port = (p.nat_header.dport == 4500)
+ is_default_port = p.nat_header.dport == 4500
else:
is_default_port = True
if is_default_port:
outbound_nat_header = p.nat_header
else:
- outbound_nat_header = UDP(sport=p.nat_header.dport,
- dport=p.nat_header.sport)
+ outbound_nat_header = UDP(sport=p.nat_header.dport, dport=p.nat_header.sport)
bind_layers(UDP, ESP, dport=p.nat_header.dport)
p.scapy_tun_sa = SecurityAssociation(
- encryption_type, spi=p.vpp_tun_spi,
+ encryption_type,
+ spi=p.vpp_tun_spi,
crypt_algo=p.crypt_algo,
crypt_key=crypt_key,
- auth_algo=p.auth_algo, auth_key=p.auth_key,
+ auth_algo=p.auth_algo,
+ auth_key=p.auth_key,
esn_en=esn_en,
- nat_t_header=outbound_nat_header)
+ nat_t_header=outbound_nat_header,
+ )
p.vpp_tun_sa = SecurityAssociation(
- encryption_type, spi=p.scapy_tun_spi,
+ encryption_type,
+ spi=p.scapy_tun_spi,
crypt_algo=p.crypt_algo,
crypt_key=crypt_key,
- auth_algo=p.auth_algo, auth_key=p.auth_key,
+ auth_algo=p.auth_algo,
+ auth_key=p.auth_key,
esn_en=esn_en,
- nat_t_header=p.nat_header)
+ nat_t_header=p.nat_header,
+ )
class TemplateIpsec4TunProtect(object):
- """ IPsec IPv4 Tunnel protect """
+ """IPsec IPv4 Tunnel protect"""
encryption_type = ESP
tun4_encrypt_node_name = "esp4-encrypt-tun"
@@ -121,69 +145,97 @@ class TemplateIpsec4TunProtect(object):
def config_sa_tra(self, p):
config_tun_params(p, self.encryption_type, p.tun_if)
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- flags=p.flags)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ flags=p.flags,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- flags=p.flags)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ flags=p.flags,
+ )
p.tun_sa_in.add_vpp_config()
def config_sa_tun(self, p):
config_tun_params(p, self.encryption_type, p.tun_if)
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- self.tun_if.local_addr[p.addr_type],
- self.tun_if.remote_addr[p.addr_type],
- flags=p.flags)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ self.tun_if.local_addr[p.addr_type],
+ self.tun_if.remote_addr[p.addr_type],
+ flags=p.flags,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- self.tun_if.remote_addr[p.addr_type],
- self.tun_if.local_addr[p.addr_type],
- flags=p.flags)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ self.tun_if.remote_addr[p.addr_type],
+ self.tun_if.local_addr[p.addr_type],
+ flags=p.flags,
+ )
p.tun_sa_in.add_vpp_config()
def config_protect(self, p):
- p.tun_protect = VppIpsecTunProtect(self,
- p.tun_if,
- p.tun_sa_out,
- [p.tun_sa_in])
+ p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in])
p.tun_protect.add_vpp_config()
def config_network(self, p):
- if hasattr(p, 'tun_dst'):
+ if hasattr(p, "tun_dst"):
tun_dst = p.tun_dst
else:
tun_dst = self.pg0.remote_ip4
- p.tun_if = VppIpIpTunInterface(self, self.pg0,
- self.pg0.local_ip4,
- tun_dst)
+ p.tun_if = VppIpIpTunInterface(self, self.pg0, self.pg0.local_ip4, tun_dst)
p.tun_if.add_vpp_config()
p.tun_if.admin_up()
p.tun_if.config_ip4()
p.tun_if.config_ip6()
- p.route = VppIpRoute(self, p.remote_tun_if_host, 32,
- [VppRoutePath(p.tun_if.remote_ip4,
- 0xffffffff)])
+ p.route = VppIpRoute(
+ self,
+ p.remote_tun_if_host,
+ 32,
+ [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)],
+ )
p.route.add_vpp_config()
- r = VppIpRoute(self, p.remote_tun_if_host6, 128,
- [VppRoutePath(p.tun_if.remote_ip6,
- 0xffffffff,
- proto=DpoProto.DPO_PROTO_IP6)])
+ r = VppIpRoute(
+ self,
+ p.remote_tun_if_host6,
+ 128,
+ [
+ VppRoutePath(
+ p.tun_if.remote_ip6, 0xFFFFFFFF, proto=DpoProto.DPO_PROTO_IP6
+ )
+ ],
+ )
r.add_vpp_config()
def unconfig_network(self, p):
@@ -198,9 +250,8 @@ class TemplateIpsec4TunProtect(object):
p.tun_sa_in.remove_vpp_config()
-class TemplateIpsec4TunIfEsp(TemplateIpsec4TunProtect,
- TemplateIpsec):
- """ IPsec tunnel interface tests """
+class TemplateIpsec4TunIfEsp(TemplateIpsec4TunProtect, TemplateIpsec):
+ """IPsec tunnel interface tests"""
encryption_type = ESP
@@ -227,9 +278,8 @@ class TemplateIpsec4TunIfEsp(TemplateIpsec4TunProtect,
super(TemplateIpsec4TunIfEsp, self).tearDown()
-class TemplateIpsec4TunIfEspUdp(TemplateIpsec4TunProtect,
- TemplateIpsec):
- """ IPsec UDP tunnel interface tests """
+class TemplateIpsec4TunIfEspUdp(TemplateIpsec4TunProtect, TemplateIpsec):
+ """IPsec UDP tunnel interface tests"""
tun4_encrypt_node_name = "esp4-encrypt-tun"
tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"]
@@ -270,30 +320,41 @@ class TemplateIpsec4TunIfEspUdp(TemplateIpsec4TunProtect,
def config_sa_tra(self, p):
config_tun_params(p, self.encryption_type, p.tun_if)
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- flags=p.flags,
- udp_src=p.nat_header.sport,
- udp_dst=p.nat_header.dport)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ flags=p.flags,
+ udp_src=p.nat_header.sport,
+ udp_dst=p.nat_header.dport,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- flags=p.flags,
- udp_src=p.nat_header.sport,
- udp_dst=p.nat_header.dport)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ flags=p.flags,
+ udp_src=p.nat_header.sport,
+ udp_dst=p.nat_header.dport,
+ )
p.tun_sa_in.add_vpp_config()
def setUp(self):
super(TemplateIpsec4TunIfEspUdp, self).setUp()
p = self.ipv4_params
- p.flags = (VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_UDP_ENCAP)
+ p.flags = VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_UDP_ENCAP
p.nat_header = UDP(sport=5454, dport=4500)
self.tun_if = self.pg0
@@ -307,38 +368,38 @@ class TemplateIpsec4TunIfEspUdp(TemplateIpsec4TunProtect,
class TestIpsec4TunIfEsp1(TemplateIpsec4TunIfEsp, IpsecTun4Tests):
- """ Ipsec ESP - TUN tests """
+ """Ipsec ESP - TUN tests"""
+
tun4_encrypt_node_name = "esp4-encrypt-tun"
tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"]
def test_tun_basic64(self):
- """ ipsec 6o4 tunnel basic test """
+ """ipsec 6o4 tunnel basic test"""
self.tun4_encrypt_node_name = "esp4-encrypt-tun"
self.verify_tun_64(self.params[socket.AF_INET], count=1)
def test_tun_burst64(self):
- """ ipsec 6o4 tunnel basic test """
+ """ipsec 6o4 tunnel basic test"""
self.tun4_encrypt_node_name = "esp4-encrypt-tun"
self.verify_tun_64(self.params[socket.AF_INET], count=257)
def test_tun_basic_frag44(self):
- """ ipsec 4o4 tunnel frag basic test """
+ """ipsec 4o4 tunnel frag basic test"""
self.tun4_encrypt_node_name = "esp4-encrypt-tun"
p = self.ipv4_params
- self.vapi.sw_interface_set_mtu(p.tun_if.sw_if_index,
- [1500, 0, 0, 0])
- self.verify_tun_44(self.params[socket.AF_INET],
- count=1, payload_size=1800, n_rx=2)
- self.vapi.sw_interface_set_mtu(p.tun_if.sw_if_index,
- [9000, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(p.tun_if.sw_if_index, [1500, 0, 0, 0])
+ self.verify_tun_44(
+ self.params[socket.AF_INET], count=1, payload_size=1800, n_rx=2
+ )
+ self.vapi.sw_interface_set_mtu(p.tun_if.sw_if_index, [9000, 0, 0, 0])
class TestIpsec4TunIfEspUdp(TemplateIpsec4TunIfEspUdp, IpsecTun4Tests):
- """ Ipsec ESP UDP tests """
+ """Ipsec ESP UDP tests"""
tun4_input_node = "ipsec4-tun-input"
@@ -346,22 +407,22 @@ class TestIpsec4TunIfEspUdp(TemplateIpsec4TunIfEspUdp, IpsecTun4Tests):
super(TestIpsec4TunIfEspUdp, self).setUp()
def test_keepalive(self):
- """ IPSEC NAT Keepalive """
+ """IPSEC NAT Keepalive"""
self.verify_keepalive(self.ipv4_params)
class TestIpsec4TunIfEspUdpGCM(TemplateIpsec4TunIfEspUdp, IpsecTun4Tests):
- """ Ipsec ESP UDP GCM tests """
+ """Ipsec ESP UDP GCM tests"""
tun4_input_node = "ipsec4-tun-input"
def setUp(self):
super(TestIpsec4TunIfEspUdpGCM, self).setUp()
p = self.ipv4_params
- p.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_NONE)
- p.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_GCM_256)
+ p.auth_algo_vpp_id = VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE
+ p.crypt_algo_vpp_id = (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_256
+ )
p.crypt_algo = "AES-GCM"
p.auth_algo = "NULL"
p.crypt_key = b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h"
@@ -369,75 +430,104 @@ class TestIpsec4TunIfEspUdpGCM(TemplateIpsec4TunIfEspUdp, IpsecTun4Tests):
class TestIpsec4TunIfEsp2(TemplateIpsec4TunIfEsp, IpsecTcpTests):
- """ Ipsec ESP - TCP tests """
+ """Ipsec ESP - TCP tests"""
+
pass
class TemplateIpsec6TunProtect(object):
- """ IPsec IPv6 Tunnel protect """
+ """IPsec IPv6 Tunnel protect"""
def config_sa_tra(self, p):
config_tun_params(p, self.encryption_type, p.tun_if)
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_in.add_vpp_config()
def config_sa_tun(self, p):
config_tun_params(p, self.encryption_type, p.tun_if)
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- self.tun_if.local_addr[p.addr_type],
- self.tun_if.remote_addr[p.addr_type])
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ self.tun_if.local_addr[p.addr_type],
+ self.tun_if.remote_addr[p.addr_type],
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- self.tun_if.remote_addr[p.addr_type],
- self.tun_if.local_addr[p.addr_type])
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ self.tun_if.remote_addr[p.addr_type],
+ self.tun_if.local_addr[p.addr_type],
+ )
p.tun_sa_in.add_vpp_config()
def config_protect(self, p):
- p.tun_protect = VppIpsecTunProtect(self,
- p.tun_if,
- p.tun_sa_out,
- [p.tun_sa_in])
+ p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in])
p.tun_protect.add_vpp_config()
def config_network(self, p):
- if hasattr(p, 'tun_dst'):
+ if hasattr(p, "tun_dst"):
tun_dst = p.tun_dst
else:
tun_dst = self.pg0.remote_ip6
- p.tun_if = VppIpIpTunInterface(self, self.pg0,
- self.pg0.local_ip6,
- tun_dst)
+ p.tun_if = VppIpIpTunInterface(self, self.pg0, self.pg0.local_ip6, tun_dst)
p.tun_if.add_vpp_config()
p.tun_if.admin_up()
p.tun_if.config_ip6()
p.tun_if.config_ip4()
- p.route = VppIpRoute(self, p.remote_tun_if_host, 128,
- [VppRoutePath(p.tun_if.remote_ip6,
- 0xffffffff,
- proto=DpoProto.DPO_PROTO_IP6)])
+ p.route = VppIpRoute(
+ self,
+ p.remote_tun_if_host,
+ 128,
+ [
+ VppRoutePath(
+ p.tun_if.remote_ip6, 0xFFFFFFFF, proto=DpoProto.DPO_PROTO_IP6
+ )
+ ],
+ )
p.route.add_vpp_config()
- r = VppIpRoute(self, p.remote_tun_if_host4, 32,
- [VppRoutePath(p.tun_if.remote_ip4,
- 0xffffffff)])
+ r = VppIpRoute(
+ self,
+ p.remote_tun_if_host4,
+ 32,
+ [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)],
+ )
r.add_vpp_config()
def unconfig_network(self, p):
@@ -452,9 +542,8 @@ class TemplateIpsec6TunProtect(object):
p.tun_sa_in.remove_vpp_config()
-class TemplateIpsec6TunIfEsp(TemplateIpsec6TunProtect,
- TemplateIpsec):
- """ IPsec tunnel interface tests """
+class TemplateIpsec6TunIfEsp(TemplateIpsec6TunProtect, TemplateIpsec):
+ """IPsec tunnel interface tests"""
encryption_type = ESP
@@ -472,31 +561,31 @@ class TemplateIpsec6TunIfEsp(TemplateIpsec6TunProtect,
super(TemplateIpsec6TunIfEsp, self).tearDown()
-class TestIpsec6TunIfEsp1(TemplateIpsec6TunIfEsp,
- IpsecTun6Tests):
- """ Ipsec ESP - TUN tests """
+class TestIpsec6TunIfEsp1(TemplateIpsec6TunIfEsp, IpsecTun6Tests):
+ """Ipsec ESP - TUN tests"""
+
tun6_encrypt_node_name = "esp6-encrypt-tun"
tun6_decrypt_node_name = ["esp6-decrypt-tun", "esp6-decrypt-tun-post"]
def test_tun_basic46(self):
- """ ipsec 4o6 tunnel basic test """
+ """ipsec 4o6 tunnel basic test"""
self.tun6_encrypt_node_name = "esp6-encrypt-tun"
self.verify_tun_46(self.params[socket.AF_INET6], count=1)
def test_tun_burst46(self):
- """ ipsec 4o6 tunnel burst test """
+ """ipsec 4o6 tunnel burst test"""
self.tun6_encrypt_node_name = "esp6-encrypt-tun"
self.verify_tun_46(self.params[socket.AF_INET6], count=257)
-class TestIpsec6TunIfEspHandoff(TemplateIpsec6TunIfEsp,
- IpsecTun6HandoffTests):
- """ Ipsec ESP 6 Handoff tests """
+class TestIpsec6TunIfEspHandoff(TemplateIpsec6TunIfEsp, IpsecTun6HandoffTests):
+ """Ipsec ESP 6 Handoff tests"""
+
tun6_encrypt_node_name = "esp6-encrypt-tun"
tun6_decrypt_node_name = ["esp6-decrypt-tun", "esp6-decrypt-tun-post"]
def test_tun_handoff_66_police(self):
- """ ESP 6o6 tunnel with policer worker hand-off test """
+ """ESP 6o6 tunnel with policer worker hand-off test"""
self.vapi.cli("clear errors")
self.vapi.cli("clear ipsec sa")
@@ -504,12 +593,19 @@ class TestIpsec6TunIfEspHandoff(TemplateIpsec6TunIfEsp,
p = self.params[socket.AF_INET6]
action_tx = PolicerAction(
- VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT,
- 0)
- policer = VppPolicer(self, "pol1", 80, 0, 1000, 0,
- conform_action=action_tx,
- exceed_action=action_tx,
- violate_action=action_tx)
+ VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0
+ )
+ policer = VppPolicer(
+ self,
+ "pol1",
+ 80,
+ 0,
+ 1000,
+ 0,
+ conform_action=action_tx,
+ exceed_action=action_tx,
+ violate_action=action_tx,
+ )
policer.add_vpp_config()
# Start policing on tun
@@ -520,13 +616,17 @@ class TestIpsec6TunIfEspHandoff(TemplateIpsec6TunIfEsp,
# inject alternately on worker 0 and 1.
for worker in [0, 1, 0, 1]:
- send_pkts = self.gen_encrypt_pkts6(p, p.scapy_tun_sa,
- self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip6,
- count=N_PKTS)
- recv_pkts = self.send_and_expect(self.tun_if, send_pkts,
- self.pg1, worker=worker)
+ send_pkts = self.gen_encrypt_pkts6(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip6,
+ count=N_PKTS,
+ )
+ recv_pkts = self.send_and_expect(
+ self.tun_if, send_pkts, self.pg1, worker=worker
+ )
self.verify_decrypted6(p, recv_pkts)
self.logger.debug(self.vapi.cli("show trace max 100"))
@@ -539,36 +639,36 @@ class TestIpsec6TunIfEspHandoff(TemplateIpsec6TunIfEsp,
self.assertEqual(stats, stats1)
# Worker 0, should have handed everything off
- self.assertEqual(stats0['conform_packets'], 0)
- self.assertEqual(stats0['exceed_packets'], 0)
- self.assertEqual(stats0['violate_packets'], 0)
+ self.assertEqual(stats0["conform_packets"], 0)
+ self.assertEqual(stats0["exceed_packets"], 0)
+ self.assertEqual(stats0["violate_packets"], 0)
else:
# Second pass: both workers should have policed equal amounts
- self.assertGreater(stats1['conform_packets'], 0)
- self.assertEqual(stats1['exceed_packets'], 0)
- self.assertGreater(stats1['violate_packets'], 0)
+ self.assertGreater(stats1["conform_packets"], 0)
+ self.assertEqual(stats1["exceed_packets"], 0)
+ self.assertGreater(stats1["violate_packets"], 0)
- self.assertGreater(stats0['conform_packets'], 0)
- self.assertEqual(stats0['exceed_packets'], 0)
- self.assertGreater(stats0['violate_packets'], 0)
+ self.assertGreater(stats0["conform_packets"], 0)
+ self.assertEqual(stats0["exceed_packets"], 0)
+ self.assertGreater(stats0["violate_packets"], 0)
- self.assertEqual(stats0['conform_packets'] +
- stats0['violate_packets'],
- stats1['conform_packets'] +
- stats1['violate_packets'])
+ self.assertEqual(
+ stats0["conform_packets"] + stats0["violate_packets"],
+ stats1["conform_packets"] + stats1["violate_packets"],
+ )
policer.apply_vpp_config(p.tun_if.sw_if_index, Dir.RX, False)
policer.remove_vpp_config()
-class TestIpsec4TunIfEspHandoff(TemplateIpsec4TunIfEsp,
- IpsecTun4HandoffTests):
- """ Ipsec ESP 4 Handoff tests """
+class TestIpsec4TunIfEspHandoff(TemplateIpsec4TunIfEsp, IpsecTun4HandoffTests):
+ """Ipsec ESP 4 Handoff tests"""
+
tun4_encrypt_node_name = "esp4-encrypt-tun"
tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"]
def test_tun_handoff_44_police(self):
- """ ESP 4o4 tunnel with policer worker hand-off test """
+ """ESP 4o4 tunnel with policer worker hand-off test"""
self.vapi.cli("clear errors")
self.vapi.cli("clear ipsec sa")
@@ -576,12 +676,19 @@ class TestIpsec4TunIfEspHandoff(TemplateIpsec4TunIfEsp,
p = self.params[socket.AF_INET]
action_tx = PolicerAction(
- VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT,
- 0)
- policer = VppPolicer(self, "pol1", 80, 0, 1000, 0,
- conform_action=action_tx,
- exceed_action=action_tx,
- violate_action=action_tx)
+ VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0
+ )
+ policer = VppPolicer(
+ self,
+ "pol1",
+ 80,
+ 0,
+ 1000,
+ 0,
+ conform_action=action_tx,
+ exceed_action=action_tx,
+ violate_action=action_tx,
+ )
policer.add_vpp_config()
# Start policing on tun
@@ -592,13 +699,17 @@ class TestIpsec4TunIfEspHandoff(TemplateIpsec4TunIfEsp,
# inject alternately on worker 0 and 1.
for worker in [0, 1, 0, 1]:
- send_pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa,
- self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip4,
- count=N_PKTS)
- recv_pkts = self.send_and_expect(self.tun_if, send_pkts,
- self.pg1, worker=worker)
+ send_pkts = self.gen_encrypt_pkts(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip4,
+ count=N_PKTS,
+ )
+ recv_pkts = self.send_and_expect(
+ self.tun_if, send_pkts, self.pg1, worker=worker
+ )
self.verify_decrypted(p, recv_pkts)
self.logger.debug(self.vapi.cli("show trace max 100"))
@@ -611,33 +722,31 @@ class TestIpsec4TunIfEspHandoff(TemplateIpsec4TunIfEsp,
self.assertEqual(stats, stats1)
# Worker 0, should have handed everything off
- self.assertEqual(stats0['conform_packets'], 0)
- self.assertEqual(stats0['exceed_packets'], 0)
- self.assertEqual(stats0['violate_packets'], 0)
+ self.assertEqual(stats0["conform_packets"], 0)
+ self.assertEqual(stats0["exceed_packets"], 0)
+ self.assertEqual(stats0["violate_packets"], 0)
else:
# Second pass: both workers should have policed equal amounts
- self.assertGreater(stats1['conform_packets'], 0)
- self.assertEqual(stats1['exceed_packets'], 0)
- self.assertGreater(stats1['violate_packets'], 0)
+ self.assertGreater(stats1["conform_packets"], 0)
+ self.assertEqual(stats1["exceed_packets"], 0)
+ self.assertGreater(stats1["violate_packets"], 0)
- self.assertGreater(stats0['conform_packets'], 0)
- self.assertEqual(stats0['exceed_packets'], 0)
- self.assertGreater(stats0['violate_packets'], 0)
+ self.assertGreater(stats0["conform_packets"], 0)
+ self.assertEqual(stats0["exceed_packets"], 0)
+ self.assertGreater(stats0["violate_packets"], 0)
- self.assertEqual(stats0['conform_packets'] +
- stats0['violate_packets'],
- stats1['conform_packets'] +
- stats1['violate_packets'])
+ self.assertEqual(
+ stats0["conform_packets"] + stats0["violate_packets"],
+ stats1["conform_packets"] + stats1["violate_packets"],
+ )
policer.apply_vpp_config(p.tun_if.sw_if_index, Dir.RX, False)
policer.remove_vpp_config()
@tag_fixme_vpp_workers
-class TestIpsec4MultiTunIfEsp(TemplateIpsec4TunProtect,
- TemplateIpsec,
- IpsecTun4):
- """ IPsec IPv4 Multi Tunnel interface """
+class TestIpsec4MultiTunIfEsp(TemplateIpsec4TunProtect, TemplateIpsec, IpsecTun4):
+ """IPsec IPv4 Multi Tunnel interface"""
encryption_type = ESP
tun4_encrypt_node_name = "esp4-encrypt-tun"
@@ -676,19 +785,23 @@ class TestIpsec4MultiTunIfEsp(TemplateIpsec4TunProtect,
super(TestIpsec4MultiTunIfEsp, self).tearDown()
def test_tun_44(self):
- """Multiple IPSEC tunnel interfaces """
+ """Multiple IPSEC tunnel interfaces"""
for p in self.multi_params:
self.verify_tun_44(p, count=127)
self.assertEqual(p.tun_if.get_rx_stats(), 127)
self.assertEqual(p.tun_if.get_tx_stats(), 127)
def test_tun_rr_44(self):
- """ Round-robin packets acrros multiple interface """
+ """Round-robin packets acrros multiple interface"""
tx = []
for p in self.multi_params:
- tx = tx + self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip4)
+ tx = tx + self.gen_encrypt_pkts(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip4,
+ )
rxs = self.send_and_expect(self.tun_if, tx, self.pg1)
for rx, p in zip(rxs, self.multi_params):
@@ -696,18 +809,17 @@ class TestIpsec4MultiTunIfEsp(TemplateIpsec4TunProtect,
tx = []
for p in self.multi_params:
- tx = tx + self.gen_pkts(self.pg1, src=self.pg1.remote_ip4,
- dst=p.remote_tun_if_host)
+ tx = tx + self.gen_pkts(
+ self.pg1, src=self.pg1.remote_ip4, dst=p.remote_tun_if_host
+ )
rxs = self.send_and_expect(self.pg1, tx, self.tun_if)
for rx, p in zip(rxs, self.multi_params):
self.verify_encrypted(p, p.vpp_tun_sa, [rx])
-class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect,
- TemplateIpsec,
- IpsecTun4):
- """ IPsec IPv4 Tunnel interface all Algos """
+class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect, TemplateIpsec, IpsecTun4):
+ """IPsec IPv4 Tunnel interface all Algos"""
encryption_type = ESP
tun4_encrypt_node_name = "esp4-encrypt-tun"
@@ -736,7 +848,7 @@ class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect,
# change the key and the SPI
#
np = copy.copy(p)
- p.crypt_key = b'X' + p.crypt_key[1:]
+ p.crypt_key = b"X" + p.crypt_key[1:]
p.scapy_tun_spi += 1
p.scapy_tun_sa_id += 1
p.vpp_tun_spi += 1
@@ -746,26 +858,30 @@ class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect,
config_tun_params(p, self.encryption_type, p.tun_if)
- p.tun_sa_out = VppIpsecSA(self,
- p.scapy_tun_sa_id,
- p.scapy_tun_spi,
- p.auth_algo_vpp_id,
- p.auth_key,
- p.crypt_algo_vpp_id,
- p.crypt_key,
- self.vpp_esp_protocol,
- flags=p.flags,
- salt=p.salt)
- p.tun_sa_in = VppIpsecSA(self,
- p.vpp_tun_sa_id,
- p.vpp_tun_spi,
- p.auth_algo_vpp_id,
- p.auth_key,
- p.crypt_algo_vpp_id,
- p.crypt_key,
- self.vpp_esp_protocol,
- flags=p.flags,
- salt=p.salt)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ flags=p.flags,
+ salt=p.salt,
+ )
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ flags=p.flags,
+ salt=p.salt,
+ )
p.tun_sa_in.add_vpp_config()
p.tun_sa_out.add_vpp_config()
@@ -775,68 +891,98 @@ class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect,
self.logger.info(self.vapi.cli("sh ipsec sa"))
def test_tun_44(self):
- """IPSEC tunnel all algos """
+ """IPSEC tunnel all algos"""
# foreach VPP crypto engine
engines = ["ia32", "ipsecmb", "openssl"]
# foreach crypto algorithm
- algos = [{'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_GCM_128),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_NONE),
- 'scapy-crypto': "AES-GCM",
- 'scapy-integ': "NULL",
- 'key': b"JPjyOWBeVEQiMe7h",
- 'salt': 3333},
- {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_GCM_192),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_NONE),
- 'scapy-crypto': "AES-GCM",
- 'scapy-integ': "NULL",
- 'key': b"JPjyOWBeVEQiMe7hJPjyOWBe",
- 'salt': 0},
- {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_GCM_256),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_NONE),
- 'scapy-crypto': "AES-GCM",
- 'scapy-integ': "NULL",
- 'key': b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h",
- 'salt': 9999},
- {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CBC_128),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96),
- 'scapy-crypto': "AES-CBC",
- 'scapy-integ': "HMAC-SHA1-96",
- 'salt': 0,
- 'key': b"JPjyOWBeVEQiMe7h"},
- {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CBC_192),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA_512_256),
- 'scapy-crypto': "AES-CBC",
- 'scapy-integ': "SHA2-512-256",
- 'salt': 0,
- 'key': b"JPjyOWBeVEQiMe7hJPjyOWBe"},
- {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CBC_256),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA_256_128),
- 'scapy-crypto': "AES-CBC",
- 'scapy-integ': "SHA2-256-128",
- 'salt': 0,
- 'key': b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h"},
- {'vpp-crypto': (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_NONE),
- 'vpp-integ': (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96),
- 'scapy-crypto': "NULL",
- 'scapy-integ': "HMAC-SHA1-96",
- 'salt': 0,
- 'key': b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h"}]
+ algos = [
+ {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_128
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE
+ ),
+ "scapy-crypto": "AES-GCM",
+ "scapy-integ": "NULL",
+ "key": b"JPjyOWBeVEQiMe7h",
+ "salt": 3333,
+ },
+ {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_192
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE
+ ),
+ "scapy-crypto": "AES-GCM",
+ "scapy-integ": "NULL",
+ "key": b"JPjyOWBeVEQiMe7hJPjyOWBe",
+ "salt": 0,
+ },
+ {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_GCM_256
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE
+ ),
+ "scapy-crypto": "AES-GCM",
+ "scapy-integ": "NULL",
+ "key": b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h",
+ "salt": 9999,
+ },
+ {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96
+ ),
+ "scapy-crypto": "AES-CBC",
+ "scapy-integ": "HMAC-SHA1-96",
+ "salt": 0,
+ "key": b"JPjyOWBeVEQiMe7h",
+ },
+ {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_192
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA_512_256
+ ),
+ "scapy-crypto": "AES-CBC",
+ "scapy-integ": "SHA2-512-256",
+ "salt": 0,
+ "key": b"JPjyOWBeVEQiMe7hJPjyOWBe",
+ },
+ {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_256
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA_256_128
+ ),
+ "scapy-crypto": "AES-CBC",
+ "scapy-integ": "SHA2-256-128",
+ "salt": 0,
+ "key": b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h",
+ },
+ {
+ "vpp-crypto": (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_NONE
+ ),
+ "vpp-integ": (
+ VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96
+ ),
+ "scapy-crypto": "NULL",
+ "scapy-integ": "HMAC-SHA1-96",
+ "salt": 0,
+ "key": b"JPjyOWBeVEQiMe7hJPjyOWBeVEQiMe7h",
+ },
+ ]
for engine in engines:
self.vapi.cli("set crypto handler all %s" % engine)
@@ -848,12 +994,12 @@ class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect,
# with self.subTest(algo=algo['scapy']):
p = self.ipv4_params
- p.auth_algo_vpp_id = algo['vpp-integ']
- p.crypt_algo_vpp_id = algo['vpp-crypto']
- p.crypt_algo = algo['scapy-crypto']
- p.auth_algo = algo['scapy-integ']
- p.crypt_key = algo['key']
- p.salt = algo['salt']
+ p.auth_algo_vpp_id = algo["vpp-integ"]
+ p.crypt_algo_vpp_id = algo["vpp-crypto"]
+ p.crypt_algo = algo["scapy-crypto"]
+ p.auth_algo = algo["scapy-integ"]
+ p.crypt_key = algo["key"]
+ p.salt = algo["salt"]
#
# rekey the tunnel
@@ -862,10 +1008,8 @@ class TestIpsec4TunIfEspAll(TemplateIpsec4TunProtect,
self.verify_tun_44(p, count=127)
-class TestIpsec4TunIfEspNoAlgo(TemplateIpsec4TunProtect,
- TemplateIpsec,
- IpsecTun4):
- """ IPsec IPv4 Tunnel interface no Algos """
+class TestIpsec4TunIfEspNoAlgo(TemplateIpsec4TunProtect, TemplateIpsec, IpsecTun4):
+ """IPsec IPv4 Tunnel interface no Algos"""
encryption_type = ESP
tun4_encrypt_node_name = "esp4-encrypt-tun"
@@ -876,29 +1020,28 @@ class TestIpsec4TunIfEspNoAlgo(TemplateIpsec4TunProtect,
self.tun_if = self.pg0
p = self.ipv4_params
- p.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_NONE)
- p.auth_algo = 'NULL'
+ p.auth_algo_vpp_id = VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE
+ p.auth_algo = "NULL"
p.auth_key = []
- p.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_NONE)
- p.crypt_algo = 'NULL'
+ p.crypt_algo_vpp_id = (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_NONE
+ )
+ p.crypt_algo = "NULL"
p.crypt_key = []
def tearDown(self):
super(TestIpsec4TunIfEspNoAlgo, self).tearDown()
def test_tun_44(self):
- """ IPSec SA with NULL algos """
+ """IPSec SA with NULL algos"""
p = self.ipv4_params
self.config_network(p)
self.config_sa_tra(p)
self.config_protect(p)
- tx = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4,
- dst=p.remote_tun_if_host)
+ tx = self.gen_pkts(self.pg1, src=self.pg1.remote_ip4, dst=p.remote_tun_if_host)
self.send_and_assert_no_replies(self.pg1, tx)
self.unconfig_protect(p)
@@ -907,10 +1050,8 @@ class TestIpsec4TunIfEspNoAlgo(TemplateIpsec4TunProtect,
@tag_fixme_vpp_workers
-class TestIpsec6MultiTunIfEsp(TemplateIpsec6TunProtect,
- TemplateIpsec,
- IpsecTun6):
- """ IPsec IPv6 Multi Tunnel interface """
+class TestIpsec6MultiTunIfEsp(TemplateIpsec6TunProtect, TemplateIpsec, IpsecTun6):
+ """IPsec IPv6 Multi Tunnel interface"""
encryption_type = ESP
tun6_encrypt_node_name = "esp6-encrypt-tun"
@@ -949,40 +1090,43 @@ class TestIpsec6MultiTunIfEsp(TemplateIpsec6TunProtect,
super(TestIpsec6MultiTunIfEsp, self).tearDown()
def test_tun_66(self):
- """Multiple IPSEC tunnel interfaces """
+ """Multiple IPSEC tunnel interfaces"""
for p in self.multi_params:
self.verify_tun_66(p, count=127)
self.assertEqual(p.tun_if.get_rx_stats(), 127)
self.assertEqual(p.tun_if.get_tx_stats(), 127)
-class TestIpsecGreTebIfEsp(TemplateIpsec,
- IpsecTun4Tests):
- """ Ipsec GRE TEB ESP - TUN tests """
+class TestIpsecGreTebIfEsp(TemplateIpsec, IpsecTun4Tests):
+ """Ipsec GRE TEB ESP - TUN tests"""
+
tun4_encrypt_node_name = "esp4-encrypt-tun"
tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"]
encryption_type = ESP
omac = "00:11:22:33:44:55"
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=self.pg0.remote_ip4,
- dst=self.pg0.local_ip4) /
- GRE() /
- Ether(dst=self.omac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts(self, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(dst=self.omac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / GRE()
+ / Ether(dst=self.omac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(dst=self.omac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted(self, p, rxs):
for rx in rxs:
@@ -1020,33 +1164,43 @@ class TestIpsecGreTebIfEsp(TemplateIpsec,
bd1 = VppBridgeDomain(self, 1)
bd1.add_vpp_config()
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- self.pg0.remote_ip4,
- self.pg0.local_ip4)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ self.pg0.remote_ip4,
+ self.pg0.local_ip4,
+ )
p.tun_sa_in.add_vpp_config()
- p.tun_if = VppGreInterface(self,
- self.pg0.local_ip4,
- self.pg0.remote_ip4,
- type=(VppEnum.vl_api_gre_tunnel_type_t.
- GRE_API_TUNNEL_TYPE_TEB))
+ p.tun_if = VppGreInterface(
+ self,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB),
+ )
p.tun_if.add_vpp_config()
- p.tun_protect = VppIpsecTunProtect(self,
- p.tun_if,
- p.tun_sa_out,
- [p.tun_sa_in])
+ p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in])
p.tun_protect.add_vpp_config()
@@ -1067,34 +1221,37 @@ class TestIpsecGreTebIfEsp(TemplateIpsec,
super(TestIpsecGreTebIfEsp, self).tearDown()
-class TestIpsecGreTebVlanIfEsp(TemplateIpsec,
- IpsecTun4Tests):
- """ Ipsec GRE TEB ESP - TUN tests """
+class TestIpsecGreTebVlanIfEsp(TemplateIpsec, IpsecTun4Tests):
+ """Ipsec GRE TEB ESP - TUN tests"""
+
tun4_encrypt_node_name = "esp4-encrypt-tun"
tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"]
encryption_type = ESP
omac = "00:11:22:33:44:55"
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=self.pg0.remote_ip4,
- dst=self.pg0.local_ip4) /
- GRE() /
- Ether(dst=self.omac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts(self, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(dst=self.omac) /
- Dot1Q(vlan=11) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / GRE()
+ / Ether(dst=self.omac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(dst=self.omac)
+ / Dot1Q(vlan=11)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted(self, p, rxs):
for rx in rxs:
@@ -1136,37 +1293,49 @@ class TestIpsecGreTebVlanIfEsp(TemplateIpsec,
self.pg1_11 = VppDot1QSubint(self, self.pg1, 11)
self.vapi.l2_interface_vlan_tag_rewrite(
- sw_if_index=self.pg1_11.sw_if_index, vtr_op=L2_VTR_OP.L2_POP_1,
- push_dot1q=11)
+ sw_if_index=self.pg1_11.sw_if_index,
+ vtr_op=L2_VTR_OP.L2_POP_1,
+ push_dot1q=11,
+ )
self.pg1_11.admin_up()
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- self.pg0.remote_ip4,
- self.pg0.local_ip4)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ self.pg0.remote_ip4,
+ self.pg0.local_ip4,
+ )
p.tun_sa_in.add_vpp_config()
- p.tun_if = VppGreInterface(self,
- self.pg0.local_ip4,
- self.pg0.remote_ip4,
- type=(VppEnum.vl_api_gre_tunnel_type_t.
- GRE_API_TUNNEL_TYPE_TEB))
+ p.tun_if = VppGreInterface(
+ self,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB),
+ )
p.tun_if.add_vpp_config()
- p.tun_protect = VppIpsecTunProtect(self,
- p.tun_if,
- p.tun_sa_out,
- [p.tun_sa_in])
+ p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in])
p.tun_protect.add_vpp_config()
@@ -1187,33 +1356,36 @@ class TestIpsecGreTebVlanIfEsp(TemplateIpsec,
self.pg1_11.remove_vpp_config()
-class TestIpsecGreTebIfEspTra(TemplateIpsec,
- IpsecTun4Tests):
- """ Ipsec GRE TEB ESP - Tra tests """
+class TestIpsecGreTebIfEspTra(TemplateIpsec, IpsecTun4Tests):
+ """Ipsec GRE TEB ESP - Tra tests"""
+
tun4_encrypt_node_name = "esp4-encrypt-tun"
tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"]
encryption_type = ESP
omac = "00:11:22:33:44:55"
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=self.pg0.remote_ip4,
- dst=self.pg0.local_ip4) /
- GRE() /
- Ether(dst=self.omac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts(self, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(dst=self.omac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / GRE()
+ / Ether(dst=self.omac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(dst=self.omac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted(self, p, rxs):
for rx in rxs:
@@ -1251,29 +1423,39 @@ class TestIpsecGreTebIfEspTra(TemplateIpsec,
bd1 = VppBridgeDomain(self, 1)
bd1.add_vpp_config()
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_in.add_vpp_config()
- p.tun_if = VppGreInterface(self,
- self.pg0.local_ip4,
- self.pg0.remote_ip4,
- type=(VppEnum.vl_api_gre_tunnel_type_t.
- GRE_API_TUNNEL_TYPE_TEB))
+ p.tun_if = VppGreInterface(
+ self,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB),
+ )
p.tun_if.add_vpp_config()
- p.tun_protect = VppIpsecTunProtect(self,
- p.tun_if,
- p.tun_sa_out,
- [p.tun_sa_in])
+ p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in])
p.tun_protect.add_vpp_config()
@@ -1292,33 +1474,36 @@ class TestIpsecGreTebIfEspTra(TemplateIpsec,
super(TestIpsecGreTebIfEspTra, self).tearDown()
-class TestIpsecGreTebUdpIfEspTra(TemplateIpsec,
- IpsecTun4Tests):
- """ Ipsec GRE TEB UDP ESP - Tra tests """
+class TestIpsecGreTebUdpIfEspTra(TemplateIpsec, IpsecTun4Tests):
+ """Ipsec GRE TEB UDP ESP - Tra tests"""
+
tun4_encrypt_node_name = "esp4-encrypt-tun"
tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"]
encryption_type = ESP
omac = "00:11:22:33:44:55"
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=self.pg0.remote_ip4,
- dst=self.pg0.local_ip4) /
- GRE() /
- Ether(dst=self.omac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts(self, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(dst=self.omac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / GRE()
+ / Ether(dst=self.omac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(dst=self.omac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted(self, p, rxs):
for rx in rxs:
@@ -1356,44 +1541,53 @@ class TestIpsecGreTebUdpIfEspTra(TemplateIpsec,
p = self.ipv4_params
p = self.ipv4_params
- p.flags = (VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_UDP_ENCAP)
+ p.flags = VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_UDP_ENCAP
p.nat_header = UDP(sport=5454, dport=4545)
bd1 = VppBridgeDomain(self, 1)
bd1.add_vpp_config()
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- flags=p.flags,
- udp_src=5454,
- udp_dst=4545)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ flags=p.flags,
+ udp_src=5454,
+ udp_dst=4545,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- flags=(p.flags |
- VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_IS_INBOUND),
- udp_src=4545,
- udp_dst=5454)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ flags=(
+ p.flags | VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_IS_INBOUND
+ ),
+ udp_src=4545,
+ udp_dst=5454,
+ )
p.tun_sa_in.add_vpp_config()
- p.tun_if = VppGreInterface(self,
- self.pg0.local_ip4,
- self.pg0.remote_ip4,
- type=(VppEnum.vl_api_gre_tunnel_type_t.
- GRE_API_TUNNEL_TYPE_TEB))
+ p.tun_if = VppGreInterface(
+ self,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB),
+ )
p.tun_if.add_vpp_config()
- p.tun_protect = VppIpsecTunProtect(self,
- p.tun_if,
- p.tun_sa_out,
- [p.tun_sa_in])
+ p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in])
p.tun_protect.add_vpp_config()
@@ -1413,32 +1607,34 @@ class TestIpsecGreTebUdpIfEspTra(TemplateIpsec,
super(TestIpsecGreTebUdpIfEspTra, self).tearDown()
-class TestIpsecGreIfEsp(TemplateIpsec,
- IpsecTun4Tests):
- """ Ipsec GRE ESP - TUN tests """
+class TestIpsecGreIfEsp(TemplateIpsec, IpsecTun4Tests):
+ """Ipsec GRE ESP - TUN tests"""
+
tun4_encrypt_node_name = "esp4-encrypt-tun"
tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"]
encryption_type = ESP
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=self.pg0.remote_ip4,
- dst=self.pg0.local_ip4) /
- GRE() /
- IP(src=self.pg1.local_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts(self, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / GRE()
+ / IP(src=self.pg1.local_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted(self, p, rxs):
for rx in rxs:
@@ -1475,40 +1671,47 @@ class TestIpsecGreIfEsp(TemplateIpsec,
bd1 = VppBridgeDomain(self, 1)
bd1.add_vpp_config()
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- self.pg0.remote_ip4,
- self.pg0.local_ip4)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ self.pg0.remote_ip4,
+ self.pg0.local_ip4,
+ )
p.tun_sa_in.add_vpp_config()
- p.tun_if = VppGreInterface(self,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ p.tun_if = VppGreInterface(self, self.pg0.local_ip4, self.pg0.remote_ip4)
p.tun_if.add_vpp_config()
- p.tun_protect = VppIpsecTunProtect(self,
- p.tun_if,
- p.tun_sa_out,
- [p.tun_sa_in])
+ p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in])
p.tun_protect.add_vpp_config()
p.tun_if.admin_up()
p.tun_if.config_ip4()
config_tun_params(p, self.encryption_type, p.tun_if)
- VppIpRoute(self, "1.1.1.2", 32,
- [VppRoutePath(p.tun_if.remote_ip4,
- 0xffffffff)]).add_vpp_config()
+ VppIpRoute(
+ self, "1.1.1.2", 32, [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)]
+ ).add_vpp_config()
def tearDown(self):
p = self.ipv4_params
@@ -1516,42 +1719,46 @@ class TestIpsecGreIfEsp(TemplateIpsec,
super(TestIpsecGreIfEsp, self).tearDown()
-class TestIpsecGreIfEspTra(TemplateIpsec,
- IpsecTun4Tests):
- """ Ipsec GRE ESP - TRA tests """
+class TestIpsecGreIfEspTra(TemplateIpsec, IpsecTun4Tests):
+ """Ipsec GRE ESP - TRA tests"""
+
tun4_encrypt_node_name = "esp4-encrypt-tun"
tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"]
encryption_type = ESP
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=self.pg0.remote_ip4,
- dst=self.pg0.local_ip4) /
- GRE() /
- IP(src=self.pg1.local_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_encrypt_non_ip_pkts(self, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=self.pg0.remote_ip4,
- dst=self.pg0.local_ip4) /
- GRE() /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts(self, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / GRE()
+ / IP(src=self.pg1.local_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_encrypt_non_ip_pkts(self, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / GRE()
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted(self, p, rxs):
for rx in rxs:
@@ -1583,36 +1790,43 @@ class TestIpsecGreIfEspTra(TemplateIpsec,
p = self.ipv4_params
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_in.add_vpp_config()
- p.tun_if = VppGreInterface(self,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ p.tun_if = VppGreInterface(self, self.pg0.local_ip4, self.pg0.remote_ip4)
p.tun_if.add_vpp_config()
- p.tun_protect = VppIpsecTunProtect(self,
- p.tun_if,
- p.tun_sa_out,
- [p.tun_sa_in])
+ p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in])
p.tun_protect.add_vpp_config()
p.tun_if.admin_up()
p.tun_if.config_ip4()
config_tra_params(p, self.encryption_type, p.tun_if)
- VppIpRoute(self, "1.1.1.2", 32,
- [VppRoutePath(p.tun_if.remote_ip4,
- 0xffffffff)]).add_vpp_config()
+ VppIpRoute(
+ self, "1.1.1.2", 32, [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)]
+ ).add_vpp_config()
def tearDown(self):
p = self.ipv4_params
@@ -1621,41 +1835,45 @@ class TestIpsecGreIfEspTra(TemplateIpsec,
def test_gre_non_ip(self):
p = self.ipv4_params
- tx = self.gen_encrypt_non_ip_pkts(p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip6)
+ tx = self.gen_encrypt_non_ip_pkts(
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip6,
+ )
self.send_and_assert_no_replies(self.tun_if, tx)
- node_name = ('/err/%s/unsupported payload' %
- self.tun4_decrypt_node_name[0])
+ node_name = "/err/%s/unsupported payload" % self.tun4_decrypt_node_name[0]
self.assertEqual(1, self.statistics.get_err_counter(node_name))
-class TestIpsecGre6IfEspTra(TemplateIpsec,
- IpsecTun6Tests):
- """ Ipsec GRE ESP - TRA tests """
+class TestIpsecGre6IfEspTra(TemplateIpsec, IpsecTun6Tests):
+ """Ipsec GRE ESP - TRA tests"""
+
tun6_encrypt_node_name = "esp6-encrypt-tun"
tun6_decrypt_node_name = ["esp6-decrypt-tun", "esp6-decrypt-tun-post"]
encryption_type = ESP
- def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IPv6(src=self.pg0.remote_ip6,
- dst=self.pg0.local_ip6) /
- GRE() /
- IPv6(src=self.pg1.local_ip6,
- dst=self.pg1.remote_ip6) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts6(self, p, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IPv6(src="1::1", dst="1::2") /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / GRE()
+ / IPv6(src=self.pg1.local_ip6, dst=self.pg1.remote_ip6)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IPv6(src="1::1", dst="1::2")
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted6(self, p, rxs):
for rx in rxs:
@@ -1690,37 +1908,50 @@ class TestIpsecGre6IfEspTra(TemplateIpsec,
bd1 = VppBridgeDomain(self, 1)
bd1.add_vpp_config()
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_in.add_vpp_config()
- p.tun_if = VppGreInterface(self,
- self.pg0.local_ip6,
- self.pg0.remote_ip6)
+ p.tun_if = VppGreInterface(self, self.pg0.local_ip6, self.pg0.remote_ip6)
p.tun_if.add_vpp_config()
- p.tun_protect = VppIpsecTunProtect(self,
- p.tun_if,
- p.tun_sa_out,
- [p.tun_sa_in])
+ p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in])
p.tun_protect.add_vpp_config()
p.tun_if.admin_up()
p.tun_if.config_ip6()
config_tra_params(p, self.encryption_type, p.tun_if)
- r = VppIpRoute(self, "1::2", 128,
- [VppRoutePath(p.tun_if.remote_ip6,
- 0xffffffff,
- proto=DpoProto.DPO_PROTO_IP6)])
+ r = VppIpRoute(
+ self,
+ "1::2",
+ 128,
+ [
+ VppRoutePath(
+ p.tun_if.remote_ip6, 0xFFFFFFFF, proto=DpoProto.DPO_PROTO_IP6
+ )
+ ],
+ )
r.add_vpp_config()
def tearDown(self):
@@ -1730,30 +1961,33 @@ class TestIpsecGre6IfEspTra(TemplateIpsec,
class TestIpsecMGreIfEspTra4(TemplateIpsec, IpsecTun4):
- """ Ipsec mGRE ESP v4 TRA tests """
+ """Ipsec mGRE ESP v4 TRA tests"""
+
tun4_encrypt_node_name = "esp4-encrypt-tun"
tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"]
encryption_type = ESP
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=p.tun_dst,
- dst=self.pg0.local_ip4) /
- GRE() /
- IP(src=self.pg1.local_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts(self, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IP(src="1.1.1.1", dst=dst) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=p.tun_dst, dst=self.pg0.local_ip4)
+ / GRE()
+ / IP(src=self.pg1.local_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IP(src="1.1.1.1", dst=dst)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted(self, p, rxs):
for rx in rxs:
@@ -1784,11 +2018,12 @@ class TestIpsecMGreIfEspTra4(TemplateIpsec, IpsecTun4):
N_NHS = 16
self.tun_if = self.pg0
p = self.ipv4_params
- p.tun_if = VppGreInterface(self,
- self.pg0.local_ip4,
- "0.0.0.0",
- mode=(VppEnum.vl_api_tunnel_mode_t.
- TUNNEL_API_MODE_MP))
+ p.tun_if = VppGreInterface(
+ self,
+ self.pg0.local_ip4,
+ "0.0.0.0",
+ mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP),
+ )
p.tun_if.add_vpp_config()
p.tun_if.admin_up()
p.tun_if.config_ip4()
@@ -1812,16 +2047,28 @@ class TestIpsecMGreIfEspTra4(TemplateIpsec, IpsecTun4):
p.scapy_tra_spi = p.scapy_tra_spi + ii
p.vpp_tra_sa_id = p.vpp_tra_sa_id + ii
p.vpp_tra_spi = p.vpp_tra_spi + ii
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_in.add_vpp_config()
p.tun_protect = VppIpsecTunProtect(
@@ -1829,19 +2076,26 @@ class TestIpsecMGreIfEspTra4(TemplateIpsec, IpsecTun4):
p.tun_if,
p.tun_sa_out,
[p.tun_sa_in],
- nh=p.tun_if.remote_hosts[ii].ip4)
+ nh=p.tun_if.remote_hosts[ii].ip4,
+ )
p.tun_protect.add_vpp_config()
config_tra_params(p, self.encryption_type, p.tun_if)
self.multi_params.append(p)
- VppIpRoute(self, p.remote_tun_if_host, 32,
- [VppRoutePath(p.tun_if.remote_hosts[ii].ip4,
- p.tun_if.sw_if_index)]).add_vpp_config()
+ VppIpRoute(
+ self,
+ p.remote_tun_if_host,
+ 32,
+ [VppRoutePath(p.tun_if.remote_hosts[ii].ip4, p.tun_if.sw_if_index)],
+ ).add_vpp_config()
# in this v4 variant add the teibs after the protect
- p.teib = VppTeib(self, p.tun_if,
- p.tun_if.remote_hosts[ii].ip4,
- self.pg0.remote_hosts[ii].ip4).add_vpp_config()
+ p.teib = VppTeib(
+ self,
+ p.tun_if,
+ p.tun_if.remote_hosts[ii].ip4,
+ self.pg0.remote_hosts[ii].ip4,
+ ).add_vpp_config()
p.tun_dst = self.pg0.remote_hosts[ii].ip4
self.logger.info(self.vapi.cli("sh ipsec protect-hash"))
@@ -1862,30 +2116,33 @@ class TestIpsecMGreIfEspTra4(TemplateIpsec, IpsecTun4):
class TestIpsecMGreIfEspTra6(TemplateIpsec, IpsecTun6):
- """ Ipsec mGRE ESP v6 TRA tests """
+ """Ipsec mGRE ESP v6 TRA tests"""
+
tun6_encrypt_node_name = "esp6-encrypt-tun"
tun6_decrypt_node_name = ["esp6-decrypt-tun", "esp6-decrypt-tun-post"]
encryption_type = ESP
- def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IPv6(src=p.tun_dst,
- dst=self.pg0.local_ip6) /
- GRE() /
- IPv6(src=self.pg1.local_ip6,
- dst=self.pg1.remote_ip6) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts6(self, p, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IPv6(src="1::1", dst=dst) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IPv6(src=p.tun_dst, dst=self.pg0.local_ip6)
+ / GRE()
+ / IPv6(src=self.pg1.local_ip6, dst=self.pg1.remote_ip6)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IPv6(src="1::1", dst=dst)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted6(self, p, rxs):
for rx in rxs:
@@ -1918,11 +2175,12 @@ class TestIpsecMGreIfEspTra6(TemplateIpsec, IpsecTun6):
N_NHS = 16
self.tun_if = self.pg0
p = self.ipv6_params
- p.tun_if = VppGreInterface(self,
- self.pg0.local_ip6,
- "::",
- mode=(VppEnum.vl_api_tunnel_mode_t.
- TUNNEL_API_MODE_MP))
+ p.tun_if = VppGreInterface(
+ self,
+ self.pg0.local_ip6,
+ "::",
+ mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP),
+ )
p.tun_if.add_vpp_config()
p.tun_if.admin_up()
p.tun_if.config_ip6()
@@ -1946,37 +2204,53 @@ class TestIpsecMGreIfEspTra6(TemplateIpsec, IpsecTun6):
p.scapy_tra_spi = p.scapy_tra_spi + ii
p.vpp_tra_sa_id = p.vpp_tra_sa_id + ii
p.vpp_tra_spi = p.vpp_tra_spi + ii
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ )
p.tun_sa_in.add_vpp_config()
# in this v6 variant add the teibs first then the protection
p.tun_dst = self.pg0.remote_hosts[ii].ip6
- VppTeib(self, p.tun_if,
- p.tun_if.remote_hosts[ii].ip6,
- p.tun_dst).add_vpp_config()
+ VppTeib(
+ self, p.tun_if, p.tun_if.remote_hosts[ii].ip6, p.tun_dst
+ ).add_vpp_config()
p.tun_protect = VppIpsecTunProtect(
self,
p.tun_if,
p.tun_sa_out,
[p.tun_sa_in],
- nh=p.tun_if.remote_hosts[ii].ip6)
+ nh=p.tun_if.remote_hosts[ii].ip6,
+ )
p.tun_protect.add_vpp_config()
config_tra_params(p, self.encryption_type, p.tun_if)
self.multi_params.append(p)
- VppIpRoute(self, p.remote_tun_if_host, 128,
- [VppRoutePath(p.tun_if.remote_hosts[ii].ip6,
- p.tun_if.sw_if_index)]).add_vpp_config()
+ VppIpRoute(
+ self,
+ p.remote_tun_if_host,
+ 128,
+ [VppRoutePath(p.tun_if.remote_hosts[ii].ip6, p.tun_if.sw_if_index)],
+ ).add_vpp_config()
p.tun_dst = self.pg0.remote_hosts[ii].ip6
self.logger.info(self.vapi.cli("sh log"))
@@ -1995,10 +2269,8 @@ class TestIpsecMGreIfEspTra6(TemplateIpsec, IpsecTun6):
@tag_fixme_vpp_workers
-class TestIpsec4TunProtect(TemplateIpsec,
- TemplateIpsec4TunProtect,
- IpsecTun4):
- """ IPsec IPv4 Tunnel protect - transport mode"""
+class TestIpsec4TunProtect(TemplateIpsec, TemplateIpsec4TunProtect, IpsecTun4):
+ """IPsec IPv4 Tunnel protect - transport mode"""
def setUp(self):
super(TestIpsec4TunProtect, self).setUp()
@@ -2028,7 +2300,7 @@ class TestIpsec4TunProtect(TemplateIpsec,
# rekey - create new SAs and update the tunnel protection
np = copy.copy(p)
- np.crypt_key = b'X' + p.crypt_key[1:]
+ np.crypt_key = b"X" + p.crypt_key[1:]
np.scapy_tun_spi += 100
np.scapy_tun_sa_id += 1
np.vpp_tun_spi += 100
@@ -2051,10 +2323,8 @@ class TestIpsec4TunProtect(TemplateIpsec,
@tag_fixme_vpp_workers
-class TestIpsec4TunProtectUdp(TemplateIpsec,
- TemplateIpsec4TunProtect,
- IpsecTun4):
- """ IPsec IPv4 Tunnel protect - transport mode"""
+class TestIpsec4TunProtectUdp(TemplateIpsec, TemplateIpsec4TunProtect, IpsecTun4):
+ """IPsec IPv4 Tunnel protect - transport mode"""
def setUp(self):
super(TestIpsec4TunProtectUdp, self).setUp()
@@ -2062,8 +2332,7 @@ class TestIpsec4TunProtectUdp(TemplateIpsec,
self.tun_if = self.pg0
p = self.ipv4_params
- p.flags = (VppEnum.vl_api_ipsec_sad_flags_t.
- IPSEC_API_SAD_FLAG_UDP_ENCAP)
+ p.flags = VppEnum.vl_api_ipsec_sad_flags_t.IPSEC_API_SAD_FLAG_UDP_ENCAP
p.nat_header = UDP(sport=4500, dport=4500)
self.config_network(p)
self.config_sa_tra(p)
@@ -2093,15 +2362,13 @@ class TestIpsec4TunProtectUdp(TemplateIpsec,
self.assertEqual(p.tun_if.get_tx_stats(), 127)
def test_keepalive(self):
- """ IPSEC NAT Keepalive """
+ """IPSEC NAT Keepalive"""
self.verify_keepalive(self.ipv4_params)
@tag_fixme_vpp_workers
-class TestIpsec4TunProtectTun(TemplateIpsec,
- TemplateIpsec4TunProtect,
- IpsecTun4):
- """ IPsec IPv4 Tunnel protect - tunnel mode"""
+class TestIpsec4TunProtectTun(TemplateIpsec, TemplateIpsec4TunProtect, IpsecTun4):
+ """IPsec IPv4 Tunnel protect - tunnel mode"""
encryption_type = ESP
tun4_encrypt_node_name = "esp4-encrypt-tun"
@@ -2115,23 +2382,26 @@ class TestIpsec4TunProtectTun(TemplateIpsec,
def tearDown(self):
super(TestIpsec4TunProtectTun, self).tearDown()
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=sw_intf.remote_ip4,
- dst=sw_intf.local_ip4) /
- IP(src=src, dst=dst) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts(self, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IP(src=src, dst=dst) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=sw_intf.remote_ip4, dst=sw_intf.local_ip4)
+ / IP(src=src, dst=dst)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IP(src=src, dst=dst)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted(self, p, rxs):
for rx in rxs:
@@ -2160,7 +2430,7 @@ class TestIpsec4TunProtectTun(TemplateIpsec,
raise
def test_tun_44(self):
- """IPSEC tunnel protect """
+ """IPSEC tunnel protect"""
p = self.ipv4_params
@@ -2170,10 +2440,7 @@ class TestIpsec4TunProtectTun(TemplateIpsec,
# also add an output features on the tunnel and physical interface
# so we test they still work
- r_all = AclRule(True,
- src_prefix="0.0.0.0/0",
- dst_prefix="0.0.0.0/0",
- proto=0)
+ r_all = AclRule(True, src_prefix="0.0.0.0/0", dst_prefix="0.0.0.0/0", proto=0)
a = VppAcl(self, [r_all]).add_vpp_config()
VppAclInterface(self, self.pg0.sw_if_index, [a]).add_vpp_config()
@@ -2186,7 +2453,7 @@ class TestIpsec4TunProtectTun(TemplateIpsec,
# rekey - create new SAs and update the tunnel protection
np = copy.copy(p)
- np.crypt_key = b'X' + p.crypt_key[1:]
+ np.crypt_key = b"X" + p.crypt_key[1:]
np.scapy_tun_spi += 100
np.scapy_tun_sa_id += 1
np.vpp_tun_spi += 100
@@ -2208,10 +2475,8 @@ class TestIpsec4TunProtectTun(TemplateIpsec,
self.unconfig_network(p)
-class TestIpsec4TunProtectTunDrop(TemplateIpsec,
- TemplateIpsec4TunProtect,
- IpsecTun4):
- """ IPsec IPv4 Tunnel protect - tunnel mode - drop"""
+class TestIpsec4TunProtectTunDrop(TemplateIpsec, TemplateIpsec4TunProtect, IpsecTun4):
+ """IPsec IPv4 Tunnel protect - tunnel mode - drop"""
encryption_type = ESP
tun4_encrypt_node_name = "esp4-encrypt-tun"
@@ -2225,18 +2490,20 @@ class TestIpsec4TunProtectTunDrop(TemplateIpsec,
def tearDown(self):
super(TestIpsec4TunProtectTunDrop, self).tearDown()
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=sw_intf.remote_ip4,
- dst="5.5.5.5") /
- IP(src=src, dst=dst) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=sw_intf.remote_ip4, dst="5.5.5.5")
+ / IP(src=src, dst=dst)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
def test_tun_drop_44(self):
- """IPSEC tunnel protect bogus tunnel header """
+ """IPSEC tunnel protect bogus tunnel header"""
p = self.ipv4_params
@@ -2244,10 +2511,14 @@ class TestIpsec4TunProtectTunDrop(TemplateIpsec,
self.config_sa_tun(p)
self.config_protect(p)
- tx = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip4,
- count=63)
+ tx = self.gen_encrypt_pkts(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip4,
+ count=63,
+ )
self.send_and_assert_no_replies(self.tun_if, tx)
# teardown
@@ -2257,10 +2528,8 @@ class TestIpsec4TunProtectTunDrop(TemplateIpsec,
@tag_fixme_vpp_workers
-class TestIpsec6TunProtect(TemplateIpsec,
- TemplateIpsec6TunProtect,
- IpsecTun6):
- """ IPsec IPv6 Tunnel protect - transport mode"""
+class TestIpsec6TunProtect(TemplateIpsec, TemplateIpsec6TunProtect, IpsecTun6):
+ """IPsec IPv6 Tunnel protect - transport mode"""
encryption_type = ESP
tun6_encrypt_node_name = "esp6-encrypt-tun"
@@ -2289,7 +2558,7 @@ class TestIpsec6TunProtect(TemplateIpsec,
# rekey - create new SAs and update the tunnel protection
np = copy.copy(p)
- np.crypt_key = b'X' + p.crypt_key[1:]
+ np.crypt_key = b"X" + p.crypt_key[1:]
np.scapy_tun_spi += 100
np.scapy_tun_sa_id += 1
np.vpp_tun_spi += 100
@@ -2308,8 +2577,9 @@ class TestIpsec6TunProtect(TemplateIpsec,
# bounce the interface state
p.tun_if.admin_down()
self.verify_drop_tun_66(np, count=127)
- node = ('/err/ipsec6-tun-input/%s' %
- 'ipsec packets received on disabled interface')
+ node = (
+ "/err/ipsec6-tun-input/%s" % "ipsec packets received on disabled interface"
+ )
self.assertEqual(127, self.statistics.get_err_counter(node))
p.tun_if.admin_up()
self.verify_tun_66(np, count=127)
@@ -2319,7 +2589,7 @@ class TestIpsec6TunProtect(TemplateIpsec,
# 2) swap output SA to [new]
# 3) use only [new] input SA
np3 = copy.copy(np)
- np3.crypt_key = b'Z' + p.crypt_key[1:]
+ np3.crypt_key = b"Z" + p.crypt_key[1:]
np3.scapy_tun_spi += 100
np3.scapy_tun_sa_id += 1
np3.vpp_tun_spi += 100
@@ -2330,25 +2600,22 @@ class TestIpsec6TunProtect(TemplateIpsec,
self.config_sa_tra(np3)
# step 1;
- p.tun_protect.update_vpp_config(np.tun_sa_out,
- [np.tun_sa_in, np3.tun_sa_in])
+ p.tun_protect.update_vpp_config(np.tun_sa_out, [np.tun_sa_in, np3.tun_sa_in])
self.verify_tun_66(np, np, count=127)
self.verify_tun_66(np3, np, count=127)
# step 2;
- p.tun_protect.update_vpp_config(np3.tun_sa_out,
- [np.tun_sa_in, np3.tun_sa_in])
+ p.tun_protect.update_vpp_config(np3.tun_sa_out, [np.tun_sa_in, np3.tun_sa_in])
self.verify_tun_66(np, np3, count=127)
self.verify_tun_66(np3, np3, count=127)
# step 1;
- p.tun_protect.update_vpp_config(np3.tun_sa_out,
- [np3.tun_sa_in])
+ p.tun_protect.update_vpp_config(np3.tun_sa_out, [np3.tun_sa_in])
self.verify_tun_66(np3, np3, count=127)
self.verify_drop_tun_rx_66(np, count=127)
- self.assertEqual(p.tun_if.get_rx_stats(), 127*9)
- self.assertEqual(p.tun_if.get_tx_stats(), 127*8)
+ self.assertEqual(p.tun_if.get_rx_stats(), 127 * 9)
+ self.assertEqual(p.tun_if.get_tx_stats(), 127 * 8)
self.unconfig_sa(np)
# teardown
@@ -2376,10 +2643,8 @@ class TestIpsec6TunProtect(TemplateIpsec,
@tag_fixme_vpp_workers
-class TestIpsec6TunProtectTun(TemplateIpsec,
- TemplateIpsec6TunProtect,
- IpsecTun6):
- """ IPsec IPv6 Tunnel protect - tunnel mode"""
+class TestIpsec6TunProtectTun(TemplateIpsec, TemplateIpsec6TunProtect, IpsecTun6):
+ """IPsec IPv6 Tunnel protect - tunnel mode"""
encryption_type = ESP
tun6_encrypt_node_name = "esp6-encrypt-tun"
@@ -2393,23 +2658,26 @@ class TestIpsec6TunProtectTun(TemplateIpsec,
def tearDown(self):
super(TestIpsec6TunProtectTun, self).tearDown()
- def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IPv6(src=sw_intf.remote_ip6,
- dst=sw_intf.local_ip6) /
- IPv6(src=src, dst=dst) /
- UDP(sport=1166, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts6(self, p, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IPv6(src=src, dst=dst) /
- UDP(sport=1166, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IPv6(src=sw_intf.remote_ip6, dst=sw_intf.local_ip6)
+ / IPv6(src=src, dst=dst)
+ / UDP(sport=1166, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts6(self, p, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IPv6(src=src, dst=dst)
+ / UDP(sport=1166, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted6(self, p, rxs):
for rx in rxs:
@@ -2438,7 +2706,7 @@ class TestIpsec6TunProtectTun(TemplateIpsec,
raise
def test_tun_66(self):
- """IPSEC tunnel protect """
+ """IPSEC tunnel protect"""
p = self.ipv6_params
@@ -2453,7 +2721,7 @@ class TestIpsec6TunProtectTun(TemplateIpsec,
# rekey - create new SAs and update the tunnel protection
np = copy.copy(p)
- np.crypt_key = b'X' + p.crypt_key[1:]
+ np.crypt_key = b"X" + p.crypt_key[1:]
np.scapy_tun_spi += 100
np.scapy_tun_sa_id += 1
np.vpp_tun_spi += 100
@@ -2475,10 +2743,8 @@ class TestIpsec6TunProtectTun(TemplateIpsec,
self.unconfig_network(p)
-class TestIpsec6TunProtectTunDrop(TemplateIpsec,
- TemplateIpsec6TunProtect,
- IpsecTun6):
- """ IPsec IPv6 Tunnel protect - tunnel mode - drop"""
+class TestIpsec6TunProtectTunDrop(TemplateIpsec, TemplateIpsec6TunProtect, IpsecTun6):
+ """IPsec IPv6 Tunnel protect - tunnel mode - drop"""
encryption_type = ESP
tun6_encrypt_node_name = "esp6-encrypt-tun"
@@ -2492,20 +2758,22 @@ class TestIpsec6TunProtectTunDrop(TemplateIpsec,
def tearDown(self):
super(TestIpsec6TunProtectTunDrop, self).tearDown()
- def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
+ def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
# the IP destination of the revelaed packet does not match
# that assigned to the tunnel
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IPv6(src=sw_intf.remote_ip6,
- dst="5::5") /
- IPv6(src=src, dst=dst) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IPv6(src=sw_intf.remote_ip6, dst="5::5")
+ / IPv6(src=src, dst=dst)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
def test_tun_drop_66(self):
- """IPSEC 6 tunnel protect bogus tunnel header """
+ """IPSEC 6 tunnel protect bogus tunnel header"""
p = self.ipv6_params
@@ -2513,10 +2781,14 @@ class TestIpsec6TunProtectTunDrop(TemplateIpsec,
self.config_sa_tun(p)
self.config_protect(p)
- tx = self.gen_encrypt_pkts6(p, p.scapy_tun_sa, self.tun_if,
- src=p.remote_tun_if_host,
- dst=self.pg1.remote_ip6,
- count=63)
+ tx = self.gen_encrypt_pkts6(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.remote_tun_if_host,
+ dst=self.pg1.remote_ip6,
+ count=63,
+ )
self.send_and_assert_no_replies(self.tun_if, tx)
self.unconfig_protect(p)
@@ -2525,7 +2797,7 @@ class TestIpsec6TunProtectTunDrop(TemplateIpsec,
class TemplateIpsecItf4(object):
- """ IPsec Interface IPv4 """
+ """IPsec Interface IPv4"""
encryption_type = ESP
tun4_encrypt_node_name = "esp4-encrypt-tun"
@@ -2535,30 +2807,41 @@ class TemplateIpsecItf4(object):
def config_sa_tun(self, p, src, dst):
config_tun_params(p, self.encryption_type, None, src, dst)
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- src, dst,
- flags=p.flags)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ src,
+ dst,
+ flags=p.flags,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- dst, src,
- flags=p.flags)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ dst,
+ src,
+ flags=p.flags,
+ )
p.tun_sa_in.add_vpp_config()
def config_protect(self, p):
- p.tun_protect = VppIpsecTunProtect(self,
- p.tun_if,
- p.tun_sa_out,
- [p.tun_sa_in])
+ p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in])
p.tun_protect.add_vpp_config()
- def config_network(self, p, instance=0xffffffff):
+ def config_network(self, p, instance=0xFFFFFFFF):
p.tun_if = VppIpsecInterface(self, instance=instance)
p.tun_if.add_vpp_config()
@@ -2566,14 +2849,23 @@ class TemplateIpsecItf4(object):
p.tun_if.config_ip4()
p.tun_if.config_ip6()
- p.route = VppIpRoute(self, p.remote_tun_if_host, 32,
- [VppRoutePath(p.tun_if.remote_ip4,
- 0xffffffff)])
+ p.route = VppIpRoute(
+ self,
+ p.remote_tun_if_host,
+ 32,
+ [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)],
+ )
p.route.add_vpp_config()
- r = VppIpRoute(self, p.remote_tun_if_host6, 128,
- [VppRoutePath(p.tun_if.remote_ip6,
- 0xffffffff,
- proto=DpoProto.DPO_PROTO_IP6)])
+ r = VppIpRoute(
+ self,
+ p.remote_tun_if_host6,
+ 128,
+ [
+ VppRoutePath(
+ p.tun_if.remote_ip6, 0xFFFFFFFF, proto=DpoProto.DPO_PROTO_IP6
+ )
+ ],
+ )
r.add_vpp_config()
def unconfig_network(self, p):
@@ -2589,10 +2881,8 @@ class TemplateIpsecItf4(object):
@tag_fixme_vpp_workers
-class TestIpsecItf4(TemplateIpsec,
- TemplateIpsecItf4,
- IpsecTun4):
- """ IPsec Interface IPv4 """
+class TestIpsecItf4(TemplateIpsec, TemplateIpsecItf4, IpsecTun4):
+ """IPsec Interface IPv4"""
def setUp(self):
super(TestIpsecItf4, self).setUp()
@@ -2621,13 +2911,11 @@ class TestIpsecItf4(TemplateIpsec,
p = self.ipv4_params
self.config_network(p)
- config_tun_params(p, self.encryption_type, None,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ config_tun_params(
+ p, self.encryption_type, None, self.pg0.local_ip4, self.pg0.remote_ip4
+ )
self.verify_tun_dropped_44(p, count=n_pkts)
- self.config_sa_tun(p,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ self.config_sa_tun(p, self.pg0.local_ip4, self.pg0.remote_ip4)
self.config_protect(p)
self.verify_tun_44(p, count=n_pkts)
@@ -2639,15 +2927,15 @@ class TestIpsecItf4(TemplateIpsec,
p.tun_if.admin_up()
self.verify_tun_44(p, count=n_pkts)
- self.assertEqual(p.tun_if.get_rx_stats(), 3*n_pkts)
- self.assertEqual(p.tun_if.get_tx_stats(), 2*n_pkts)
+ self.assertEqual(p.tun_if.get_rx_stats(), 3 * n_pkts)
+ self.assertEqual(p.tun_if.get_tx_stats(), 2 * n_pkts)
# it's a v6 packet when its encrypted
self.tun4_encrypt_node_name = "esp6-encrypt-tun"
self.verify_tun_64(p, count=n_pkts)
- self.assertEqual(p.tun_if.get_rx_stats(), 4*n_pkts)
- self.assertEqual(p.tun_if.get_tx_stats(), 3*n_pkts)
+ self.assertEqual(p.tun_if.get_rx_stats(), 4 * n_pkts)
+ self.assertEqual(p.tun_if.get_tx_stats(), 3 * n_pkts)
self.tun4_encrypt_node_name = "esp4-encrypt-tun"
@@ -2655,7 +2943,7 @@ class TestIpsecItf4(TemplateIpsec,
# rekey - create new SAs and update the tunnel protection
np = copy.copy(p)
- np.crypt_key = b'X' + p.crypt_key[1:]
+ np.crypt_key = b"X" + p.crypt_key[1:]
np.scapy_tun_spi += 100
np.scapy_tun_sa_id += 1
np.vpp_tun_spi += 100
@@ -2663,9 +2951,7 @@ class TestIpsecItf4(TemplateIpsec,
np.tun_if.local_spi = p.vpp_tun_spi
np.tun_if.remote_spi = p.scapy_tun_spi
- self.config_sa_tun(np,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ self.config_sa_tun(np, self.pg0.local_ip4, self.pg0.remote_ip4)
self.config_protect(np)
self.unconfig_sa(p)
@@ -2684,17 +2970,15 @@ class TestIpsecItf4(TemplateIpsec,
n_pkts = 127
p = copy.copy(self.ipv4_params)
- p.auth_algo_vpp_id = (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_NONE)
- p.crypt_algo_vpp_id = (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_NONE)
+ p.auth_algo_vpp_id = VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_NONE
+ p.crypt_algo_vpp_id = (
+ VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_NONE
+ )
p.crypt_algo = "NULL"
p.auth_algo = "NULL"
self.config_network(p)
- self.config_sa_tun(p,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ self.config_sa_tun(p, self.pg0.local_ip4, self.pg0.remote_ip4)
self.config_protect(p)
self.logger.info(self.vapi.cli("sh ipsec sa"))
@@ -2711,18 +2995,23 @@ class TestIpsecItf4(TemplateIpsec,
p = self.ipv4_params
self.config_network(p)
- self.config_sa_tun(p,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ self.config_sa_tun(p, self.pg0.local_ip4, self.pg0.remote_ip4)
self.config_protect(p)
action_tx = PolicerAction(
- VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT,
- 0)
- policer = VppPolicer(self, "pol1", 80, 0, 1000, 0,
- conform_action=action_tx,
- exceed_action=action_tx,
- violate_action=action_tx)
+ VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0
+ )
+ policer = VppPolicer(
+ self,
+ "pol1",
+ 80,
+ 0,
+ 1000,
+ 0,
+ conform_action=action_tx,
+ exceed_action=action_tx,
+ violate_action=action_tx,
+ )
policer.add_vpp_config()
# Start policing on tun
@@ -2735,9 +3024,9 @@ class TestIpsecItf4(TemplateIpsec,
stats = policer.get_stats()
# Single rate, 2 colour policer - expect conform, violate but no exceed
- self.assertGreater(stats['conform_packets'], 0)
- self.assertEqual(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ self.assertGreater(stats["conform_packets"], 0)
+ self.assertEqual(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
# Stop policing on tun
policer.apply_vpp_config(p.tun_if.sw_if_index, Dir.RX, False)
@@ -2754,10 +3043,8 @@ class TestIpsecItf4(TemplateIpsec,
self.unconfig_network(p)
-class TestIpsecItf4MPLS(TemplateIpsec,
- TemplateIpsecItf4,
- IpsecTun4):
- """ IPsec Interface MPLSoIPv4 """
+class TestIpsecItf4MPLS(TemplateIpsec, TemplateIpsecItf4, IpsecTun4):
+ """IPsec Interface MPLSoIPv4"""
tun4_encrypt_node_name = "esp-mpls-encrypt-tun"
@@ -2769,14 +3056,17 @@ class TestIpsecItf4MPLS(TemplateIpsec,
def tearDown(self):
super(TestIpsecItf4MPLS, self).tearDown()
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(MPLS(label=44, ttl=3) /
- IP(src=src, dst=dst) /
- UDP(sport=1166, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ MPLS(label=44, ttl=3)
+ / IP(src=src, dst=dst)
+ / UDP(sport=1166, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
def verify_encrypted(self, p, sa, rxs):
for rx in rxs:
@@ -2807,18 +3097,19 @@ class TestIpsecItf4MPLS(TemplateIpsec,
self.config_network(p)
# deag MPLS routes from the tunnel
- r4 = VppMplsRoute(self, 44, 1,
- [VppRoutePath(
- self.pg1.remote_ip4,
- self.pg1.sw_if_index)]).add_vpp_config()
- p.route.modify([VppRoutePath(p.tun_if.remote_ip4,
- p.tun_if.sw_if_index,
- labels=[VppMplsLabel(44)])])
+ r4 = VppMplsRoute(
+ self, 44, 1, [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)]
+ ).add_vpp_config()
+ p.route.modify(
+ [
+ VppRoutePath(
+ p.tun_if.remote_ip4, p.tun_if.sw_if_index, labels=[VppMplsLabel(44)]
+ )
+ ]
+ )
p.tun_if.enable_mpls()
- self.config_sa_tun(p,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ self.config_sa_tun(p, self.pg0.local_ip4, self.pg0.remote_ip4)
self.config_protect(p)
self.verify_tun_44(p, count=n_pkts)
@@ -2831,7 +3122,7 @@ class TestIpsecItf4MPLS(TemplateIpsec,
class TemplateIpsecItf6(object):
- """ IPsec Interface IPv6 """
+ """IPsec Interface IPv6"""
encryption_type = ESP
tun6_encrypt_node_name = "esp6-encrypt-tun"
@@ -2841,34 +3132,45 @@ class TemplateIpsecItf6(object):
def config_sa_tun(self, p, src, dst):
config_tun_params(p, self.encryption_type, None, src, dst)
- if not hasattr(p, 'tun_flags'):
+ if not hasattr(p, "tun_flags"):
p.tun_flags = None
- if not hasattr(p, 'hop_limit'):
+ if not hasattr(p, "hop_limit"):
p.hop_limit = 255
- p.tun_sa_out = VppIpsecSA(self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- src, dst,
- flags=p.flags,
- tun_flags=p.tun_flags,
- hop_limit=p.hop_limit)
+ p.tun_sa_out = VppIpsecSA(
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ src,
+ dst,
+ flags=p.flags,
+ tun_flags=p.tun_flags,
+ hop_limit=p.hop_limit,
+ )
p.tun_sa_out.add_vpp_config()
- p.tun_sa_in = VppIpsecSA(self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
- self.vpp_esp_protocol,
- dst, src,
- flags=p.flags)
+ p.tun_sa_in = VppIpsecSA(
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
+ self.vpp_esp_protocol,
+ dst,
+ src,
+ flags=p.flags,
+ )
p.tun_sa_in.add_vpp_config()
def config_protect(self, p):
- p.tun_protect = VppIpsecTunProtect(self,
- p.tun_if,
- p.tun_sa_out,
- [p.tun_sa_in])
+ p.tun_protect = VppIpsecTunProtect(self, p.tun_if, p.tun_sa_out, [p.tun_sa_in])
p.tun_protect.add_vpp_config()
def config_network(self, p):
@@ -2879,15 +3181,24 @@ class TemplateIpsecItf6(object):
p.tun_if.config_ip4()
p.tun_if.config_ip6()
- r = VppIpRoute(self, p.remote_tun_if_host4, 32,
- [VppRoutePath(p.tun_if.remote_ip4,
- 0xffffffff)])
+ r = VppIpRoute(
+ self,
+ p.remote_tun_if_host4,
+ 32,
+ [VppRoutePath(p.tun_if.remote_ip4, 0xFFFFFFFF)],
+ )
r.add_vpp_config()
- p.route = VppIpRoute(self, p.remote_tun_if_host, 128,
- [VppRoutePath(p.tun_if.remote_ip6,
- 0xffffffff,
- proto=DpoProto.DPO_PROTO_IP6)])
+ p.route = VppIpRoute(
+ self,
+ p.remote_tun_if_host,
+ 128,
+ [
+ VppRoutePath(
+ p.tun_if.remote_ip6, 0xFFFFFFFF, proto=DpoProto.DPO_PROTO_IP6
+ )
+ ],
+ )
p.route.add_vpp_config()
def unconfig_network(self, p):
@@ -2903,10 +3214,8 @@ class TemplateIpsecItf6(object):
@tag_fixme_vpp_workers
-class TestIpsecItf6(TemplateIpsec,
- TemplateIpsecItf6,
- IpsecTun6):
- """ IPsec Interface IPv6 """
+class TestIpsecItf6(TemplateIpsec, TemplateIpsecItf6, IpsecTun6):
+ """IPsec Interface IPv6"""
def setUp(self):
super(TestIpsecItf6, self).setUp()
@@ -2928,13 +3237,11 @@ class TestIpsecItf6(TemplateIpsec,
p.tun_flags = tf.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_HOP_LIMIT
self.config_network(p)
- config_tun_params(p, self.encryption_type, None,
- self.pg0.local_ip6,
- self.pg0.remote_ip6)
+ config_tun_params(
+ p, self.encryption_type, None, self.pg0.local_ip6, self.pg0.remote_ip6
+ )
self.verify_drop_tun_66(p, count=n_pkts)
- self.config_sa_tun(p,
- self.pg0.local_ip6,
- self.pg0.remote_ip6)
+ self.config_sa_tun(p, self.pg0.local_ip6, self.pg0.remote_ip6)
self.config_protect(p)
self.verify_tun_66(p, count=n_pkts)
@@ -2946,15 +3253,15 @@ class TestIpsecItf6(TemplateIpsec,
p.tun_if.admin_up()
self.verify_tun_66(p, count=n_pkts)
- self.assertEqual(p.tun_if.get_rx_stats(), 3*n_pkts)
- self.assertEqual(p.tun_if.get_tx_stats(), 2*n_pkts)
+ self.assertEqual(p.tun_if.get_rx_stats(), 3 * n_pkts)
+ self.assertEqual(p.tun_if.get_tx_stats(), 2 * n_pkts)
# it's a v4 packet when its encrypted
self.tun6_encrypt_node_name = "esp4-encrypt-tun"
self.verify_tun_46(p, count=n_pkts)
- self.assertEqual(p.tun_if.get_rx_stats(), 4*n_pkts)
- self.assertEqual(p.tun_if.get_tx_stats(), 3*n_pkts)
+ self.assertEqual(p.tun_if.get_rx_stats(), 4 * n_pkts)
+ self.assertEqual(p.tun_if.get_tx_stats(), 3 * n_pkts)
self.tun6_encrypt_node_name = "esp6-encrypt-tun"
@@ -2962,7 +3269,7 @@ class TestIpsecItf6(TemplateIpsec,
# rekey - create new SAs and update the tunnel protection
np = copy.copy(p)
- np.crypt_key = b'X' + p.crypt_key[1:]
+ np.crypt_key = b"X" + p.crypt_key[1:]
np.scapy_tun_spi += 100
np.scapy_tun_sa_id += 1
np.vpp_tun_spi += 100
@@ -2971,14 +3278,12 @@ class TestIpsecItf6(TemplateIpsec,
np.tun_if.remote_spi = p.scapy_tun_spi
np.inner_hop_limit = 24
np.outer_hop_limit = 128
- np.inner_flow_label = 0xabcde
- np.outer_flow_label = 0xabcde
+ np.inner_flow_label = 0xABCDE
+ np.outer_flow_label = 0xABCDE
np.hop_limit = 128
np.tun_flags = tf.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_FLOW_LABEL
- self.config_sa_tun(np,
- self.pg0.local_ip6,
- self.pg0.remote_ip6)
+ self.config_sa_tun(np, self.pg0.local_ip6, self.pg0.remote_ip6)
self.config_protect(np)
self.unconfig_sa(p)
@@ -3002,18 +3307,23 @@ class TestIpsecItf6(TemplateIpsec,
p.tun_flags = tf.TUNNEL_API_ENCAP_DECAP_FLAG_ENCAP_COPY_HOP_LIMIT
self.config_network(p)
- self.config_sa_tun(p,
- self.pg0.local_ip6,
- self.pg0.remote_ip6)
+ self.config_sa_tun(p, self.pg0.local_ip6, self.pg0.remote_ip6)
self.config_protect(p)
action_tx = PolicerAction(
- VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT,
- 0)
- policer = VppPolicer(self, "pol1", 80, 0, 1000, 0,
- conform_action=action_tx,
- exceed_action=action_tx,
- violate_action=action_tx)
+ VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0
+ )
+ policer = VppPolicer(
+ self,
+ "pol1",
+ 80,
+ 0,
+ 1000,
+ 0,
+ conform_action=action_tx,
+ exceed_action=action_tx,
+ violate_action=action_tx,
+ )
policer.add_vpp_config()
# Start policing on tun
@@ -3026,9 +3336,9 @@ class TestIpsecItf6(TemplateIpsec,
stats = policer.get_stats()
# Single rate, 2 colour policer - expect conform, violate but no exceed
- self.assertGreater(stats['conform_packets'], 0)
- self.assertEqual(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ self.assertGreater(stats["conform_packets"], 0)
+ self.assertEqual(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
# Stop policing on tun
policer.apply_vpp_config(p.tun_if.sw_if_index, Dir.RX, False)
@@ -3046,27 +3356,31 @@ class TestIpsecItf6(TemplateIpsec,
class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4):
- """ Ipsec P2MP ESP v4 tests """
+ """Ipsec P2MP ESP v4 tests"""
+
tun4_encrypt_node_name = "esp4-encrypt-tun"
tun4_decrypt_node_name = ["esp4-decrypt-tun", "esp4-decrypt-tun-post"]
encryption_type = ESP
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=self.pg1.local_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
-
- def gen_pkts(self, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- IP(src="1.1.1.1", dst=dst) /
- UDP(sport=1144, dport=2233) /
- Raw(b'X' * payload_size)
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=self.pg1.local_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
+
+ def gen_pkts(self, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / IP(src="1.1.1.1", dst=dst)
+ / UDP(sport=1144, dport=2233)
+ / Raw(b"X" * payload_size)
+ for i in range(count)
+ ]
def verify_decrypted(self, p, rxs):
for rx in rxs:
@@ -3076,8 +3390,9 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4):
def verify_encrypted(self, p, sa, rxs):
for rx in rxs:
try:
- self.assertEqual(rx[IP].tos,
- VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF << 2)
+ self.assertEqual(
+ rx[IP].tos, VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF << 2
+ )
self.assertEqual(rx[IP].ttl, p.hop_limit)
pkt = sa.decrypt(rx[IP])
if not pkt.haslayer(IP):
@@ -3099,9 +3414,9 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4):
N_NHS = 16
self.tun_if = self.pg0
p = self.ipv4_params
- p.tun_if = VppIpsecInterface(self,
- mode=(VppEnum.vl_api_tunnel_mode_t.
- TUNNEL_API_MODE_MP))
+ p.tun_if = VppIpsecInterface(
+ self, mode=(VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_MP)
+ )
p.tun_if.add_vpp_config()
p.tun_if.admin_up()
p.tun_if.config_ip4()
@@ -3111,10 +3426,7 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4):
self.pg0.generate_remote_hosts(N_NHS)
self.pg0.configure_ipv4_neighbors()
- r_all = AclRule(True,
- src_prefix="0.0.0.0/0",
- dst_prefix="0.0.0.0/0",
- proto=0)
+ r_all = AclRule(True, src_prefix="0.0.0.0/0", dst_prefix="0.0.0.0/0", proto=0)
a = VppAcl(self, [r_all]).add_vpp_config()
VppAclInterface(self, self.pg0.sw_if_index, [a]).add_vpp_config()
@@ -3136,27 +3448,37 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4):
p.scapy_tra_spi = p.scapy_tra_spi + ii
p.vpp_tra_sa_id = p.vpp_tra_sa_id + ii
p.vpp_tra_spi = p.vpp_tra_spi + ii
- p.hop_limit = ii+10
+ p.hop_limit = ii + 10
p.tun_sa_out = VppIpsecSA(
- self, p.scapy_tun_sa_id, p.scapy_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
+ self,
+ p.scapy_tun_sa_id,
+ p.scapy_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
self.vpp_esp_protocol,
self.pg0.local_ip4,
self.pg0.remote_hosts[ii].ip4,
dscp=VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF,
- hop_limit=p.hop_limit)
+ hop_limit=p.hop_limit,
+ )
p.tun_sa_out.add_vpp_config()
p.tun_sa_in = VppIpsecSA(
- self, p.vpp_tun_sa_id, p.vpp_tun_spi,
- p.auth_algo_vpp_id, p.auth_key,
- p.crypt_algo_vpp_id, p.crypt_key,
+ self,
+ p.vpp_tun_sa_id,
+ p.vpp_tun_spi,
+ p.auth_algo_vpp_id,
+ p.auth_key,
+ p.crypt_algo_vpp_id,
+ p.crypt_key,
self.vpp_esp_protocol,
self.pg0.remote_hosts[ii].ip4,
self.pg0.local_ip4,
dscp=VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_EF,
- hop_limit=p.hop_limit)
+ hop_limit=p.hop_limit,
+ )
p.tun_sa_in.add_vpp_config()
p.tun_protect = VppIpsecTunProtect(
@@ -3164,17 +3486,24 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4):
p.tun_if,
p.tun_sa_out,
[p.tun_sa_in],
- nh=p.tun_if.remote_hosts[ii].ip4)
+ nh=p.tun_if.remote_hosts[ii].ip4,
+ )
p.tun_protect.add_vpp_config()
- config_tun_params(p, self.encryption_type, None,
- self.pg0.local_ip4,
- self.pg0.remote_hosts[ii].ip4)
+ config_tun_params(
+ p,
+ self.encryption_type,
+ None,
+ self.pg0.local_ip4,
+ self.pg0.remote_hosts[ii].ip4,
+ )
self.multi_params.append(p)
p.via_tun_route = VppIpRoute(
- self, p.remote_tun_if_host, 32,
- [VppRoutePath(p.tun_if.remote_hosts[ii].ip4,
- p.tun_if.sw_if_index)]).add_vpp_config()
+ self,
+ p.remote_tun_if_host,
+ 32,
+ [VppRoutePath(p.tun_if.remote_hosts[ii].ip4, p.tun_if.sw_if_index)],
+ ).add_vpp_config()
p.tun_dst = self.pg0.remote_hosts[ii].ip4
@@ -3205,10 +3534,8 @@ class TestIpsecMIfEsp4(TemplateIpsec, IpsecTun4):
self.verify_tun_44(p, count=N_PKTS)
-class TestIpsecItf6MPLS(TemplateIpsec,
- TemplateIpsecItf6,
- IpsecTun6):
- """ IPsec Interface MPLSoIPv6 """
+class TestIpsecItf6MPLS(TemplateIpsec, TemplateIpsecItf6, IpsecTun6):
+ """IPsec Interface MPLSoIPv6"""
tun6_encrypt_node_name = "esp-mpls-encrypt-tun"
@@ -3220,14 +3547,17 @@ class TestIpsecItf6MPLS(TemplateIpsec,
def tearDown(self):
super(TestIpsecItf6MPLS, self).tearDown()
- def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=100):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(MPLS(label=66, ttl=3) /
- IPv6(src=src, dst=dst) /
- UDP(sport=1166, dport=2233) /
- Raw(b'X' * payload_size))
- for i in range(count)]
+ def gen_encrypt_pkts6(self, p, sa, sw_intf, src, dst, count=1, payload_size=100):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ MPLS(label=66, ttl=3)
+ / IPv6(src=src, dst=dst)
+ / UDP(sport=1166, dport=2233)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
def verify_encrypted6(self, p, sa, rxs):
for rx in rxs:
@@ -3258,19 +3588,23 @@ class TestIpsecItf6MPLS(TemplateIpsec,
self.config_network(p)
# deag MPLS routes from the tunnel
- r6 = VppMplsRoute(self, 66, 1,
- [VppRoutePath(
- self.pg1.remote_ip6,
- self.pg1.sw_if_index)],
- eos_proto=f.FIB_PATH_NH_PROTO_IP6).add_vpp_config()
- p.route.modify([VppRoutePath(p.tun_if.remote_ip6,
- p.tun_if.sw_if_index,
- labels=[VppMplsLabel(66)])])
+ r6 = VppMplsRoute(
+ self,
+ 66,
+ 1,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ eos_proto=f.FIB_PATH_NH_PROTO_IP6,
+ ).add_vpp_config()
+ p.route.modify(
+ [
+ VppRoutePath(
+ p.tun_if.remote_ip6, p.tun_if.sw_if_index, labels=[VppMplsLabel(66)]
+ )
+ ]
+ )
p.tun_if.enable_mpls()
- self.config_sa_tun(p,
- self.pg0.local_ip6,
- self.pg0.remote_ip6)
+ self.config_sa_tun(p, self.pg0.local_ip6, self.pg0.remote_ip6)
self.config_protect(p)
self.verify_tun_66(p, count=n_pkts)
@@ -3282,5 +3616,5 @@ class TestIpsecItf6MPLS(TemplateIpsec,
self.unconfig_network(p)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_l2_fib.py b/test/test_l2_fib.py
index 065e57e5343..fe1ea458182 100644
--- a/test/test_l2_fib.py
+++ b/test/test_l2_fib.py
@@ -73,12 +73,11 @@ from vpp_papi import mac_pton, VppEnum
class TestL2fib(VppTestCase):
- """ L2 FIB Test Case """
+ """L2 FIB Test Case"""
@classmethod
def bd_ifs(cls, bd_id):
- return range((bd_id - 1) * cls.n_ifs_per_bd,
- bd_id * cls.n_ifs_per_bd - 1)
+ return range((bd_id - 1) * cls.n_ifs_per_bd, bd_id * cls.n_ifs_per_bd - 1)
@classmethod
def setUpClass(cls):
@@ -104,7 +103,8 @@ class TestL2fib(VppTestCase):
ifs = cls.bd_ifs(bd_id)
for j in ifs:
cls.flows[cls.pg_interfaces[j]] = [
- cls.pg_interfaces[x] for x in ifs if x != j]
+ cls.pg_interfaces[x] for x in ifs if x != j
+ ]
# Packet sizes
cls.pg_if_packet_sizes = [64, 512, 1518, 9018]
@@ -112,12 +112,12 @@ class TestL2fib(VppTestCase):
for bd_id in n_brs:
# Create BD with MAC learning and unknown unicast flooding
# disabled and put interfaces to this BD
- cls.vapi.bridge_domain_add_del(bd_id=bd_id, uu_flood=0,
- learn=0)
+ cls.vapi.bridge_domain_add_del(bd_id=bd_id, uu_flood=0, learn=0)
ifs = [cls.pg_interfaces[i] for i in cls.bd_ifs(bd_id)]
for pg_if in ifs:
cls.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=pg_if.sw_if_index, bd_id=bd_id)
+ rx_sw_if_index=pg_if.sw_if_index, bd_id=bd_id
+ )
# Set up all interfaces
for i in cls.pg_interfaces:
@@ -141,8 +141,9 @@ class TestL2fib(VppTestCase):
super(TestL2fib, self).tearDown()
if not self.vpp_dead:
for bd_id in self.n_brs:
- self.logger.info(self.vapi.ppcli("show bridge-domain %s detail"
- % bd_id))
+ self.logger.info(
+ self.vapi.ppcli("show bridge-domain %s detail" % bd_id)
+ )
def show_commands_at_teardown(self):
self.logger.info(self.vapi.ppcli("show l2fib verbose"))
@@ -160,11 +161,15 @@ class TestL2fib(VppTestCase):
for pg_if in self.pg_interfaces:
swif = pg_if.sw_if_index
- def mac(j): return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j)
+ def mac(j):
+ return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j)
- def ip(j): return "172.%02u.1%02x.%u" % (subnet, swif, j)
+ def ip(j):
+ return "172.%02u.1%02x.%u" % (subnet, swif, j)
+
+ def h(j):
+ return Host(mac(j), ip(j))
- def h(j): return Host(mac(j), ip(j))
hosts[swif] = [h(j) for j in range(n_hosts_per_if)]
return hosts
@@ -188,8 +193,9 @@ class TestL2fib(VppTestCase):
ifs = [self.pg_interfaces[i] for i in self.bd_ifs(bd_id)]
for pg_if in ifs:
swif = pg_if.sw_if_index
- packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac)
- for host in hosts[swif]]
+ packets = [
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) for host in hosts[swif]
+ ]
pg_if.add_stream(packets)
self.logger.info("Sending broadcast eth frames for MAC learning")
self.pg_start()
@@ -206,8 +212,7 @@ class TestL2fib(VppTestCase):
for pg_if in ifs:
swif = pg_if.sw_if_index
for host in hosts[swif]:
- self.vapi.l2fib_add_del(
- mac_pton(host.mac), bd_id, swif, static_mac=1)
+ self.vapi.l2fib_add_del(mac_pton(host.mac), bd_id, swif, static_mac=1)
def delete_l2_fib_entry(self, bd_id, hosts):
"""
@@ -219,8 +224,7 @@ class TestL2fib(VppTestCase):
for pg_if in ifs:
swif = pg_if.sw_if_index
for host in hosts[swif]:
- self.vapi.l2fib_add_del(
- mac_pton(host.mac), bd_id, swif, is_add=0)
+ self.vapi.l2fib_add_del(mac_pton(host.mac), bd_id, swif, is_add=0)
def flush_int(self, swif, learned_hosts):
"""
@@ -278,10 +282,12 @@ class TestL2fib(VppTestCase):
src_host = random.choice(src_hosts)
pkt_info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(pkt_info)
- p = (Ether(dst=dst_host.mac, src=src_host.mac) /
- IP(src=src_host.ip4, dst=dst_host.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=dst_host.mac, src=src_host.mac)
+ / IP(src=src_host.ip4, dst=dst_host.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
pkt_info.data = p.copy()
size = random.choice(packet_sizes)
self.extend_packet(p, size)
@@ -306,11 +312,13 @@ class TestL2fib(VppTestCase):
udp = packet[UDP]
packet_index = payload_info.index
self.assertEqual(payload_info.dst, dst_sw_if_index)
- self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
- (pg_if.name, payload_info.src, packet_index))
+ self.logger.debug(
+ "Got packet on port %s: src=%u (id=%u)"
+ % (pg_if.name, payload_info.src, packet_index)
+ )
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
self.assertEqual(packet_index, next_info.index)
@@ -325,11 +333,13 @@ class TestL2fib(VppTestCase):
raise
for i in self.pg_interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i, dst_sw_if_index, last_info[i.sw_if_index])
+ i, dst_sw_if_index, last_info[i.sw_if_index]
+ )
self.assertTrue(
remaining_packet is None,
- "Port %u: Packet expected from source %u didn't arrive" %
- (dst_sw_if_index, i.sw_if_index))
+ "Port %u: Packet expected from source %u didn't arrive"
+ % (dst_sw_if_index, i.sw_if_index),
+ )
def run_verify_test(self, bd_id, src_hosts, dst_hosts):
# Test
@@ -338,9 +348,11 @@ class TestL2fib(VppTestCase):
ifs = [self.pg_interfaces[i] for i in self.bd_ifs(bd_id)]
for i in ifs:
pkts = self.create_stream(
- i, self.pg_if_packet_sizes,
+ i,
+ self.pg_if_packet_sizes,
if_src_hosts=src_hosts,
- if_dst_hosts=dst_hosts)
+ if_dst_hosts=dst_hosts,
+ )
if pkts:
i.add_stream(pkts)
@@ -366,9 +378,11 @@ class TestL2fib(VppTestCase):
ifs = [self.pg_interfaces[i] for i in self.bd_ifs(bd_id)]
for i in ifs:
pkts = self.create_stream(
- i, self.pg_if_packet_sizes,
+ i,
+ self.pg_if_packet_sizes,
if_src_hosts=src_hosts,
- if_dst_hosts=dst_hosts)
+ if_dst_hosts=dst_hosts,
+ )
if pkts:
i.add_stream(pkts)
@@ -386,16 +400,14 @@ class TestL2fib(VppTestCase):
timeout = 0.1
def test_l2_fib_program100(self):
- """ L2 FIB - program 100 MACs
- """
+ """L2 FIB - program 100 MACs"""
bd_id = 1
hosts = self.create_hosts(100, subnet=17)
self.config_l2_fib_entries(bd_id, hosts)
self.run_verify_test(bd_id, hosts, hosts)
def test_l2_fib_program100_delete12(self):
- """ L2 FIB - program 100, delete 12 MACs
- """
+ """L2 FIB - program 100, delete 12 MACs"""
bd_id = 1
hosts = self.create_hosts(100, subnet=17)
self.config_l2_fib_entries(bd_id, hosts)
@@ -406,8 +418,7 @@ class TestL2fib(VppTestCase):
self.run_verify_negat_test(bd_id, hosts, del_hosts)
def test_l2_fib_program100_add100(self):
- """ L2 FIB - program 100, add 100 MACs
- """
+ """L2 FIB - program 100, add 100 MACs"""
bd_id = 1
hosts = self.create_hosts(100, subnet=17)
self.config_l2_fib_entries(bd_id, hosts)
@@ -416,8 +427,7 @@ class TestL2fib(VppTestCase):
self.run_verify_test(bd_id, hosts, hosts2)
def test_l2_fib_program10_learn10(self):
- """ L2 FIB - program 10 MACs, learn 10
- """
+ """L2 FIB - program 10 MACs, learn 10"""
hosts = self.create_hosts(20, subnet=35)
lhosts = self.split_hosts(hosts, 10)
@@ -431,8 +441,7 @@ class TestL2fib(VppTestCase):
self.run_verify_test(bd2, lhosts, hosts)
def test_l2_fib_flush_int(self):
- """ L2 FIB - flush interface
- """
+ """L2 FIB - flush interface"""
hosts = self.create_hosts(20, subnet=36)
lhosts = self.split_hosts(hosts, 10)
@@ -445,8 +454,7 @@ class TestL2fib(VppTestCase):
self.run_verify_negat_test(bd1, hosts, flushed)
def test_l2_fib_flush_bd(self):
- """ L2 FIB - flush BD
- """
+ """L2 FIB - flush BD"""
hosts = self.create_hosts(20, subnet=37)
lhosts = self.split_hosts(hosts, 10)
@@ -458,8 +466,7 @@ class TestL2fib(VppTestCase):
self.run_verify_negat_test(bd1, hosts, flushed)
def test_l2_fib_flush_all(self):
- """ L2 FIB - flush all
- """
+ """L2 FIB - flush all"""
hosts = self.create_hosts(20, subnet=38)
lhosts = self.split_hosts(hosts, 10)
@@ -478,8 +485,7 @@ class TestL2fib(VppTestCase):
self.run_verify_negat_test(bd2, hosts, lhosts)
def test_l2_fib_mac_learn_evs(self):
- """ L2 FIB - mac learning events
- """
+ """L2 FIB - mac learning events"""
bd1 = 1
hosts = self.create_hosts(10, subnet=39)
@@ -491,16 +497,21 @@ class TestL2fib(VppTestCase):
evs = self.vapi.collect_events()
action = VppEnum.vl_api_mac_event_action_t.MAC_EVENT_ACTION_API_ADD
learned_macs = {
- e.mac[i].mac_addr.packed for e in evs for i in range(e.n_macs)
- if e.mac[i].action == action}
- macs = {h.bin_mac for swif in self.bd_ifs(bd1)
- for h in hosts[self.pg_interfaces[swif].sw_if_index]}
+ e.mac[i].mac_addr.packed
+ for e in evs
+ for i in range(e.n_macs)
+ if e.mac[i].action == action
+ }
+ macs = {
+ h.bin_mac
+ for swif in self.bd_ifs(bd1)
+ for h in hosts[self.pg_interfaces[swif].sw_if_index]
+ }
self.vapi.want_l2_macs_events(enable_disable=0)
self.assertEqual(len(learned_macs ^ macs), 0)
def test_l2_fib_mac_learn_evs2(self):
- """ L2 FIB - mac learning events using want_l2_macs_events2
- """
+ """L2 FIB - mac learning events using want_l2_macs_events2"""
bd1 = 1
hosts = self.create_hosts(10, subnet=39)
@@ -514,16 +525,21 @@ class TestL2fib(VppTestCase):
evs = self.vapi.collect_events()
action = VppEnum.vl_api_mac_event_action_t.MAC_EVENT_ACTION_API_ADD
learned_macs = {
- e.mac[i].mac_addr.packed for e in evs for i in range(e.n_macs)
- if e.mac[i].action == action}
- macs = {h.bin_mac for swif in self.bd_ifs(bd1)
- for h in hosts[self.pg_interfaces[swif].sw_if_index]}
+ e.mac[i].mac_addr.packed
+ for e in evs
+ for i in range(e.n_macs)
+ if e.mac[i].action == action
+ }
+ macs = {
+ h.bin_mac
+ for swif in self.bd_ifs(bd1)
+ for h in hosts[self.pg_interfaces[swif].sw_if_index]
+ }
self.vapi.want_l2_macs_events2(enable_disable=0)
self.assertEqual(len(learned_macs ^ macs), 0)
def test_l2_fib_macs_learn_max(self):
- """ L2 FIB - mac learning max macs in event
- """
+ """L2 FIB - mac learning max macs in event"""
bd1 = 1
hosts = self.create_hosts(10, subnet=40)
@@ -539,18 +555,23 @@ class TestL2fib(VppTestCase):
self.assertGreater(len(evs), 0)
action = VppEnum.vl_api_mac_event_action_t.MAC_EVENT_ACTION_API_ADD
learned_macs = {
- e.mac[i].mac_addr.packed for e in evs for i in range(e.n_macs)
- if e.mac[i].action == action}
- macs = {h.bin_mac for swif in self.bd_ifs(bd1)
- for h in hosts[self.pg_interfaces[swif].sw_if_index]}
+ e.mac[i].mac_addr.packed
+ for e in evs
+ for i in range(e.n_macs)
+ if e.mac[i].action == action
+ }
+ macs = {
+ h.bin_mac
+ for swif in self.bd_ifs(bd1)
+ for h in hosts[self.pg_interfaces[swif].sw_if_index]
+ }
for e in evs:
self.assertLess(len(e), ev_macs * 10)
self.assertEqual(len(learned_macs ^ macs), 0)
def test_l2_fib_macs_learn_max2(self):
- """ L2 FIB - mac learning max macs in event using want_l2_macs_events2
- """
+ """L2 FIB - mac learning max macs in event using want_l2_macs_events2"""
bd1 = 1
hosts = self.create_hosts(10, subnet=40)
@@ -568,14 +589,21 @@ class TestL2fib(VppTestCase):
self.assertGreater(len(evs), 0)
action = VppEnum.vl_api_mac_event_action_t.MAC_EVENT_ACTION_API_ADD
learned_macs = {
- e.mac[i].mac_addr.packed for e in evs for i in range(e.n_macs)
- if e.mac[i].action == action}
- macs = {h.bin_mac for swif in self.bd_ifs(bd1)
- for h in hosts[self.pg_interfaces[swif].sw_if_index]}
+ e.mac[i].mac_addr.packed
+ for e in evs
+ for i in range(e.n_macs)
+ if e.mac[i].action == action
+ }
+ macs = {
+ h.bin_mac
+ for swif in self.bd_ifs(bd1)
+ for h in hosts[self.pg_interfaces[swif].sw_if_index]
+ }
for e in evs:
self.assertLess(len(e), ev_macs * 10)
self.assertEqual(len(learned_macs ^ macs), 0)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_l2_flood.py b/test/test_l2_flood.py
index 7f3c57a399d..db4af607451 100644
--- a/test/test_l2_flood.py
+++ b/test/test_l2_flood.py
@@ -15,7 +15,7 @@ NUM_PKTS = 67
class TestL2Flood(VppTestCase):
- """ L2-flood """
+ """L2-flood"""
@classmethod
def setUpClass(cls):
@@ -52,7 +52,7 @@ class TestL2Flood(VppTestCase):
super(TestL2Flood, self).tearDown()
def test_flood(self):
- """ L2 Flood Tests """
+ """L2 Flood Tests"""
#
# Create a single bridge Domain
@@ -63,31 +63,35 @@ class TestL2Flood(VppTestCase):
# add each interface to the BD. 3 interfaces per split horizon group
#
for i in self.pg_interfaces[0:4]:
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=1, shg=0)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index, bd_id=1, shg=0
+ )
for i in self.pg_interfaces[4:8]:
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=1, shg=1)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index, bd_id=1, shg=1
+ )
for i in self.pg_interfaces[8:12]:
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=1, shg=2)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index, bd_id=1, shg=2
+ )
for i in self.bvi_interfaces:
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=1, shg=2,
- port_type=L2_PORT_TYPE.BVI)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index, bd_id=1, shg=2, port_type=L2_PORT_TYPE.BVI
+ )
- p = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src="00:00:de:ad:be:ef") /
- IP(src="10.10.10.10", dst="1.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src="00:00:de:ad:be:ef")
+ / IP(src="10.10.10.10", dst="1.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# input on pg0 expect copies on pg1->11
# this is in SHG=0 so its flooded to all, expect the pg0 since that's
# the ingress link
#
- self.pg0.add_stream(p*NUM_PKTS)
+ self.pg0.add_stream(p * NUM_PKTS)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -98,7 +102,7 @@ class TestL2Flood(VppTestCase):
# input on pg4 (SHG=1) expect copies on pg0->3 (SHG=0)
# and pg8->11 (SHG=2)
#
- self.pg4.add_stream(p*NUM_PKTS)
+ self.pg4.add_stream(p * NUM_PKTS)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -112,9 +116,12 @@ class TestL2Flood(VppTestCase):
#
# An IP route so the packet that hits the BVI is sent out of pg12
#
- ip_route = VppIpRoute(self, "1.1.1.1", 32,
- [VppRoutePath(self.pg12.remote_ip4,
- self.pg12.sw_if_index)])
+ ip_route = VppIpRoute(
+ self,
+ "1.1.1.1",
+ 32,
+ [VppRoutePath(self.pg12.remote_ip4, self.pg12.sw_if_index)],
+ )
ip_route.add_vpp_config()
self.logger.info(self.vapi.cli("sh bridge 1 detail"))
@@ -124,7 +131,7 @@ class TestL2Flood(VppTestCase):
# this is in SHG=0 so its flooded to all, expect the pg0 since that's
# the ingress link
#
- self.pg0.add_stream(p*NUM_PKTS)
+ self.pg0.add_stream(p * NUM_PKTS)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -135,7 +142,7 @@ class TestL2Flood(VppTestCase):
# input on pg4 (SHG=1) expect copies on pg0->3 (SHG=0)
# and pg8->12 (SHG=2)
#
- self.pg4.add_stream(p*NUM_PKTS)
+ self.pg4.add_stream(p * NUM_PKTS)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -150,18 +157,22 @@ class TestL2Flood(VppTestCase):
# cleanup
#
for i in self.pg_interfaces[:12]:
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=1, enable=0)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index, bd_id=1, enable=0
+ )
for i in self.bvi_interfaces:
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=1, shg=2,
- port_type=L2_PORT_TYPE.BVI,
- enable=0)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index,
+ bd_id=1,
+ shg=2,
+ port_type=L2_PORT_TYPE.BVI,
+ enable=0,
+ )
self.vapi.bridge_domain_add_del(bd_id=1, is_add=0)
def test_flood_one(self):
- """ L2 no-Flood Test """
+ """L2 no-Flood Test"""
#
# Create a single bridge Domain
@@ -173,30 +184,33 @@ class TestL2Flood(VppTestCase):
# one member
#
for i in self.pg_interfaces[:2]:
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=1, shg=0)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index, bd_id=1, shg=0
+ )
- p = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src="00:00:de:ad:be:ef") /
- IP(src="10.10.10.10", dst="1.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src="00:00:de:ad:be:ef")
+ / IP(src="10.10.10.10", dst="1.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# input on pg0 expect copies on pg1
#
- self.send_and_expect(self.pg0, p*NUM_PKTS, self.pg1)
+ self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1)
#
# cleanup
#
for i in self.pg_interfaces[:2]:
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=1, enable=0)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index, bd_id=1, enable=0
+ )
self.vapi.bridge_domain_add_del(bd_id=1, is_add=0)
def test_uu_fwd(self):
- """ UU Flood """
+ """UU Flood"""
#
# Create a single bridge Domain
@@ -207,34 +221,37 @@ class TestL2Flood(VppTestCase):
# add each interface to the BD. 3 interfaces per split horizon group
#
for i in self.pg_interfaces[0:4]:
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=1, shg=0)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index, bd_id=1, shg=0
+ )
#
# an unknown unicast and broadcast packets
#
- p_uu = (Ether(dst="00:00:00:c1:5c:00",
- src="00:00:de:ad:be:ef") /
- IP(src="10.10.10.10", dst="1.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- p_bm = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src="00:00:de:ad:be:ef") /
- IP(src="10.10.10.10", dst="1.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_uu = (
+ Ether(dst="00:00:00:c1:5c:00", src="00:00:de:ad:be:ef")
+ / IP(src="10.10.10.10", dst="1.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ p_bm = (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src="00:00:de:ad:be:ef")
+ / IP(src="10.10.10.10", dst="1.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# input on pg0, expected copies on pg1->4
#
- self.pg0.add_stream(p_uu*NUM_PKTS)
+ self.pg0.add_stream(p_uu * NUM_PKTS)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
for i in self.pg_interfaces[1:4]:
rx0 = i.get_capture(NUM_PKTS, timeout=1)
- self.pg0.add_stream(p_bm*NUM_PKTS)
+ self.pg0.add_stream(p_bm * NUM_PKTS)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -245,13 +262,16 @@ class TestL2Flood(VppTestCase):
# use pg8 as the uu-fwd interface
#
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg8.sw_if_index, bd_id=1, shg=0,
- port_type=L2_PORT_TYPE.UU_FWD)
+ rx_sw_if_index=self.pg8.sw_if_index,
+ bd_id=1,
+ shg=0,
+ port_type=L2_PORT_TYPE.UU_FWD,
+ )
#
# expect the UU packet on the uu-fwd interface and not be flooded
#
- self.pg0.add_stream(p_uu*NUM_PKTS)
+ self.pg0.add_stream(p_uu * NUM_PKTS)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -260,7 +280,7 @@ class TestL2Flood(VppTestCase):
for i in self.pg_interfaces[0:4]:
i.assert_nothing_captured(remark="UU not flooded")
- self.pg0.add_stream(p_bm*NUM_PKTS)
+ self.pg0.add_stream(p_bm * NUM_PKTS)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -271,10 +291,14 @@ class TestL2Flood(VppTestCase):
# remove the uu-fwd interface and expect UU to be flooded again
#
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg8.sw_if_index, bd_id=1, shg=0,
- port_type=L2_PORT_TYPE.UU_FWD, enable=0)
-
- self.pg0.add_stream(p_uu*NUM_PKTS)
+ rx_sw_if_index=self.pg8.sw_if_index,
+ bd_id=1,
+ shg=0,
+ port_type=L2_PORT_TYPE.UU_FWD,
+ enable=0,
+ )
+
+ self.pg0.add_stream(p_uu * NUM_PKTS)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -292,11 +316,14 @@ class TestL2Flood(VppTestCase):
# re-add the uu-fwd interface
#
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg8.sw_if_index, bd_id=1, shg=0,
- port_type=L2_PORT_TYPE.UU_FWD)
+ rx_sw_if_index=self.pg8.sw_if_index,
+ bd_id=1,
+ shg=0,
+ port_type=L2_PORT_TYPE.UU_FWD,
+ )
self.logger.info(self.vapi.cli("sh bridge 1 detail"))
- self.pg0.add_stream(p_uu*NUM_PKTS)
+ self.pg0.add_stream(p_uu * NUM_PKTS)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -309,19 +336,24 @@ class TestL2Flood(VppTestCase):
# remove the uu-fwd interface
#
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg8.sw_if_index, bd_id=1, shg=0,
- port_type=L2_PORT_TYPE.UU_FWD, enable=0)
+ rx_sw_if_index=self.pg8.sw_if_index,
+ bd_id=1,
+ shg=0,
+ port_type=L2_PORT_TYPE.UU_FWD,
+ enable=0,
+ )
self.send_and_assert_no_replies(self.pg0, p_uu)
#
# cleanup
#
for i in self.pg_interfaces[:4]:
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=1, enable=0)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index, bd_id=1, enable=0
+ )
self.vapi.bridge_domain_add_del(bd_id=1, is_add=0)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_l2bd.py b/test/test_l2bd.py
index 5eca48c6e9b..63ed2deeb68 100644
--- a/test/test_l2bd.py
+++ b/test/test_l2bd.py
@@ -13,7 +13,7 @@ from vpp_sub_interface import VppDot1QSubint, VppDot1ADSubint
class TestL2bd(VppTestCase):
- """ L2BD Test Case """
+ """L2BD Test Case"""
@classmethod
def setUpClass(cls):
@@ -54,8 +54,14 @@ class TestL2bd(VppTestCase):
# create 2 sub-interfaces for pg1 and pg2
cls.sub_interfaces = [
VppDot1QSubint(cls, cls.pg1, cls.dot1q_tag),
- VppDot1ADSubint(cls, cls.pg2, cls.dot1ad_sub_id,
- cls.dot1ad_outer_tag, cls.dot1ad_inner_tag)]
+ VppDot1ADSubint(
+ cls,
+ cls.pg2,
+ cls.dot1ad_sub_id,
+ cls.dot1ad_outer_tag,
+ cls.dot1ad_inner_tag,
+ ),
+ ]
# packet flows mapping pg0 -> pg1, pg2, etc.
cls.flows = dict()
@@ -73,10 +79,14 @@ class TestL2bd(VppTestCase):
# Create BD with MAC learning enabled and put interfaces and
# sub-interfaces to this BD
for pg_if in cls.pg_interfaces:
- sw_if_index = pg_if.sub_if.sw_if_index \
- if hasattr(pg_if, 'sub_if') else pg_if.sw_if_index
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=sw_if_index,
- bd_id=cls.bd_id)
+ sw_if_index = (
+ pg_if.sub_if.sw_if_index
+ if hasattr(pg_if, "sub_if")
+ else pg_if.sw_if_index
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=sw_if_index, bd_id=cls.bd_id
+ )
# setup all interfaces
for i in cls.interfaces:
@@ -112,8 +122,9 @@ class TestL2bd(VppTestCase):
super(TestL2bd, self).tearDown()
if not self.vpp_dead:
self.logger.info(self.vapi.ppcli("show l2fib verbose"))
- self.logger.info(self.vapi.ppcli("show bridge-domain %s detail" %
- self.bd_id))
+ self.logger.info(
+ self.vapi.ppcli("show bridge-domain %s detail" % self.bd_id)
+ )
@classmethod
def create_hosts_and_learn(cls, count):
@@ -138,10 +149,11 @@ class TestL2bd(VppTestCase):
for j in range(start_nr, end_nr):
host = Host(
"00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j),
- "172.17.1%02x.%u" % (pg_if.sw_if_index, j))
- packet = (Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac))
+ "172.17.1%02x.%u" % (pg_if.sw_if_index, j),
+ )
+ packet = Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac)
hosts.append(host)
- if hasattr(pg_if, 'sub_if'):
+ if hasattr(pg_if, "sub_if"):
packet = pg_if.sub_if.add_dot1_layer(packet)
packets.append(packet)
pg_if.add_stream(packets)
@@ -164,12 +176,14 @@ class TestL2bd(VppTestCase):
src_host = random.choice(self.hosts_by_pg_idx[src_if.sw_if_index])
pkt_info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(pkt_info)
- p = (Ether(dst=dst_host.mac, src=src_host.mac) /
- IP(src=src_host.ip4, dst=dst_host.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=dst_host.mac, src=src_host.mac)
+ / IP(src=src_host.ip4, dst=dst_host.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
pkt_info.data = p.copy()
- if hasattr(src_if, 'sub_if'):
+ if hasattr(src_if, "sub_if"):
p = src_if.sub_if.add_dot1_layer(p)
size = random.choice(packet_sizes)
self.extend_packet(p, size)
@@ -196,7 +210,7 @@ class TestL2bd(VppTestCase):
if ifc.sw_if_index == src_sw_if_index:
src_if = ifc
break
- if hasattr(src_if, 'sub_if'):
+ if hasattr(src_if, "sub_if"):
# Check VLAN tags and Ethernet header
packet = src_if.sub_if.remove_dot1_layer(packet)
self.assertTrue(Dot1Q not in packet)
@@ -205,11 +219,13 @@ class TestL2bd(VppTestCase):
udp = packet[UDP]
packet_index = payload_info.index
self.assertEqual(payload_info.dst, dst_sw_if_index)
- self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
- (pg_if.name, payload_info.src, packet_index))
+ self.logger.debug(
+ "Got packet on port %s: src=%u (id=%u)"
+ % (pg_if.name, payload_info.src, packet_index)
+ )
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
self.assertEqual(packet_index, next_info.index)
@@ -224,19 +240,24 @@ class TestL2bd(VppTestCase):
raise
for i in self.pg_interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i, dst_sw_if_index, last_info[i.sw_if_index])
+ i, dst_sw_if_index, last_info[i.sw_if_index]
+ )
self.assertTrue(
remaining_packet is None,
- "Port %u: Packet expected from source %u didn't arrive" %
- (dst_sw_if_index, i.sw_if_index))
+ "Port %u: Packet expected from source %u didn't arrive"
+ % (dst_sw_if_index, i.sw_if_index),
+ )
def run_l2bd_test(self, pkts_per_burst):
- """ L2BD MAC learning test """
+ """L2BD MAC learning test"""
# Create incoming packet streams for packet-generator interfaces
for i in self.pg_interfaces:
- packet_sizes = self.sub_if_packet_sizes if hasattr(i, 'sub_if') \
+ packet_sizes = (
+ self.sub_if_packet_sizes
+ if hasattr(i, "sub_if")
else self.pg_if_packet_sizes
+ )
pkts = self.create_stream(i, packet_sizes, pkts_per_burst)
i.add_stream(pkts)
@@ -251,7 +272,7 @@ class TestL2bd(VppTestCase):
self.verify_capture(i, capture)
def test_l2bd_sl(self):
- """ L2BD MAC learning single-loop test
+ """L2BD MAC learning single-loop test
Test scenario:
1.config
@@ -268,22 +289,22 @@ class TestL2bd(VppTestCase):
self.run_l2bd_test(self.sl_pkts_per_burst)
def test_l2bd_dl(self):
- """ L2BD MAC learning dual-loop test
+ """L2BD MAC learning dual-loop test
- Test scenario:
- 1.config
- MAC learning enabled
- learn 100 MAC entries
- 3 interfaces: untagged, dot1q, dot1ad (dot1q used instead of
- dot1ad in the first version)
-
- 2.sending l2 eth pkts between 3 interface
- 64B, 512B, 1518B, 9200B (ether_size)
- burst of 257 pkts per interface
+ Test scenario:
+ 1.config
+ MAC learning enabled
+ learn 100 MAC entries
+ 3 interfaces: untagged, dot1q, dot1ad (dot1q used instead of
+ dot1ad in the first version)
+
+ 2.sending l2 eth pkts between 3 interface
+ 64B, 512B, 1518B, 9200B (ether_size)
+ burst of 257 pkts per interface
"""
self.run_l2bd_test(self.dl_pkts_per_burst)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_l2bd_arp_term.py b/test/test_l2bd_arp_term.py
index c64d5d4f01c..598203950d9 100644
--- a/test/test_l2bd_arp_term.py
+++ b/test/test_l2bd_arp_term.py
@@ -10,19 +10,38 @@ from socket import AF_INET, AF_INET6, inet_pton, inet_ntop
from scapy.packet import Raw
from scapy.layers.l2 import Ether, ARP
from scapy.layers.inet import IP
-from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ptop, in6_islladdr, \
- in6_mactoifaceid, in6_ismaddr
-from scapy.layers.inet6 import IPv6, UDP, ICMPv6ND_NS, ICMPv6ND_RS, \
- ICMPv6ND_RA, ICMPv6NDOptSrcLLAddr, getmacbyip6, ICMPv6MRD_Solicitation, \
- ICMPv6NDOptMTU, ICMPv6NDOptSrcLLAddr, ICMPv6NDOptPrefixInfo, \
- ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, ICMPv6DestUnreach, icmp6types
+from scapy.utils6 import (
+ in6_getnsma,
+ in6_getnsmac,
+ in6_ptop,
+ in6_islladdr,
+ in6_mactoifaceid,
+ in6_ismaddr,
+)
+from scapy.layers.inet6 import (
+ IPv6,
+ UDP,
+ ICMPv6ND_NS,
+ ICMPv6ND_RS,
+ ICMPv6ND_RA,
+ ICMPv6NDOptSrcLLAddr,
+ getmacbyip6,
+ ICMPv6MRD_Solicitation,
+ ICMPv6NDOptMTU,
+ ICMPv6NDOptSrcLLAddr,
+ ICMPv6NDOptPrefixInfo,
+ ICMPv6ND_NA,
+ ICMPv6NDOptDstLLAddr,
+ ICMPv6DestUnreach,
+ icmp6types,
+)
from framework import VppTestCase, VppTestRunner
from util import Host, ppp
class TestL2bdArpTerm(VppTestCase):
- """ L2BD arp termination Test Case """
+ """L2BD arp termination Test Case"""
@classmethod
def setUpClass(cls):
@@ -77,11 +96,9 @@ class TestL2bdArpTerm(VppTestCase):
def add_del_arp_term_hosts(self, entries, bd_id=1, is_add=1, is_ipv6=0):
for e in entries:
ip = e.ip4 if is_ipv6 == 0 else e.ip6
- self.vapi.bd_ip_mac_add_del(is_add=is_add,
- entry={
- 'bd_id': bd_id,
- 'ip': ip,
- 'mac': e.mac})
+ self.vapi.bd_ip_mac_add_del(
+ is_add=is_add, entry={"bd_id": bd_id, "ip": ip, "mac": e.mac}
+ )
@classmethod
def mac_list(cls, b6_range):
@@ -89,23 +106,23 @@ class TestL2bdArpTerm(VppTestCase):
@classmethod
def ip4_host(cls, subnet, host, mac):
- return Host(mac=mac,
- ip4="172.17.1%02u.%u" % (subnet, host))
+ return Host(mac=mac, ip4="172.17.1%02u.%u" % (subnet, host))
@classmethod
def ip4_hosts(cls, subnet, start, mac_list):
- return {cls.ip4_host(subnet, start + j, mac_list[j])
- for j in range(len(mac_list))}
+ return {
+ cls.ip4_host(subnet, start + j, mac_list[j]) for j in range(len(mac_list))
+ }
@classmethod
def ip6_host(cls, subnet, host, mac):
- return Host(mac=mac,
- ip6="fd01:%x::%x" % (subnet, host))
+ return Host(mac=mac, ip6="fd01:%x::%x" % (subnet, host))
@classmethod
def ip6_hosts(cls, subnet, start, mac_list):
- return {cls.ip6_host(subnet, start + j, mac_list[j])
- for j in range(len(mac_list))}
+ return {
+ cls.ip6_host(subnet, start + j, mac_list[j]) for j in range(len(mac_list))
+ }
@classmethod
def bd_swifs(cls, b):
@@ -118,18 +135,17 @@ class TestL2bdArpTerm(VppTestCase):
self.vapi.bridge_domain_add_del(bd_id=bd_id, is_add=is_add)
for swif in self.bd_swifs(bd_id):
swif_idx = swif.sw_if_index
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=swif_idx,
- bd_id=bd_id, enable=is_add)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=swif_idx, bd_id=bd_id, enable=is_add
+ )
if not is_add:
self.vapi.bridge_domain_add_del(bd_id=bd_id, is_add=is_add)
@classmethod
def arp_req(cls, src_host, host):
- return (Ether(dst="ff:ff:ff:ff:ff:ff", src=src_host.mac) /
- ARP(op="who-has",
- hwsrc=src_host.bin_mac,
- pdst=host.ip4,
- psrc=src_host.ip4))
+ return Ether(dst="ff:ff:ff:ff:ff:ff", src=src_host.mac) / ARP(
+ op="who-has", hwsrc=src_host.bin_mac, pdst=host.ip4, psrc=src_host.ip4
+ )
@classmethod
def arp_reqs(cls, src_host, entries):
@@ -167,7 +183,7 @@ class TestL2bdArpTerm(VppTestCase):
o2 = int(ip / 65536) % 256
o3 = int(ip / 256) % 256
o4 = int(ip) % 256
- return '%s.%s.%s.%s' % (o1, o2, o3, o4)
+ return "%s.%s.%s.%s" % (o1, o2, o3, o4)
def arp_event_host(self, e):
return Host(str(e.mac), ip4=str(e.ip))
@@ -185,10 +201,12 @@ class TestL2bdArpTerm(VppTestCase):
def ns_req(cls, src_host, host):
nsma = in6_getnsma(inet_pton(AF_INET6, "fd10::ffff"))
d = inet_ntop(AF_INET6, nsma)
- return (Ether(dst="ff:ff:ff:ff:ff:ff", src=src_host.mac) /
- IPv6(dst=d, src=src_host.ip6) /
- ICMPv6ND_NS(tgt=host.ip6) /
- ICMPv6NDOptSrcLLAddr(lladdr=src_host.mac))
+ return (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=src_host.mac)
+ / IPv6(dst=d, src=src_host.ip6)
+ / ICMPv6ND_NS(tgt=host.ip6)
+ / ICMPv6NDOptSrcLLAddr(lladdr=src_host.mac)
+ )
@classmethod
def ns_reqs_dst(cls, entries, dst_host):
@@ -200,8 +218,7 @@ class TestL2bdArpTerm(VppTestCase):
def na_resp_host(self, src_host, rx):
self.assertEqual(rx[Ether].dst, src_host.mac)
- self.assertEqual(in6_ptop(rx[IPv6].dst),
- in6_ptop(src_host.ip6))
+ self.assertEqual(in6_ptop(rx[IPv6].dst), in6_ptop(src_host.ip6))
self.assertTrue(rx.haslayer(ICMPv6ND_NA))
self.assertTrue(rx.haslayer(ICMPv6NDOptDstLLAddr))
@@ -236,8 +253,7 @@ class TestL2bdArpTerm(VppTestCase):
else:
raise ValueError("Unknown feature used: %s" % flag)
is_set = 1 if args[flag] else 0
- self.vapi.bridge_flags(bd_id=bd_id, is_set=is_set,
- flags=feature_bitmap)
+ self.vapi.bridge_flags(bd_id=bd_id, is_set=is_set, flags=feature_bitmap)
self.logger.info("Bridge domain ID %d updated" % bd_id)
def verify_arp(self, src_host, req_hosts, resp_hosts, bd_id=1):
@@ -269,12 +285,10 @@ class TestL2bdArpTerm(VppTestCase):
self.assertEqual(len(resps ^ resp_hosts), 0)
def test_l2bd_arp_term_01(self):
- """ L2BD arp term - add 5 hosts, verify arp responses
- """
+ """L2BD arp term - add 5 hosts, verify arp responses"""
src_host = self.ip4_host(50, 50, "00:00:11:22:33:44")
self.bd_add_del(1, is_add=1)
- self.set_bd_flags(1, arp_term=True, flood=False,
- uu_flood=False, learn=False)
+ self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False)
macs = self.mac_list(range(1, 5))
hosts = self.ip4_hosts(4, 1, macs)
self.add_del_arp_term_hosts(hosts, is_add=1)
@@ -283,8 +297,7 @@ class TestL2bdArpTerm(VppTestCase):
type(self).hosts = hosts
def test_l2bd_arp_term_02(self):
- """ L2BD arp term - delete 3 hosts, verify arp responses
- """
+ """L2BD arp term - delete 3 hosts, verify arp responses"""
src_host = self.ip4_host(50, 50, "00:00:11:22:33:44")
macs = self.mac_list(range(1, 3))
deleted = self.ip4_hosts(4, 1, macs)
@@ -295,12 +308,10 @@ class TestL2bdArpTerm(VppTestCase):
self.bd_add_del(1, is_add=0)
def test_l2bd_arp_term_03(self):
- """ L2BD arp term - recreate BD1, readd 3 hosts, verify arp responses
- """
+ """L2BD arp term - recreate BD1, readd 3 hosts, verify arp responses"""
src_host = self.ip4_host(50, 50, "00:00:11:22:33:44")
self.bd_add_del(1, is_add=1)
- self.set_bd_flags(1, arp_term=True, flood=False,
- uu_flood=False, learn=False)
+ self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False)
macs = self.mac_list(range(1, 3))
readded = self.ip4_hosts(4, 1, macs)
self.add_del_arp_term_hosts(readded, is_add=1)
@@ -308,8 +319,7 @@ class TestL2bdArpTerm(VppTestCase):
type(self).hosts = readded
def test_l2bd_arp_term_04(self):
- """ L2BD arp term - 2 IP4 addrs per host
- """
+ """L2BD arp term - 2 IP4 addrs per host"""
src_host = self.ip4_host(50, 50, "00:00:11:22:33:44")
macs = self.mac_list(range(1, 3))
sub5_hosts = self.ip4_hosts(5, 1, macs)
@@ -320,12 +330,10 @@ class TestL2bdArpTerm(VppTestCase):
self.bd_add_del(1, is_add=0)
def test_l2bd_arp_term_05(self):
- """ L2BD arp term - create and update 10 IP4-mac pairs
- """
+ """L2BD arp term - create and update 10 IP4-mac pairs"""
src_host = self.ip4_host(50, 50, "00:00:11:22:33:44")
self.bd_add_del(1, is_add=1)
- self.set_bd_flags(1, arp_term=True, flood=False,
- uu_flood=False, learn=False)
+ self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False)
macs1 = self.mac_list(range(10, 20))
hosts1 = self.ip4_hosts(5, 1, macs1)
self.add_del_arp_term_hosts(hosts1, is_add=1)
@@ -337,14 +345,12 @@ class TestL2bdArpTerm(VppTestCase):
self.bd_add_del(1, is_add=0)
def test_l2bd_arp_term_06(self):
- """ L2BD arp/ND term - hosts with both ip4/ip6
- """
+ """L2BD arp/ND term - hosts with both ip4/ip6"""
src_host4 = self.ip4_host(50, 50, "00:00:11:22:33:44")
src_host6 = self.ip6_host(50, 50, "00:00:11:22:33:44")
self.bd_add_del(1, is_add=1)
# enable flood to make sure requests are not flooded
- self.set_bd_flags(1, arp_term=True, flood=True,
- uu_flood=False, learn=False)
+ self.set_bd_flags(1, arp_term=True, flood=True, uu_flood=False, learn=False)
macs = self.mac_list(range(10, 20))
hosts6 = self.ip6_hosts(5, 1, macs)
hosts4 = self.ip4_hosts(5, 1, macs)
@@ -355,12 +361,10 @@ class TestL2bdArpTerm(VppTestCase):
self.bd_add_del(1, is_add=0)
def test_l2bd_arp_term_07(self):
- """ L2BD ND term - Add and Del hosts, verify ND replies
- """
+ """L2BD ND term - Add and Del hosts, verify ND replies"""
src_host6 = self.ip6_host(50, 50, "00:00:11:22:33:44")
self.bd_add_del(1, is_add=1)
- self.set_bd_flags(1, arp_term=True, flood=False,
- uu_flood=False, learn=False)
+ self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False)
macs = self.mac_list(range(10, 20))
hosts6 = self.ip6_hosts(5, 1, macs)
self.add_del_arp_term_hosts(hosts6, is_add=1, is_ipv6=1)
@@ -372,12 +376,10 @@ class TestL2bdArpTerm(VppTestCase):
self.bd_add_del(1, is_add=0)
def test_l2bd_arp_term_08(self):
- """ L2BD ND term - Add and update IP+mac, verify ND replies
- """
+ """L2BD ND term - Add and update IP+mac, verify ND replies"""
src_host = self.ip6_host(50, 50, "00:00:11:22:33:44")
self.bd_add_del(1, is_add=1)
- self.set_bd_flags(1, arp_term=True, flood=False,
- uu_flood=False, learn=False)
+ self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False)
macs1 = self.mac_list(range(10, 20))
hosts = self.ip6_hosts(5, 1, macs1)
self.add_del_arp_term_hosts(hosts, is_add=1, is_ipv6=1)
@@ -389,12 +391,10 @@ class TestL2bdArpTerm(VppTestCase):
self.bd_add_del(1, is_add=0)
def test_l2bd_arp_term_09(self):
- """ L2BD arp term - send garps, verify arp event reports
- """
+ """L2BD arp term - send garps, verify arp event reports"""
self.vapi.want_l2_arp_term_events(enable=1)
self.bd_add_del(1, is_add=1)
- self.set_bd_flags(1, arp_term=True, flood=False,
- uu_flood=False, learn=False)
+ self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False)
macs = self.mac_list(range(90, 95))
hosts = self.ip4_hosts(5, 1, macs)
@@ -403,14 +403,14 @@ class TestL2bdArpTerm(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- evs = [self.vapi.wait_for_event(1, "l2_arp_term_event")
- for i in range(len(hosts))]
+ evs = [
+ self.vapi.wait_for_event(1, "l2_arp_term_event") for i in range(len(hosts))
+ ]
ev_hosts = self.arp_event_hosts(evs)
self.assertEqual(len(ev_hosts ^ hosts), 0)
def test_l2bd_arp_term_10(self):
- """ L2BD arp term - send duplicate garps, verify suppression
- """
+ """L2BD arp term - send duplicate garps, verify suppression"""
macs = self.mac_list(range(70, 71))
hosts = self.ip4_hosts(6, 1, macs)
@@ -421,14 +421,14 @@ class TestL2bdArpTerm(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- evs = [self.vapi.wait_for_event(1, "l2_arp_term_event")
- for i in range(len(hosts))]
+ evs = [
+ self.vapi.wait_for_event(1, "l2_arp_term_event") for i in range(len(hosts))
+ ]
ev_hosts = self.arp_event_hosts(evs)
self.assertEqual(len(ev_hosts ^ hosts), 0)
def test_l2bd_arp_term_11(self):
- """ L2BD arp term - disable ip4 arp events,send garps, verify no events
- """
+ """L2BD arp term - disable ip4 arp events,send garps, verify no events"""
self.vapi.want_l2_arp_term_events(enable=0)
macs = self.mac_list(range(90, 95))
hosts = self.ip4_hosts(5, 1, macs)
@@ -443,13 +443,11 @@ class TestL2bdArpTerm(VppTestCase):
self.bd_add_del(1, is_add=0)
def test_l2bd_arp_term_12(self):
- """ L2BD ND term - send NS packets verify reports
- """
+ """L2BD ND term - send NS packets verify reports"""
self.vapi.want_l2_arp_term_events(enable=1)
dst_host = self.ip6_host(50, 50, "00:00:11:22:33:44")
self.bd_add_del(1, is_add=1)
- self.set_bd_flags(1, arp_term=True, flood=False,
- uu_flood=False, learn=False)
+ self.set_bd_flags(1, arp_term=True, flood=False, uu_flood=False, learn=False)
macs = self.mac_list(range(10, 15))
hosts = self.ip6_hosts(5, 1, macs)
reqs = self.ns_reqs_dst(hosts, dst_host)
@@ -457,14 +455,14 @@ class TestL2bdArpTerm(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- evs = [self.vapi.wait_for_event(2, "l2_arp_term_event")
- for i in range(len(hosts))]
+ evs = [
+ self.vapi.wait_for_event(2, "l2_arp_term_event") for i in range(len(hosts))
+ ]
ev_hosts = self.nd_event_hosts(evs)
self.assertEqual(len(ev_hosts ^ hosts), 0)
def test_l2bd_arp_term_13(self):
- """ L2BD ND term - send duplicate ns, verify suppression
- """
+ """L2BD ND term - send duplicate ns, verify suppression"""
dst_host = self.ip6_host(50, 50, "00:00:11:22:33:44")
macs = self.mac_list(range(16, 17))
hosts = self.ip6_hosts(5, 1, macs)
@@ -473,14 +471,14 @@ class TestL2bdArpTerm(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- evs = [self.vapi.wait_for_event(2, "l2_arp_term_event")
- for i in range(len(hosts))]
+ evs = [
+ self.vapi.wait_for_event(2, "l2_arp_term_event") for i in range(len(hosts))
+ ]
ev_hosts = self.nd_event_hosts(evs)
self.assertEqual(len(ev_hosts ^ hosts), 0)
def test_l2bd_arp_term_14(self):
- """ L2BD ND term - disable ip4 arp events,send ns, verify no events
- """
+ """L2BD ND term - disable ip4 arp events,send ns, verify no events"""
self.vapi.want_l2_arp_term_events(enable=0)
dst_host = self.ip6_host(50, 50, "00:00:11:22:33:44")
macs = self.mac_list(range(10, 15))
@@ -495,5 +493,5 @@ class TestL2bdArpTerm(VppTestCase):
self.bd_add_del(1, is_add=0)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_l2bd_learnlimit.py b/test/test_l2bd_learnlimit.py
index 91740590151..1ae25da2686 100644
--- a/test/test_l2bd_learnlimit.py
+++ b/test/test_l2bd_learnlimit.py
@@ -12,7 +12,7 @@ from util import Host, ppp
class TestL2LearnLimit(VppTestCase):
- """ L2 Learn no limit Test Case """
+ """L2 Learn no limit Test Case"""
@classmethod
def setUpClass(self):
@@ -35,11 +35,15 @@ class TestL2LearnLimit(VppTestCase):
hosts = dict()
swif = pg_if.sw_if_index
- def mac(j): return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j)
+ def mac(j):
+ return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j)
- def ip(j): return "172.%02u.1%02x.%u" % (subnet, swif, j)
+ def ip(j):
+ return "172.%02u.1%02x.%u" % (subnet, swif, j)
+
+ def h(j):
+ return Host(mac(j), ip(j))
- def h(j): return Host(mac(j), ip(j))
hosts[swif] = [h(j) for j in range(n_hosts_per_if)]
return hosts
@@ -56,15 +60,13 @@ class TestL2LearnLimit(VppTestCase):
self.vapi.bridge_flags(bd_id=bd_id, is_set=1, flags=1)
swif = pg_if.sw_if_index
- packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac)
- for host in hosts[swif]]
+ packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) for host in hosts[swif]]
pg_if.add_stream(packets)
self.logger.info("Sending broadcast eth frames for MAC learning")
self.pg_start()
def test_l2bd_learnlimit(self):
- """ L2BD test without learn Limit
- """
+ """L2BD test without learn Limit"""
hosts = self.create_hosts(self.pg_interfaces[0], 20, 1)
self.learn_hosts(self.pg_interfaces[0], 1, hosts)
lfs = self.vapi.l2_fib_table_dump(1)
@@ -78,22 +80,20 @@ class TestL2LearnLimit(VppTestCase):
self.vapi.bridge_domain_add_del(bd_id=1)
self.vapi.bridge_domain_add_del(bd_id=2)
- self.vapi.sw_interface_set_l2_bridge(
- self.pg_interfaces[0].sw_if_index, bd_id=1)
- self.vapi.sw_interface_set_l2_bridge(
- self.pg_interfaces[1].sw_if_index, bd_id=2)
+ self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[0].sw_if_index, bd_id=1)
+ self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[1].sw_if_index, bd_id=2)
def tearDown(self):
super(TestL2LearnLimit, self).tearDown()
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg_interfaces[0].sw_if_index,
- bd_id=1, enable=0)
+ rx_sw_if_index=self.pg_interfaces[0].sw_if_index, bd_id=1, enable=0
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg_interfaces[1].sw_if_index,
- bd_id=2, enable=0)
+ rx_sw_if_index=self.pg_interfaces[1].sw_if_index, bd_id=2, enable=0
+ )
self.vapi.bridge_domain_add_del(bd_id=1, is_add=0)
self.vapi.bridge_domain_add_del(bd_id=2, is_add=0)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_l2bd_learnlimit_bdenabled.py b/test/test_l2bd_learnlimit_bdenabled.py
index 63dc5d10542..0578cedbe4a 100644
--- a/test/test_l2bd_learnlimit_bdenabled.py
+++ b/test/test_l2bd_learnlimit_bdenabled.py
@@ -12,7 +12,7 @@ from util import Host, ppp
class TestL2LearnLimitBdEnable(VppTestCase):
- """ L2 Bridge Domain Learn limit Test Case """
+ """L2 Bridge Domain Learn limit Test Case"""
@classmethod
def setUpClass(self):
@@ -35,11 +35,15 @@ class TestL2LearnLimitBdEnable(VppTestCase):
hosts = dict()
swif = pg_if.sw_if_index
- def mac(j): return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j)
+ def mac(j):
+ return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j)
- def ip(j): return "172.%02u.1%02x.%u" % (subnet, swif, j)
+ def ip(j):
+ return "172.%02u.1%02x.%u" % (subnet, swif, j)
+
+ def h(j):
+ return Host(mac(j), ip(j))
- def h(j): return Host(mac(j), ip(j))
hosts[swif] = [h(j) for j in range(n_hosts_per_if)]
return hosts
@@ -56,20 +60,17 @@ class TestL2LearnLimitBdEnable(VppTestCase):
self.vapi.bridge_flags(bd_id=bd_id, is_set=1, flags=1)
swif = pg_if.sw_if_index
- packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac)
- for host in hosts[swif]]
+ packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) for host in hosts[swif]]
pg_if.add_stream(packets)
self.logger.info("Sending broadcast eth frames for MAC learning")
self.pg_start()
def test_l2bd_learnlimit(self):
- """ L2BD test with bridge domain limit
- """
+ """L2BD test with bridge domain limit"""
self.vapi.want_l2_macs_events(enable_disable=1, learn_limit=1000)
self.vapi.bridge_domain_set_default_learn_limit(4)
self.vapi.bridge_domain_add_del(bd_id=3)
- self.vapi.sw_interface_set_l2_bridge(
- self.pg_interfaces[2].sw_if_index, bd_id=3)
+ self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[2].sw_if_index, bd_id=3)
self.vapi.bridge_domain_set_learn_limit(2, 5)
@@ -92,8 +93,8 @@ class TestL2LearnLimitBdEnable(VppTestCase):
self.assertEqual(len(lfs2), 4)
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg_interfaces[2].sw_if_index,
- bd_id=3, enable=0)
+ rx_sw_if_index=self.pg_interfaces[2].sw_if_index, bd_id=3, enable=0
+ )
self.vapi.bridge_domain_add_del(is_add=0, bd_id=3)
def setUp(self):
@@ -102,22 +103,20 @@ class TestL2LearnLimitBdEnable(VppTestCase):
self.vapi.bridge_domain_add_del(bd_id=1)
self.vapi.bridge_domain_add_del(bd_id=2)
- self.vapi.sw_interface_set_l2_bridge(
- self.pg_interfaces[0].sw_if_index, bd_id=1)
- self.vapi.sw_interface_set_l2_bridge(
- self.pg_interfaces[1].sw_if_index, bd_id=2)
+ self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[0].sw_if_index, bd_id=1)
+ self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[1].sw_if_index, bd_id=2)
def tearDown(self):
super(TestL2LearnLimitBdEnable, self).tearDown()
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg_interfaces[0].sw_if_index,
- bd_id=1, enable=0)
+ rx_sw_if_index=self.pg_interfaces[0].sw_if_index, bd_id=1, enable=0
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg_interfaces[1].sw_if_index,
- bd_id=2, enable=0)
+ rx_sw_if_index=self.pg_interfaces[1].sw_if_index, bd_id=2, enable=0
+ )
self.vapi.bridge_domain_add_del(bd_id=1, is_add=0)
self.vapi.bridge_domain_add_del(bd_id=2, is_add=0)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_l2bd_learnlimit_enabled.py b/test/test_l2bd_learnlimit_enabled.py
index 5fcd54cb8f2..8bb3b4029b0 100644
--- a/test/test_l2bd_learnlimit_enabled.py
+++ b/test/test_l2bd_learnlimit_enabled.py
@@ -12,7 +12,7 @@ from util import Host, ppp
class TestL2LearnLimitEnable(VppTestCase):
- """ L2 Global Learn limit Test Case """
+ """L2 Global Learn limit Test Case"""
@classmethod
def setUpClass(self):
@@ -35,11 +35,15 @@ class TestL2LearnLimitEnable(VppTestCase):
hosts = dict()
swif = pg_if.sw_if_index
- def mac(j): return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j)
+ def mac(j):
+ return "00:00:%02x:ff:%02x:%02x" % (subnet, swif, j)
- def ip(j): return "172.%02u.1%02x.%u" % (subnet, swif, j)
+ def ip(j):
+ return "172.%02u.1%02x.%u" % (subnet, swif, j)
+
+ def h(j):
+ return Host(mac(j), ip(j))
- def h(j): return Host(mac(j), ip(j))
hosts[swif] = [h(j) for j in range(n_hosts_per_if)]
return hosts
@@ -56,15 +60,13 @@ class TestL2LearnLimitEnable(VppTestCase):
self.vapi.bridge_flags(bd_id=bd_id, is_set=1, flags=1)
swif = pg_if.sw_if_index
- packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac)
- for host in hosts[swif]]
+ packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) for host in hosts[swif]]
pg_if.add_stream(packets)
self.logger.info("Sending broadcast eth frames for MAC learning")
self.pg_start()
def test_l2bd_learnlimit01(self):
- """ L2BD test with learn Limit
- """
+ """L2BD test with learn Limit"""
self.vapi.want_l2_macs_events(enable_disable=1, learn_limit=10)
hosts = self.create_hosts(self.pg_interfaces[0], 20, 1)
fhosts = self.create_hosts(self.pg_interfaces[1], 1, 2)
@@ -90,22 +92,20 @@ class TestL2LearnLimitEnable(VppTestCase):
self.vapi.bridge_domain_add_del(bd_id=1)
self.vapi.bridge_domain_add_del(bd_id=2)
- self.vapi.sw_interface_set_l2_bridge(
- self.pg_interfaces[0].sw_if_index, bd_id=1)
- self.vapi.sw_interface_set_l2_bridge(
- self.pg_interfaces[1].sw_if_index, bd_id=2)
+ self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[0].sw_if_index, bd_id=1)
+ self.vapi.sw_interface_set_l2_bridge(self.pg_interfaces[1].sw_if_index, bd_id=2)
def tearDown(self):
super(TestL2LearnLimitEnable, self).tearDown()
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg_interfaces[0].sw_if_index,
- bd_id=1, enable=0)
+ rx_sw_if_index=self.pg_interfaces[0].sw_if_index, bd_id=1, enable=0
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg_interfaces[1].sw_if_index,
- bd_id=2, enable=0)
+ rx_sw_if_index=self.pg_interfaces[1].sw_if_index, bd_id=2, enable=0
+ )
self.vapi.bridge_domain_add_del(bd_id=1, is_add=0)
self.vapi.bridge_domain_add_del(bd_id=2, is_add=0)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_l2bd_multi_instance.py b/test/test_l2bd_multi_instance.py
index c4692d686b0..1266afcb690 100644
--- a/test/test_l2bd_multi_instance.py
+++ b/test/test_l2bd_multi_instance.py
@@ -74,7 +74,7 @@ from util import Host, ppp
class TestL2bdMultiInst(VppTestCase):
- """ L2BD Multi-instance Test Case """
+ """L2BD Multi-instance Test Case"""
@classmethod
def setUpClass(cls):
@@ -98,9 +98,9 @@ class TestL2bdMultiInst(VppTestCase):
bd_ifs = cls.bd_if_range(b + 1)
for j in bd_ifs:
cls.flows[cls.pg_interfaces[j]] = [
- cls.pg_interfaces[x] for x in bd_ifs if x != j]
- assert(
- len(cls.flows[cls.pg_interfaces[j]]) == ifs_per_bd - 1)
+ cls.pg_interfaces[x] for x in bd_ifs if x != j
+ ]
+ assert len(cls.flows[cls.pg_interfaces[j]]) == ifs_per_bd - 1
# Mapping between packet-generator index and lists of test hosts
cls.hosts_by_pg_idx = dict()
@@ -158,12 +158,16 @@ class TestL2bdMultiInst(VppTestCase):
addresses for.
"""
c = hosts_per_if
- assert(not cls.hosts_by_pg_idx)
+ assert not cls.hosts_by_pg_idx
for i in range(len(cls.pg_interfaces)):
pg_idx = cls.pg_interfaces[i].sw_if_index
- cls.hosts_by_pg_idx[pg_idx] = [Host(
- "00:00:00:ff:%02x:%02x" % (pg_idx, j + 1),
- "172.17.1%02u.%u" % (pg_idx, j + 1)) for j in range(c)]
+ cls.hosts_by_pg_idx[pg_idx] = [
+ Host(
+ "00:00:00:ff:%02x:%02x" % (pg_idx, j + 1),
+ "172.17.1%02u.%u" % (pg_idx, j + 1),
+ )
+ for j in range(c)
+ ]
@classmethod
def bd_if_range(cls, b):
@@ -191,13 +195,16 @@ class TestL2bdMultiInst(VppTestCase):
for j in self.bd_if_range(b):
pg_if = self.pg_interfaces[j]
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=pg_if.sw_if_index, bd_id=b)
- self.logger.info("pg-interface %s added to bridge domain ID %d"
- % (pg_if.name, b))
+ rx_sw_if_index=pg_if.sw_if_index, bd_id=b
+ )
+ self.logger.info(
+ "pg-interface %s added to bridge domain ID %d" % (pg_if.name, b)
+ )
self.pg_in_bd.append(pg_if)
hosts = self.hosts_by_pg_idx[pg_if.sw_if_index]
- packets = [Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac)
- for host in hosts]
+ packets = [
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac) for host in hosts
+ ]
pg_if.add_stream(packets)
self.logger.info("Sending broadcast eth frames for MAC learning")
self.pg_start()
@@ -216,7 +223,8 @@ class TestL2bdMultiInst(VppTestCase):
for j in self.bd_if_range(b):
pg_if = self.pg_interfaces[j]
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=pg_if.sw_if_index, bd_id=b, enable=0)
+ rx_sw_if_index=pg_if.sw_if_index, bd_id=b, enable=0
+ )
self.pg_in_bd.remove(pg_if)
self.vapi.bridge_domain_add_del(bd_id=b, is_add=0)
self.bd_list.remove(b)
@@ -240,16 +248,20 @@ class TestL2bdMultiInst(VppTestCase):
pkt_info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(pkt_info)
src_host = random.choice(src_hosts)
- p = (Ether(dst=dst_host.mac, src=src_host.mac) /
- IP(src=src_host.ip4, dst=dst_host.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=dst_host.mac, src=src_host.mac)
+ / IP(src=src_host.ip4, dst=dst_host.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
pkt_info.data = p.copy()
size = random.choice(packet_sizes)
self.extend_packet(p, size)
pkts.append(p)
- self.logger.debug("Input stream created for port %s. Length: %u pkt(s)"
- % (src_if.name, len(pkts)))
+ self.logger.debug(
+ "Input stream created for port %s. Length: %u pkt(s)"
+ % (src_if.name, len(pkts))
+ )
return pkts
def verify_capture(self, dst_if):
@@ -268,10 +280,13 @@ class TestL2bdMultiInst(VppTestCase):
udp = packet[UDP]
info = self.payload_to_info(packet[Raw])
self.assertEqual(info.dst, dst)
- self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
- (dst_if.name, info.src, info.index))
+ self.logger.debug(
+ "Got packet on port %s: src=%u (id=%u)"
+ % (dst_if.name, info.src, info.index)
+ )
last_info[info.src] = self.get_next_packet_info_for_interface2(
- info.src, dst, last_info[info.src])
+ info.src, dst, last_info[info.src]
+ )
pkt_info = last_info[info.src]
self.assertTrue(pkt_info is not None)
self.assertEqual(info.index, pkt_info.index)
@@ -288,10 +303,13 @@ class TestL2bdMultiInst(VppTestCase):
remaining = 0
for src in self.flows[dst_if]:
remaining_packet = self.get_next_packet_info_for_interface2(
- src.sw_if_index, dst, last_info[src.sw_if_index])
+ src.sw_if_index, dst, last_info[src.sw_if_index]
+ )
if remaining_packet is None:
- s += "Port %u: Packet expected from source %u didn't arrive\n"\
- % (dst, src.sw_if_index)
+ s += "Port %u: Packet expected from source %u didn't arrive\n" % (
+ dst,
+ src.sw_if_index,
+ )
remaining += 1
self.assertNotEqual(0, remaining, s)
@@ -319,8 +337,7 @@ class TestL2bdMultiInst(VppTestCase):
else:
raise ValueError("Unknown feature used: %s" % flag)
is_set = 1 if args[flag] else 0
- self.vapi.bridge_flags(bd_id=bd_id, is_set=is_set,
- flags=feature_bitmap)
+ self.vapi.bridge_flags(bd_id=bd_id, is_set=is_set, flags=feature_bitmap)
self.logger.info("Bridge domain ID %d updated" % bd_id)
def verify_bd(self, bd_id, **args):
@@ -376,7 +393,7 @@ class TestL2bdMultiInst(VppTestCase):
# Test
# Create incoming packet streams for packet-generator interfaces
# for pg_if in self.pg_interfaces:
- assert(len(self._packet_count_for_dst_if_idx) == 0)
+ assert len(self._packet_count_for_dst_if_idx) == 0
for pg_if in self.pg_in_bd:
pkts = self.create_stream(pg_if)
pg_if.add_stream(pkts)
@@ -391,8 +408,7 @@ class TestL2bdMultiInst(VppTestCase):
self.verify_capture(pg_if)
def test_l2bd_inst_01(self):
- """ L2BD Multi-instance test 1 - create 5 BDs
- """
+ """L2BD Multi-instance test 1 - create 5 BDs"""
# Config 1
# Create 5 BDs, put interfaces to these BDs and send MAC learning
# packets
@@ -408,13 +424,13 @@ class TestL2bdMultiInst(VppTestCase):
self.delete_bd(5)
def test_l2bd_inst_02(self):
- """ L2BD Multi-instance test 2 - update data of 5 BDs
- """
+ """L2BD Multi-instance test 2 - update data of 5 BDs"""
# Config 2
# Update data of 5 BDs (disable learn, forward, flood, uu-flood)
self.create_bd_and_mac_learn(5)
- self.set_bd_flags(self.bd_list[0], learn=False, forward=False,
- flood=False, uu_flood=False)
+ self.set_bd_flags(
+ self.bd_list[0], learn=False, forward=False, flood=False, uu_flood=False
+ )
self.set_bd_flags(self.bd_list[1], forward=False)
self.set_bd_flags(self.bd_list[2], flood=False)
self.set_bd_flags(self.bd_list[3], uu_flood=False)
@@ -423,21 +439,25 @@ class TestL2bdMultiInst(VppTestCase):
# Verify 2
# Skipping check of uu_flood as it is not returned by
# bridge_domain_dump api command
- self.verify_bd(self.bd_list[0], learn=False, forward=False,
- flood=False, uu_flood=False)
- self.verify_bd(self.bd_list[1], learn=True, forward=False,
- flood=True, uu_flood=True)
- self.verify_bd(self.bd_list[2], learn=True, forward=True,
- flood=False, uu_flood=True)
- self.verify_bd(self.bd_list[3], learn=True, forward=True,
- flood=True, uu_flood=False)
- self.verify_bd(self.bd_list[4], learn=False, forward=True,
- flood=True, uu_flood=True)
+ self.verify_bd(
+ self.bd_list[0], learn=False, forward=False, flood=False, uu_flood=False
+ )
+ self.verify_bd(
+ self.bd_list[1], learn=True, forward=False, flood=True, uu_flood=True
+ )
+ self.verify_bd(
+ self.bd_list[2], learn=True, forward=True, flood=False, uu_flood=True
+ )
+ self.verify_bd(
+ self.bd_list[3], learn=True, forward=True, flood=True, uu_flood=False
+ )
+ self.verify_bd(
+ self.bd_list[4], learn=False, forward=True, flood=True, uu_flood=True
+ )
self.delete_bd(5)
def test_l2bd_inst_03(self):
- """ L2BD Multi-instance test 3 - delete 2 BDs
- """
+ """L2BD Multi-instance test 3 - delete 2 BDs"""
# Config 3
# Delete 2 BDs
self.create_bd_and_mac_learn(5)
@@ -454,8 +474,7 @@ class TestL2bdMultiInst(VppTestCase):
self.delete_bd(3, 3)
def test_l2bd_inst_04(self):
- """ L2BD Multi-instance test 4 - add 2 BDs
- """
+ """L2BD Multi-instance test 4 - add 2 BDs"""
# Config 4
# Create 5 BDs, put interfaces to these BDs and send MAC learning
# packets
@@ -471,8 +490,7 @@ class TestL2bdMultiInst(VppTestCase):
self.delete_bd(2)
def test_l2bd_inst_05(self):
- """ L2BD Multi-instance test 5 - delete 5 BDs
- """
+ """L2BD Multi-instance test 5 - delete 5 BDs"""
# Config 5
# Delete 5 BDs
self.create_bd_and_mac_learn(5)
@@ -485,5 +503,5 @@ class TestL2bdMultiInst(VppTestCase):
self.assertEqual(self.verify_bd(bd_id), 1)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_l2tp.py b/test/test_l2tp.py
index 5a665238260..13fa02ecc2c 100644
--- a/test/test_l2tp.py
+++ b/test/test_l2tp.py
@@ -11,7 +11,7 @@ from framework import VppTestCase
@tag_fixme_vpp_workers
class TestL2tp(VppTestCase):
- """ L2TP Test Case """
+ """L2TP Test Case"""
@classmethod
def setUpClass(cls):
@@ -22,28 +22,32 @@ class TestL2tp(VppTestCase):
cls.pg0.config_ip6()
def test_l2tp_decap_local(self):
- """ L2TP don't accept packets unless configured """
+ """L2TP don't accept packets unless configured"""
- pkt = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=115))
+ pkt = Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) / IPv6(
+ src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=115
+ )
self.pg0.add_stream(pkt)
self.pg_start()
# l2tp should not accept packets
err = self.statistics.get_counter(
- '/err/l2tp-decap-local/l2tpv3 session not found')[0]
+ "/err/l2tp-decap-local/l2tpv3 session not found"
+ )[0]
self.assertEqual(err, 0)
err_count = err
- self.vapi.l2tpv3_create_tunnel(client_address=self.pg0.local_ip6,
- our_address=self.pg0.remote_ip6)
+ self.vapi.l2tpv3_create_tunnel(
+ client_address=self.pg0.local_ip6, our_address=self.pg0.remote_ip6
+ )
self.pg0.add_stream(pkt)
self.pg_start()
# l2tp accepts packets
err = self.statistics.get_counter(
- '/err/l2tp-decap-local/l2tpv3 session not found')[0]
+ "/err/l2tp-decap-local/l2tpv3 session not found"
+ )[0]
self.assertEqual(err, 1)
err_count = err
diff --git a/test/test_l2xc.py b/test/test_l2xc.py
index bc653f0b4fb..eba349a2a0f 100644
--- a/test/test_l2xc.py
+++ b/test/test_l2xc.py
@@ -12,7 +12,7 @@ from util import Host, ppp
class TestL2xc(VppTestCase):
- """ L2XC Test Case """
+ """L2XC Test Case"""
@classmethod
def setUpClass(cls):
@@ -52,15 +52,19 @@ class TestL2xc(VppTestCase):
# Create bi-directional cross-connects between pg0 and pg1
cls.vapi.sw_interface_set_l2_xconnect(
- cls.pg0.sw_if_index, cls.pg1.sw_if_index, enable=1)
+ cls.pg0.sw_if_index, cls.pg1.sw_if_index, enable=1
+ )
cls.vapi.sw_interface_set_l2_xconnect(
- cls.pg1.sw_if_index, cls.pg0.sw_if_index, enable=1)
+ cls.pg1.sw_if_index, cls.pg0.sw_if_index, enable=1
+ )
# Create bi-directional cross-connects between pg2 and pg3
cls.vapi.sw_interface_set_l2_xconnect(
- cls.pg2.sw_if_index, cls.pg3.sw_if_index, enable=1)
+ cls.pg2.sw_if_index, cls.pg3.sw_if_index, enable=1
+ )
cls.vapi.sw_interface_set_l2_xconnect(
- cls.pg3.sw_if_index, cls.pg2.sw_if_index, enable=1)
+ cls.pg3.sw_if_index, cls.pg2.sw_if_index, enable=1
+ )
# mapping between packet-generator index and lists of test hosts
cls.hosts_by_pg_idx = dict()
@@ -108,7 +112,8 @@ class TestL2xc(VppTestCase):
for j in range(0, count):
host = Host(
"00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j),
- "172.17.1%02x.%u" % (pg_if.sw_if_index, j))
+ "172.17.1%02x.%u" % (pg_if.sw_if_index, j),
+ )
hosts.append(host)
def create_stream(self, src_if, packet_sizes, packets_per_burst):
@@ -127,10 +132,12 @@ class TestL2xc(VppTestCase):
src_host = random.choice(self.hosts_by_pg_idx[src_if.sw_if_index])
pkt_info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(pkt_info)
- p = (Ether(dst=dst_host.mac, src=src_host.mac) /
- IP(src=src_host.ip4, dst=dst_host.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=dst_host.mac, src=src_host.mac)
+ / IP(src=src_host.ip4, dst=dst_host.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
pkt_info.data = p.copy()
size = random.choice(packet_sizes)
self.extend_packet(p, size)
@@ -155,11 +162,13 @@ class TestL2xc(VppTestCase):
payload_info = self.payload_to_info(packet[Raw])
packet_index = payload_info.index
self.assertEqual(payload_info.dst, dst_sw_if_index)
- self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
- (pg_if.name, payload_info.src, packet_index))
+ self.logger.debug(
+ "Got packet on port %s: src=%u (id=%u)"
+ % (pg_if.name, payload_info.src, packet_index)
+ )
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
self.assertEqual(packet_index, next_info.index)
@@ -174,18 +183,20 @@ class TestL2xc(VppTestCase):
raise
for i in self.interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i, dst_sw_if_index, last_info[i.sw_if_index])
- self.assertTrue(remaining_packet is None,
- "Port %u: Packet expected from source %u didn't"
- " arrive" % (dst_sw_if_index, i.sw_if_index))
+ i, dst_sw_if_index, last_info[i.sw_if_index]
+ )
+ self.assertTrue(
+ remaining_packet is None,
+ "Port %u: Packet expected from source %u didn't"
+ " arrive" % (dst_sw_if_index, i.sw_if_index),
+ )
def run_l2xc_test(self, pkts_per_burst):
- """ L2XC test """
+ """L2XC test"""
# Create incoming packet streams for packet-generator interfaces
for i in self.interfaces:
- pkts = self.create_stream(i, self.pg_if_packet_sizes,
- pkts_per_burst)
+ pkts = self.create_stream(i, self.pg_if_packet_sizes, pkts_per_burst)
i.add_stream(pkts)
# Enable packet capturing and start packet sending
@@ -199,7 +210,7 @@ class TestL2xc(VppTestCase):
self.verify_capture(i, capture)
def test_l2xc_sl(self):
- """ L2XC single-loop test
+ """L2XC single-loop test
Test scenario:
1. config
@@ -213,7 +224,7 @@ class TestL2xc(VppTestCase):
self.run_l2xc_test(self.sl_pkts_per_burst)
def test_l2xc_dl(self):
- """ L2XC dual-loop test
+ """L2XC dual-loop test
Test scenario:
1. config
@@ -227,5 +238,5 @@ class TestL2xc(VppTestCase):
self.run_l2xc_test(self.dl_pkts_per_burst)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_l2xc_multi_instance.py b/test/test_l2xc_multi_instance.py
index 2a6e41c8791..801951657af 100644
--- a/test/test_l2xc_multi_instance.py
+++ b/test/test_l2xc_multi_instance.py
@@ -63,7 +63,7 @@ from util import Host, ppp
class TestL2xcMultiInst(VppTestCase):
- """ L2XC Multi-instance Test Case """
+ """L2XC Multi-instance Test Case"""
@classmethod
def setUpClass(cls):
@@ -82,8 +82,7 @@ class TestL2xcMultiInst(VppTestCase):
cls.flows = dict()
for i in range(len(cls.pg_interfaces)):
delta = 1 if i % 2 == 0 else -1
- cls.flows[cls.pg_interfaces[i]] =\
- [cls.pg_interfaces[i + delta]]
+ cls.flows[cls.pg_interfaces[i]] = [cls.pg_interfaces[i + delta]]
# Mapping between packet-generator index and lists of test hosts
cls.hosts_by_pg_idx = dict()
@@ -151,7 +150,8 @@ class TestL2xcMultiInst(VppTestCase):
for j in range(start_nr, end_nr):
host = Host(
"00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j),
- "172.17.1%02u.%u" % (pg_if.sw_if_index, j))
+ "172.17.1%02u.%u" % (pg_if.sw_if_index, j),
+ )
hosts.append(host)
def create_xconnects(self, count, start=0):
@@ -167,10 +167,12 @@ class TestL2xcMultiInst(VppTestCase):
rx_if = self.pg_interfaces[i + start]
delta = 1 if i % 2 == 0 else -1
tx_if = self.pg_interfaces[i + start + delta]
- self.vapi.sw_interface_set_l2_xconnect(rx_if.sw_if_index,
- tx_if.sw_if_index, 1)
- self.logger.info("Cross-connect from %s to %s created"
- % (tx_if.name, rx_if.name))
+ self.vapi.sw_interface_set_l2_xconnect(
+ rx_if.sw_if_index, tx_if.sw_if_index, 1
+ )
+ self.logger.info(
+ "Cross-connect from %s to %s created" % (tx_if.name, rx_if.name)
+ )
if self.pg_in_xc.count(rx_if) == 0:
self.pg_in_xc.append(rx_if)
if self.pg_not_in_xc.count(rx_if) == 1:
@@ -189,10 +191,12 @@ class TestL2xcMultiInst(VppTestCase):
rx_if = self.pg_interfaces[i + start]
delta = 1 if i % 2 == 0 else -1
tx_if = self.pg_interfaces[i + start + delta]
- self.vapi.sw_interface_set_l2_xconnect(rx_if.sw_if_index,
- tx_if.sw_if_index, 0)
- self.logger.info("Cross-connect from %s to %s deleted"
- % (tx_if.name, rx_if.name))
+ self.vapi.sw_interface_set_l2_xconnect(
+ rx_if.sw_if_index, tx_if.sw_if_index, 0
+ )
+ self.logger.info(
+ "Cross-connect from %s to %s deleted" % (tx_if.name, rx_if.name)
+ )
if self.pg_not_in_xc.count(rx_if) == 0:
self.pg_not_in_xc.append(rx_if)
if self.pg_in_xc.count(rx_if) == 1:
@@ -216,16 +220,20 @@ class TestL2xcMultiInst(VppTestCase):
src_host = random.choice(src_hosts)
pkt_info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(pkt_info)
- p = (Ether(dst=dst_host.mac, src=src_host.mac) /
- IP(src=src_host.ip4, dst=dst_host.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=dst_host.mac, src=src_host.mac)
+ / IP(src=src_host.ip4, dst=dst_host.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
pkt_info.data = p.copy()
size = random.choice(packet_sizes)
self.extend_packet(p, size)
pkts.append(p)
- self.logger.debug("Input stream created for port %s. Length: %u pkt(s)"
- % (src_if.name, len(pkts)))
+ self.logger.debug(
+ "Input stream created for port %s. Length: %u pkt(s)"
+ % (src_if.name, len(pkts))
+ )
return pkts
def verify_capture(self, pg_if, capture):
@@ -246,11 +254,13 @@ class TestL2xcMultiInst(VppTestCase):
udp = packet[UDP]
packet_index = payload_info.index
self.assertEqual(payload_info.dst, dst_sw_if_index)
- self.logger.debug("Got packet on port %s: src=%u (id=%u)" %
- (pg_if.name, payload_info.src, packet_index))
+ self.logger.debug(
+ "Got packet on port %s: src=%u (id=%u)"
+ % (pg_if.name, payload_info.src, packet_index)
+ )
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
self.assertTrue(next_info is not None)
self.assertEqual(packet_index, next_info.index)
@@ -265,11 +275,13 @@ class TestL2xcMultiInst(VppTestCase):
raise
for i in self.pg_interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i, dst_sw_if_index, last_info[i.sw_if_index])
+ i, dst_sw_if_index, last_info[i.sw_if_index]
+ )
self.assertTrue(
remaining_packet is None,
- "Port %u: Packet expected from source %u didn't arrive" %
- (dst_sw_if_index, i.sw_if_index))
+ "Port %u: Packet expected from source %u didn't arrive"
+ % (dst_sw_if_index, i.sw_if_index),
+ )
def run_verify_test(self):
"""
@@ -299,18 +311,17 @@ class TestL2xcMultiInst(VppTestCase):
# Verify outgoing packet streams per packet-generator interface
for pg_if in self.pg_interfaces:
if pg_if in self.pg_in_xc:
- capture = pg_if.get_capture(
- remark="interface is a cross-connect sink")
+ capture = pg_if.get_capture(remark="interface is a cross-connect sink")
self.verify_capture(pg_if, capture)
elif pg_if in self.pg_not_in_xc:
pg_if.assert_nothing_captured(
- remark="interface is not a cross-connect sink")
+ remark="interface is not a cross-connect sink"
+ )
else:
raise Exception("Unexpected interface: %s" % pg_if.name)
def test_l2xc_inst_01(self):
- """ L2XC Multi-instance test 1 - create 10 cross-connects
- """
+ """L2XC Multi-instance test 1 - create 10 cross-connects"""
# Config 1
# Create 10 cross-connects
self.create_xconnects(10)
@@ -319,8 +330,7 @@ class TestL2xcMultiInst(VppTestCase):
self.run_verify_test()
def test_l2xc_inst_02(self):
- """ L2XC Multi-instance test 2 - delete 4 cross-connects
- """
+ """L2XC Multi-instance test 2 - delete 4 cross-connects"""
# Config 2
# Delete 4 cross-connects
self.delete_xconnects(4)
@@ -329,8 +339,7 @@ class TestL2xcMultiInst(VppTestCase):
self.run_verify_test()
def test_l2xc_inst_03(self):
- """ L2BD Multi-instance 3 - add new 4 cross-connects
- """
+ """L2BD Multi-instance 3 - add new 4 cross-connects"""
# Config 3
# Add new 4 cross-connects
self.create_xconnects(4, start=10)
@@ -339,8 +348,7 @@ class TestL2xcMultiInst(VppTestCase):
self.run_verify_test()
def test_l2xc_inst_04(self):
- """ L2XC Multi-instance test 4 - delete 10 cross-connects
- """
+ """L2XC Multi-instance test 4 - delete 10 cross-connects"""
# Config 4
# Delete 10 cross-connects
self.delete_xconnects(10, start=4)
@@ -349,5 +357,5 @@ class TestL2xcMultiInst(VppTestCase):
self.run_verify_test()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_l3xc.py b/test/test_l3xc.py
index 2bcb6d5ae23..66eb242ff52 100644
--- a/test/test_l3xc.py
+++ b/test/test_l3xc.py
@@ -28,8 +28,7 @@ def find_l3xc(test, sw_if_index, dump_sw_if_index=None):
class VppL3xc(VppObject):
-
- def __init__(self, test, intf, paths, is_ip6=False):
+ def __init__(self, test, intf, paths, is_ip6=False):
self._test = test
self.intf = intf
self.is_ip6 = is_ip6
@@ -41,27 +40,26 @@ class VppL3xc(VppObject):
def add_vpp_config(self):
self._test.vapi.l3xc_update(
l3xc={
- 'is_ip6': self.is_ip6,
- 'sw_if_index': self.intf.sw_if_index,
- 'n_paths': len(self.paths),
- 'paths': self.encoded_paths
- })
+ "is_ip6": self.is_ip6,
+ "sw_if_index": self.intf.sw_if_index,
+ "n_paths": len(self.paths),
+ "paths": self.encoded_paths,
+ }
+ )
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
- self._test.vapi.l3xc_del(
- is_ip6=self.is_ip6,
- sw_if_index=self.intf.sw_if_index)
+ self._test.vapi.l3xc_del(is_ip6=self.is_ip6, sw_if_index=self.intf.sw_if_index)
def query_vpp_config(self):
return find_l3xc(self._test, self.intf.sw_if_index)
def object_id(self):
- return ("l3xc-%d" % self.intf.sw_if_index)
+ return "l3xc-%d" % self.intf.sw_if_index
class TestL3xc(VppTestCase):
- """ L3XC Test Case """
+ """L3XC Test Case"""
@classmethod
def setUpClass(cls):
@@ -91,25 +89,27 @@ class TestL3xc(VppTestCase):
super(TestL3xc, self).tearDown()
def test_l3xc4(self):
- """ IPv4 X-Connect """
+ """IPv4 X-Connect"""
#
# x-connect pg0 to pg1 and pg2 to pg3->5
#
- l3xc_1 = VppL3xc(self, self.pg0,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ l3xc_1 = VppL3xc(
+ self, self.pg0, [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)]
+ )
l3xc_1.add_vpp_config()
- l3xc_2 = VppL3xc(self, self.pg2,
- [VppRoutePath(self.pg3.remote_ip4,
- self.pg3.sw_if_index),
- VppRoutePath(self.pg4.remote_ip4,
- self.pg4.sw_if_index),
- VppRoutePath(self.pg5.remote_ip4,
- self.pg5.sw_if_index)])
+ l3xc_2 = VppL3xc(
+ self,
+ self.pg2,
+ [
+ VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index),
+ VppRoutePath(self.pg4.remote_ip4, self.pg4.sw_if_index),
+ VppRoutePath(self.pg5.remote_ip4, self.pg5.sw_if_index),
+ ],
+ )
l3xc_2.add_vpp_config()
- self.assertTrue(find_l3xc(self, self.pg2.sw_if_index, 0xffffffff))
+ self.assertTrue(find_l3xc(self, self.pg2.sw_if_index, 0xFFFFFFFF))
self.logger.info(self.vapi.cli("sh l3xc"))
@@ -117,26 +117,29 @@ class TestL3xc(VppTestCase):
# fire in packets. If it's forwarded then the L3XC was successful,
# since default routing will drop it
#
- p_1 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
# self.send_and_expect(self.pg0, p_1*NUM_PKTS, self.pg1)
p_2 = []
for ii in range(NUM_PKTS):
- p_2.append(Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1000 + ii, dport=1234) /
- Raw(b'\xa5' * 100))
- self.send_and_expect_load_balancing(self.pg2, p_2,
- [self.pg3, self.pg4, self.pg5])
+ p_2.append(
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1000 + ii, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ self.send_and_expect_load_balancing(
+ self.pg2, p_2, [self.pg3, self.pg4, self.pg5]
+ )
l3xc_2.remove_vpp_config()
self.send_and_assert_no_replies(self.pg2, p_2)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_lacp.py b/test/test_lacp.py
index b5f2dae2cd3..016e8de4d61 100644
--- a/test/test_lacp.py
+++ b/test/test_lacp.py
@@ -12,20 +12,18 @@ from vpp_bond_interface import VppBondInterface
from vpp_papi import VppEnum, MACAddress
bond_mac = "02:02:02:02:02:02"
-lacp_dst_mac = '01:80:c2:00:00:02'
+lacp_dst_mac = "01:80:c2:00:00:02"
LACP_COLLECTION_AND_DISTRIBUTION_STATE = 63
class TestMarker(VppTestCase):
- """LACP Marker Protocol Test Case
-
- """
+ """LACP Marker Protocol Test Case"""
@classmethod
def setUpClass(cls):
super().setUpClass()
# Test variables
- cls.pkts_per_burst = 257 # Number of packets per burst
+ cls.pkts_per_burst = 257 # Number of packets per burst
# create 3 pg interfaces
cls.create_pg_interfaces(range(1))
@@ -50,7 +48,7 @@ class TestMarker(VppTestCase):
self.logger.info(self.vapi.ppcli("show interface"))
def test_marker_request(self):
- """ Marker Request test """
+ """Marker Request test"""
# topology
#
@@ -63,22 +61,21 @@ class TestMarker(VppTestCase):
# +-+ +-+
socket1 = VppSocketFilename(
- self,
- socket_id=1,
- socket_filename="%s/memif.sock1" % self.tempdir)
+ self, socket_id=1, socket_filename="%s/memif.sock1" % self.tempdir
+ )
socket1.add_vpp_config()
socket11 = VppSocketFilename(
- self,
- socket_id=2,
- socket_filename="%s/memif.sock1" % self.tempdir)
+ self, socket_id=2, socket_filename="%s/memif.sock1" % self.tempdir
+ )
socket11.add_vpp_config()
memif1 = VppMemif(
self,
role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_MASTER,
mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
- socket_id=1)
+ socket_id=1,
+ )
memif1.add_vpp_config()
memif1.admin_up()
@@ -86,7 +83,8 @@ class TestMarker(VppTestCase):
self,
role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE,
mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
- socket_id=2)
+ socket_id=2,
+ )
memif11.add_vpp_config()
memif11.admin_up()
@@ -94,14 +92,15 @@ class TestMarker(VppTestCase):
self,
mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP,
use_custom_mac=1,
- mac_address=bond_mac)
+ mac_address=bond_mac,
+ )
bond0.add_vpp_config()
bond0.admin_up()
bond1 = VppBondInterface(
- self,
- mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP)
+ self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP
+ )
bond1.add_vpp_config()
bond1.admin_up()
@@ -113,26 +112,28 @@ class TestMarker(VppTestCase):
self.assertEqual(memif11.wait_for_link_up(10), True)
# verify memif1 in bond0
- intfs = self.vapi.sw_member_interface_dump(
- sw_if_index=bond0.sw_if_index)
+ intfs = self.vapi.sw_member_interface_dump(sw_if_index=bond0.sw_if_index)
for intf in intfs:
self.assertEqual(intf.sw_if_index, memif1.sw_if_index)
# verify memif11 in bond1
- intfs = self.vapi.sw_member_interface_dump(
- sw_if_index=bond1.sw_if_index)
+ intfs = self.vapi.sw_member_interface_dump(sw_if_index=bond1.sw_if_index)
for intf in intfs:
self.assertEqual(intf.sw_if_index, memif11.sw_if_index)
self.vapi.ppcli("trace add memif-input 100")
# create marker request
- marker = (Ether(src=bond_mac, dst=lacp_dst_mac) /
- SlowProtocol() /
- MarkerProtocol(marker_type=1,
- requester_port=1,
- requester_system=bond_mac,
- requester_transaction_id=1))
+ marker = (
+ Ether(src=bond_mac, dst=lacp_dst_mac)
+ / SlowProtocol()
+ / MarkerProtocol(
+ marker_type=1,
+ requester_port=1,
+ requester_system=bond_mac,
+ requester_transaction_id=1,
+ )
+ )
bond1.add_member_vpp_bond_interface(sw_if_index=self.pg0.sw_if_index)
self.pg0.add_stream(marker)
@@ -147,9 +148,7 @@ class TestMarker(VppTestCase):
class TestLACP(VppTestCase):
- """LACP Test Case
-
- """
+ """LACP Test Case"""
@classmethod
def setUpClass(cls):
@@ -173,12 +172,11 @@ class TestLACP(VppTestCase):
intfs = self.vapi.sw_interface_lacp_dump()
all_good = 1
for intf in intfs:
- if ((intf.actor_state !=
- LACP_COLLECTION_AND_DISTRIBUTION_STATE) or
- (intf.partner_state !=
- LACP_COLLECTION_AND_DISTRIBUTION_STATE)):
+ if (intf.actor_state != LACP_COLLECTION_AND_DISTRIBUTION_STATE) or (
+ intf.partner_state != LACP_COLLECTION_AND_DISTRIBUTION_STATE
+ ):
all_good = 0
- if (all_good == 1):
+ if all_good == 1:
return 1
self.sleep(step)
timeout -= step
@@ -187,20 +185,18 @@ class TestLACP(VppTestCase):
def wait_for_member_detach(self, bond, timeout, count, step=1):
while 1:
- intfs = self.vapi.sw_bond_interface_dump(
- sw_if_index=bond.sw_if_index)
+ intfs = self.vapi.sw_bond_interface_dump(sw_if_index=bond.sw_if_index)
for intf in intfs:
- if ((intf.members == count) and
- (intf.active_members == count)):
+ if (intf.members == count) and (intf.active_members == count):
return 1
else:
self.sleep(1)
timeout -= step
- if (timeouut <= 0):
+ if timeouut <= 0:
return 0
def test_lacp_connect(self):
- """ LACP protocol connect test """
+ """LACP protocol connect test"""
# topology
#
@@ -213,34 +209,31 @@ class TestLACP(VppTestCase):
# +-+ +-+
socket1 = VppSocketFilename(
- self,
- socket_id=1,
- socket_filename="%s/memif.sock1" % self.tempdir)
+ self, socket_id=1, socket_filename="%s/memif.sock1" % self.tempdir
+ )
socket1.add_vpp_config()
socket11 = VppSocketFilename(
- self,
- socket_id=2,
- socket_filename="%s/memif.sock1" % self.tempdir)
+ self, socket_id=2, socket_filename="%s/memif.sock1" % self.tempdir
+ )
socket11.add_vpp_config()
socket2 = VppSocketFilename(
- self,
- socket_id=3,
- socket_filename="%s/memif.sock2" % self.tempdir)
+ self, socket_id=3, socket_filename="%s/memif.sock2" % self.tempdir
+ )
socket2.add_vpp_config()
socket22 = VppSocketFilename(
- self,
- socket_id=4,
- socket_filename="%s/memif.sock2" % self.tempdir)
+ self, socket_id=4, socket_filename="%s/memif.sock2" % self.tempdir
+ )
socket22.add_vpp_config()
memif1 = VppMemif(
self,
role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_MASTER,
mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
- socket_id=1)
+ socket_id=1,
+ )
memif1.add_vpp_config()
memif1.admin_up()
@@ -248,7 +241,8 @@ class TestLACP(VppTestCase):
self,
role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE,
mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
- socket_id=2)
+ socket_id=2,
+ )
memif11.add_vpp_config()
memif11.admin_up()
@@ -256,7 +250,8 @@ class TestLACP(VppTestCase):
self,
role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_MASTER,
mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
- socket_id=3)
+ socket_id=3,
+ )
memif2.add_vpp_config()
memif2.admin_up()
@@ -264,7 +259,8 @@ class TestLACP(VppTestCase):
self,
role=VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE,
mode=VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
- socket_id=4)
+ socket_id=4,
+ )
memif12.add_vpp_config()
memif12.admin_up()
@@ -273,14 +269,15 @@ class TestLACP(VppTestCase):
self,
mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP,
use_custom_mac=1,
- mac_address=bond_mac)
+ mac_address=bond_mac,
+ )
bond0.add_vpp_config()
bond0.admin_up()
bond1 = VppBondInterface(
- self,
- mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP)
+ self, mode=VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP
+ )
bond1.add_vpp_config()
bond1.admin_up()
@@ -299,18 +296,14 @@ class TestLACP(VppTestCase):
self.assertEqual(memif12.wait_for_link_up(10), True)
# verify memif1 and memif2 in bond0
- intfs = self.vapi.sw_member_interface_dump(
- sw_if_index=bond0.sw_if_index)
+ intfs = self.vapi.sw_member_interface_dump(sw_if_index=bond0.sw_if_index)
for intf in intfs:
- self.assertIn(
- intf.sw_if_index, (memif1.sw_if_index, memif2.sw_if_index))
+ self.assertIn(intf.sw_if_index, (memif1.sw_if_index, memif2.sw_if_index))
# verify memif11 and memif12 in bond1
- intfs = self.vapi.sw_member_interface_dump(
- sw_if_index=bond1.sw_if_index)
+ intfs = self.vapi.sw_member_interface_dump(sw_if_index=bond1.sw_if_index)
for intf in intfs:
- self.assertIn(
- intf.sw_if_index, (memif11.sw_if_index, memif12.sw_if_index))
+ self.assertIn(intf.sw_if_index, (memif11.sw_if_index, memif12.sw_if_index))
self.assertEqual(intf.is_long_timeout, 0)
self.assertEqual(intf.is_passive, 0)
@@ -319,17 +312,14 @@ class TestLACP(VppTestCase):
intfs = self.vapi.sw_interface_lacp_dump()
for intf in intfs:
- self.assertEqual(
- intf.actor_state, LACP_COLLECTION_AND_DISTRIBUTION_STATE)
- self.assertEqual(
- intf.partner_state, LACP_COLLECTION_AND_DISTRIBUTION_STATE)
+ self.assertEqual(intf.actor_state, LACP_COLLECTION_AND_DISTRIBUTION_STATE)
+ self.assertEqual(intf.partner_state, LACP_COLLECTION_AND_DISTRIBUTION_STATE)
intfs = self.vapi.sw_bond_interface_dump(sw_if_index=0xFFFFFFFF)
for intf in intfs:
self.assertEqual(intf.members, 2)
self.assertEqual(intf.active_members, 2)
- self.assertEqual(
- intf.mode, VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP)
+ self.assertEqual(intf.mode, VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP)
self.logger.info(self.vapi.ppcli("show lacp"))
self.logger.info(self.vapi.ppcli("show lacp details"))
@@ -338,20 +328,17 @@ class TestLACP(VppTestCase):
bond0.detach_vpp_bond_interface(sw_if_index=memif1.sw_if_index)
self.wait_for_member_detach(bond0, timeout=10, count=1)
- intfs = self.vapi.sw_bond_interface_dump(
- sw_if_index=bond0.sw_if_index)
+ intfs = self.vapi.sw_bond_interface_dump(sw_if_index=bond0.sw_if_index)
for intf in intfs:
self.assertEqual(intf.members, 1)
self.assertEqual(intf.active_members, 1)
- self.assertEqual(
- intf.mode, VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP)
+ self.assertEqual(intf.mode, VppEnum.vl_api_bond_mode_t.BOND_API_MODE_LACP)
# detach member memif2
bond0.detach_vpp_bond_interface(sw_if_index=memif2.sw_if_index)
self.wait_for_member_detach(bond0, timeout=10, count=0)
- intfs = self.vapi.sw_bond_interface_dump(
- sw_if_index=bond0.sw_if_index)
+ intfs = self.vapi.sw_bond_interface_dump(sw_if_index=bond0.sw_if_index)
for intf in intfs:
self.assertEqual(intf.members, 0)
self.assertEqual(intf.active_members, 0)
@@ -360,5 +347,5 @@ class TestLACP(VppTestCase):
bond1.remove_vpp_config()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_lb.py b/test/test_lb.py
index fafb87b62d9..dca9ea3f7ef 100644
--- a/test/test_lb.py
+++ b/test/test_lb.py
@@ -32,7 +32,7 @@ from vpp_ip import INVALID_INDEX
class TestLB(VppTestCase):
- """ Load Balancer Test Case """
+ """Load Balancer Test Case"""
@classmethod
def setUpClass(cls):
@@ -53,18 +53,23 @@ class TestLB(VppTestCase):
i.resolve_arp()
i.resolve_ndp()
- dst4 = VppIpRoute(cls, "10.0.0.0", 24,
- [VppRoutePath(cls.pg1.remote_ip4,
- INVALID_INDEX)],
- register=False)
+ dst4 = VppIpRoute(
+ cls,
+ "10.0.0.0",
+ 24,
+ [VppRoutePath(cls.pg1.remote_ip4, INVALID_INDEX)],
+ register=False,
+ )
dst4.add_vpp_config()
- dst6 = VppIpRoute(cls, "2002::", 16,
- [VppRoutePath(cls.pg1.remote_ip6,
- INVALID_INDEX)],
- register=False)
+ dst6 = VppIpRoute(
+ cls,
+ "2002::",
+ 16,
+ [VppRoutePath(cls.pg1.remote_ip6, INVALID_INDEX)],
+ register=False,
+ )
dst6.add_vpp_config()
- cls.vapi.lb_conf(ip4_src_address="39.40.41.42",
- ip6_src_address="2004::1")
+ cls.vapi.lb_conf(ip4_src_address="39.40.41.42", ip6_src_address="2004::1")
except Exception:
super(TestLB, cls).tearDownClass()
raise
@@ -80,13 +85,15 @@ class TestLB(VppTestCase):
self.logger.info(self.vapi.cli("show lb vip verbose"))
def getIPv4Flow(self, id):
- return (IP(dst="90.0.%u.%u" % (id / 255, id % 255),
- src="40.0.%u.%u" % (id / 255, id % 255)) /
- UDP(sport=10000 + id, dport=20000))
+ return IP(
+ dst="90.0.%u.%u" % (id / 255, id % 255),
+ src="40.0.%u.%u" % (id / 255, id % 255),
+ ) / UDP(sport=10000 + id, dport=20000)
def getIPv6Flow(self, id):
- return (IPv6(dst="2001::%u" % (id), src="fd00:f00d:ffff::%u" % (id)) /
- UDP(sport=10000 + id, dport=20000))
+ return IPv6(dst="2001::%u" % (id), src="fd00:f00d:ffff::%u" % (id)) / UDP(
+ sport=10000 + id, dport=20000
+ )
def generatePackets(self, src_if, isv4):
self.reset_packet_infos()
@@ -95,9 +102,9 @@ class TestLB(VppTestCase):
info = self.create_packet_info(src_if, self.pg1)
payload = self.info_to_payload(info)
ip = self.getIPv4Flow(pktid) if isv4 else self.getIPv6Flow(pktid)
- packet = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- ip /
- Raw(payload))
+ packet = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac) / ip / Raw(payload)
+ )
self.extend_packet(packet, 128)
info.data = packet.copy()
pkts.append(packet)
@@ -112,8 +119,9 @@ class TestLB(VppTestCase):
payload_info = self.payload_to_info(inner[Raw])
self.info = self.packet_infos[payload_info.index]
self.assertEqual(payload_info.src, self.pg0.sw_if_index)
- self.assertEqual(scapy.compat.raw(inner),
- scapy.compat.raw(self.info.data[IPver]))
+ self.assertEqual(
+ scapy.compat.raw(inner), scapy.compat.raw(self.info.data[IPver])
+ )
def checkCapture(self, encap, isv4):
self.pg0.assert_nothing_captured()
@@ -125,7 +133,7 @@ class TestLB(VppTestCase):
try:
asid = 0
gre = None
- if (encap == 'gre4'):
+ if encap == "gre4":
ip = p[IP]
asid = int(ip.dst.split(".")[3])
self.assertEqual(ip.version, 4)
@@ -136,7 +144,7 @@ class TestLB(VppTestCase):
self.assertEqual(len(ip.options), 0)
gre = p[GRE]
self.checkInner(gre, isv4)
- elif (encap == 'gre6'):
+ elif encap == "gre6":
ip = p[IPv6]
asid = ip.dst.split(":")
asid = asid[len(asid) - 1]
@@ -147,26 +155,26 @@ class TestLB(VppTestCase):
self.assertEqual(ip.src, "2004::1")
self.assertEqual(
socket.inet_pton(socket.AF_INET6, ip.dst),
- socket.inet_pton(socket.AF_INET6, "2002::%u" % asid)
+ socket.inet_pton(socket.AF_INET6, "2002::%u" % asid),
)
self.assertEqual(ip.nh, 47)
# self.assertEqual(len(ip.options), 0)
gre = GRE(scapy.compat.raw(p[IPv6].payload))
self.checkInner(gre, isv4)
- elif (encap == 'l3dsr'):
+ elif encap == "l3dsr":
ip = p[IP]
asid = int(ip.dst.split(".")[3])
self.assertEqual(ip.version, 4)
self.assertEqual(ip.flags, 0)
self.assertEqual(ip.dst, "10.0.0.%u" % asid)
- self.assertEqual(ip.tos, 0x1c)
+ self.assertEqual(ip.tos, 0x1C)
self.assertEqual(len(ip.options), 0)
self.assert_ip_checksum_valid(p)
if ip.proto == IP_PROTOS.tcp:
self.assert_tcp_checksum_valid(p)
elif ip.proto == IP_PROTOS.udp:
self.assert_udp_checksum_valid(p)
- elif (encap == 'nat4'):
+ elif encap == "nat4":
ip = p[IP]
asid = int(ip.dst.split(".")[3])
self.assertEqual(ip.version, 4)
@@ -176,7 +184,7 @@ class TestLB(VppTestCase):
self.assertEqual(len(ip.options), 0)
udp = p[UDP]
self.assertEqual(udp.dport, 3307)
- elif (encap == 'nat6'):
+ elif encap == "nat6":
ip = p[IPv6]
asid = ip.dst.split(":")
asid = asid[len(asid) - 1]
@@ -186,7 +194,7 @@ class TestLB(VppTestCase):
self.assertEqual(ip.fl, 0)
self.assertEqual(
socket.inet_pton(socket.AF_INET6, ip.dst),
- socket.inet_pton(socket.AF_INET6, "2002::%u" % asid)
+ socket.inet_pton(socket.AF_INET6, "2002::%u" % asid),
)
self.assertEqual(ip.nh, 17)
self.assertGreaterEqual(ip.hlim, 63)
@@ -202,301 +210,268 @@ class TestLB(VppTestCase):
for asid in self.ass:
if load[asid] < int(len(self.packets) / (len(self.ass) * 2)):
self.logger.error(
- "ASS is not balanced: load[%d] = %d" % (asid, load[asid]))
+ "ASS is not balanced: load[%d] = %d" % (asid, load[asid])
+ )
raise Exception("Load Balancer algorithm is biased")
def test_lb_ip4_gre4(self):
- """ Load Balancer IP4 GRE4 on vip case """
+ """Load Balancer IP4 GRE4 on vip case"""
try:
- self.vapi.cli(
- "lb vip 90.0.0.0/8 encap gre4")
+ self.vapi.cli("lb vip 90.0.0.0/8 encap gre4")
for asid in self.ass:
- self.vapi.cli(
- "lb as 90.0.0.0/8 10.0.0.%u"
- % (asid))
+ self.vapi.cli("lb as 90.0.0.0/8 10.0.0.%u" % (asid))
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='gre4', isv4=True)
+ self.checkCapture(encap="gre4", isv4=True)
finally:
for asid in self.ass:
- self.vapi.cli(
- "lb as 90.0.0.0/8 10.0.0.%u del"
- % (asid))
- self.vapi.cli(
- "lb vip 90.0.0.0/8 encap gre4 del")
+ self.vapi.cli("lb as 90.0.0.0/8 10.0.0.%u del" % (asid))
+ self.vapi.cli("lb vip 90.0.0.0/8 encap gre4 del")
self.vapi.cli("test lb flowtable flush")
def test_lb_ip6_gre4(self):
- """ Load Balancer IP6 GRE4 on vip case """
+ """Load Balancer IP6 GRE4 on vip case"""
try:
- self.vapi.cli(
- "lb vip 2001::/16 encap gre4")
+ self.vapi.cli("lb vip 2001::/16 encap gre4")
for asid in self.ass:
- self.vapi.cli(
- "lb as 2001::/16 10.0.0.%u"
- % (asid))
+ self.vapi.cli("lb as 2001::/16 10.0.0.%u" % (asid))
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=False))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='gre4', isv4=False)
+ self.checkCapture(encap="gre4", isv4=False)
finally:
for asid in self.ass:
- self.vapi.cli(
- "lb as 2001::/16 10.0.0.%u del"
- % (asid))
- self.vapi.cli(
- "lb vip 2001::/16 encap gre4 del")
+ self.vapi.cli("lb as 2001::/16 10.0.0.%u del" % (asid))
+ self.vapi.cli("lb vip 2001::/16 encap gre4 del")
self.vapi.cli("test lb flowtable flush")
def test_lb_ip4_gre6(self):
- """ Load Balancer IP4 GRE6 on vip case """
+ """Load Balancer IP4 GRE6 on vip case"""
try:
- self.vapi.cli(
- "lb vip 90.0.0.0/8 encap gre6")
+ self.vapi.cli("lb vip 90.0.0.0/8 encap gre6")
for asid in self.ass:
- self.vapi.cli(
- "lb as 90.0.0.0/8 2002::%u"
- % (asid))
+ self.vapi.cli("lb as 90.0.0.0/8 2002::%u" % (asid))
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='gre6', isv4=True)
+ self.checkCapture(encap="gre6", isv4=True)
finally:
for asid in self.ass:
- self.vapi.cli(
- "lb as 90.0.0.0/8 2002::%u del"
- % (asid))
- self.vapi.cli(
- "lb vip 90.0.0.0/8 encap gre6 del")
+ self.vapi.cli("lb as 90.0.0.0/8 2002::%u del" % (asid))
+ self.vapi.cli("lb vip 90.0.0.0/8 encap gre6 del")
self.vapi.cli("test lb flowtable flush")
def test_lb_ip6_gre6(self):
- """ Load Balancer IP6 GRE6 on vip case """
+ """Load Balancer IP6 GRE6 on vip case"""
try:
- self.vapi.cli(
- "lb vip 2001::/16 encap gre6")
+ self.vapi.cli("lb vip 2001::/16 encap gre6")
for asid in self.ass:
- self.vapi.cli(
- "lb as 2001::/16 2002::%u"
- % (asid))
+ self.vapi.cli("lb as 2001::/16 2002::%u" % (asid))
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=False))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='gre6', isv4=False)
+ self.checkCapture(encap="gre6", isv4=False)
finally:
for asid in self.ass:
- self.vapi.cli(
- "lb as 2001::/16 2002::%u del"
- % (asid))
- self.vapi.cli(
- "lb vip 2001::/16 encap gre6 del")
+ self.vapi.cli("lb as 2001::/16 2002::%u del" % (asid))
+ self.vapi.cli("lb vip 2001::/16 encap gre6 del")
self.vapi.cli("test lb flowtable flush")
def test_lb_ip4_gre4_port(self):
- """ Load Balancer IP4 GRE4 on per-port-vip case """
+ """Load Balancer IP4 GRE4 on per-port-vip case"""
try:
- self.vapi.cli(
- "lb vip 90.0.0.0/8 protocol udp port 20000 encap gre4")
+ self.vapi.cli("lb vip 90.0.0.0/8 protocol udp port 20000 encap gre4")
for asid in self.ass:
self.vapi.cli(
- "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u"
- % (asid))
+ "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u" % (asid)
+ )
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='gre4', isv4=True)
+ self.checkCapture(encap="gre4", isv4=True)
finally:
for asid in self.ass:
self.vapi.cli(
- "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del"
- % (asid))
- self.vapi.cli(
- "lb vip 90.0.0.0/8 protocol udp port 20000 encap gre4 del")
+ "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del" % (asid)
+ )
+ self.vapi.cli("lb vip 90.0.0.0/8 protocol udp port 20000 encap gre4 del")
self.vapi.cli("test lb flowtable flush")
def test_lb_ip6_gre4_port(self):
- """ Load Balancer IP6 GRE4 on per-port-vip case """
+ """Load Balancer IP6 GRE4 on per-port-vip case"""
try:
- self.vapi.cli(
- "lb vip 2001::/16 protocol udp port 20000 encap gre4")
+ self.vapi.cli("lb vip 2001::/16 protocol udp port 20000 encap gre4")
for asid in self.ass:
self.vapi.cli(
- "lb as 2001::/16 protocol udp port 20000 10.0.0.%u"
- % (asid))
+ "lb as 2001::/16 protocol udp port 20000 10.0.0.%u" % (asid)
+ )
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=False))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='gre4', isv4=False)
+ self.checkCapture(encap="gre4", isv4=False)
finally:
for asid in self.ass:
self.vapi.cli(
- "lb as 2001::/16 protocol udp port 20000 10.0.0.%u del"
- % (asid))
- self.vapi.cli(
- "lb vip 2001::/16 protocol udp port 20000 encap gre4 del")
+ "lb as 2001::/16 protocol udp port 20000 10.0.0.%u del" % (asid)
+ )
+ self.vapi.cli("lb vip 2001::/16 protocol udp port 20000 encap gre4 del")
self.vapi.cli("test lb flowtable flush")
def test_lb_ip4_gre6_port(self):
- """ Load Balancer IP4 GRE6 on per-port-vip case """
+ """Load Balancer IP4 GRE6 on per-port-vip case"""
try:
- self.vapi.cli(
- "lb vip 90.0.0.0/8 protocol udp port 20000 encap gre6")
+ self.vapi.cli("lb vip 90.0.0.0/8 protocol udp port 20000 encap gre6")
for asid in self.ass:
self.vapi.cli(
- "lb as 90.0.0.0/8 protocol udp port 20000 2002::%u"
- % (asid))
+ "lb as 90.0.0.0/8 protocol udp port 20000 2002::%u" % (asid)
+ )
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='gre6', isv4=True)
+ self.checkCapture(encap="gre6", isv4=True)
finally:
for asid in self.ass:
self.vapi.cli(
- "lb as 90.0.0.0/8 protocol udp port 20000 2002::%u del"
- % (asid))
- self.vapi.cli(
- "lb vip 90.0.0.0/8 protocol udp port 20000 encap gre6 del")
+ "lb as 90.0.0.0/8 protocol udp port 20000 2002::%u del" % (asid)
+ )
+ self.vapi.cli("lb vip 90.0.0.0/8 protocol udp port 20000 encap gre6 del")
self.vapi.cli("test lb flowtable flush")
def test_lb_ip6_gre6_port(self):
- """ Load Balancer IP6 GRE6 on per-port-vip case """
+ """Load Balancer IP6 GRE6 on per-port-vip case"""
try:
- self.vapi.cli(
- "lb vip 2001::/16 protocol udp port 20000 encap gre6")
+ self.vapi.cli("lb vip 2001::/16 protocol udp port 20000 encap gre6")
for asid in self.ass:
self.vapi.cli(
- "lb as 2001::/16 protocol udp port 20000 2002::%u"
- % (asid))
+ "lb as 2001::/16 protocol udp port 20000 2002::%u" % (asid)
+ )
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=False))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='gre6', isv4=False)
+ self.checkCapture(encap="gre6", isv4=False)
finally:
for asid in self.ass:
self.vapi.cli(
- "lb as 2001::/16 protocol udp port 20000 2002::%u del"
- % (asid))
- self.vapi.cli(
- "lb vip 2001::/16 protocol udp port 20000 encap gre6 del")
+ "lb as 2001::/16 protocol udp port 20000 2002::%u del" % (asid)
+ )
+ self.vapi.cli("lb vip 2001::/16 protocol udp port 20000 encap gre6 del")
self.vapi.cli("test lb flowtable flush")
def test_lb_ip4_l3dsr(self):
- """ Load Balancer IP4 L3DSR on vip case """
+ """Load Balancer IP4 L3DSR on vip case"""
try:
- self.vapi.cli(
- "lb vip 90.0.0.0/8 encap l3dsr dscp 7")
+ self.vapi.cli("lb vip 90.0.0.0/8 encap l3dsr dscp 7")
for asid in self.ass:
- self.vapi.cli(
- "lb as 90.0.0.0/8 10.0.0.%u"
- % (asid))
+ self.vapi.cli("lb as 90.0.0.0/8 10.0.0.%u" % (asid))
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='l3dsr', isv4=True)
+ self.checkCapture(encap="l3dsr", isv4=True)
finally:
for asid in self.ass:
- self.vapi.cli(
- "lb as 90.0.0.0/8 10.0.0.%u del"
- % (asid))
- self.vapi.cli(
- "lb vip 90.0.0.0/8 encap l3dsr"
- " dscp 7 del")
+ self.vapi.cli("lb as 90.0.0.0/8 10.0.0.%u del" % (asid))
+ self.vapi.cli("lb vip 90.0.0.0/8 encap l3dsr dscp 7 del")
self.vapi.cli("test lb flowtable flush")
def test_lb_ip4_l3dsr_port(self):
- """ Load Balancer IP4 L3DSR on per-port-vip case """
+ """Load Balancer IP4 L3DSR on per-port-vip case"""
try:
self.vapi.cli(
- "lb vip 90.0.0.0/8 protocol udp port 20000 encap l3dsr dscp 7")
+ "lb vip 90.0.0.0/8 protocol udp port 20000 encap l3dsr dscp 7"
+ )
for asid in self.ass:
self.vapi.cli(
- "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u"
- % (asid))
+ "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u" % (asid)
+ )
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='l3dsr', isv4=True)
+ self.checkCapture(encap="l3dsr", isv4=True)
finally:
for asid in self.ass:
self.vapi.cli(
- "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del"
- % (asid))
+ "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del" % (asid)
+ )
self.vapi.cli(
- "lb vip 90.0.0.0/8 protocol udp port 20000 encap l3dsr"
- " dscp 7 del")
+ "lb vip 90.0.0.0/8 protocol udp port 20000 encap l3dsr dscp 7 del"
+ )
self.vapi.cli("test lb flowtable flush")
def test_lb_ip4_nat4_port(self):
- """ Load Balancer IP4 NAT4 on per-port-vip case """
+ """Load Balancer IP4 NAT4 on per-port-vip case"""
try:
self.vapi.cli(
"lb vip 90.0.0.0/8 protocol udp port 20000 encap nat4"
- " type clusterip target_port 3307")
+ " type clusterip target_port 3307"
+ )
for asid in self.ass:
self.vapi.cli(
- "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u"
- % (asid))
+ "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u" % (asid)
+ )
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=True))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='nat4', isv4=True)
+ self.checkCapture(encap="nat4", isv4=True)
finally:
for asid in self.ass:
self.vapi.cli(
- "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del"
- % (asid))
+ "lb as 90.0.0.0/8 protocol udp port 20000 10.0.0.%u del" % (asid)
+ )
self.vapi.cli(
"lb vip 90.0.0.0/8 protocol udp port 20000 encap nat4"
- " type clusterip target_port 3307 del")
+ " type clusterip target_port 3307 del"
+ )
self.vapi.cli("test lb flowtable flush")
def test_lb_ip6_nat6_port(self):
- """ Load Balancer IP6 NAT6 on per-port-vip case """
+ """Load Balancer IP6 NAT6 on per-port-vip case"""
try:
self.vapi.cli(
"lb vip 2001::/16 protocol udp port 20000 encap nat6"
- " type clusterip target_port 3307")
+ " type clusterip target_port 3307"
+ )
for asid in self.ass:
self.vapi.cli(
- "lb as 2001::/16 protocol udp port 20000 2002::%u"
- % (asid))
+ "lb as 2001::/16 protocol udp port 20000 2002::%u" % (asid)
+ )
self.pg0.add_stream(self.generatePackets(self.pg0, isv4=False))
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.checkCapture(encap='nat6', isv4=False)
+ self.checkCapture(encap="nat6", isv4=False)
finally:
for asid in self.ass:
self.vapi.cli(
- "lb as 2001::/16 protocol udp port 20000 2002::%u del"
- % (asid))
+ "lb as 2001::/16 protocol udp port 20000 2002::%u del" % (asid)
+ )
self.vapi.cli(
"lb vip 2001::/16 protocol udp port 20000 encap nat6"
- " type clusterip target_port 3307 del")
+ " type clusterip target_port 3307 del"
+ )
self.vapi.cli("test lb flowtable flush")
diff --git a/test/test_lb_api.py b/test/test_lb_api.py
index 70d41d432a7..048f7bf44e8 100644
--- a/test/test_lb_api.py
+++ b/test/test_lb_api.py
@@ -19,7 +19,7 @@ DEFAULT_VIP = "lb_vip_details(_0=978, context=12, vip=vl_api_lb_ip_addr_t(pfx=IP
class TestLbEmptyApi(framework.VppTestCase):
- """TestLbEmptyApi """
+ """TestLbEmptyApi"""
def test_lb_empty_vip_dump(self):
@@ -27,18 +27,18 @@ class TestLbEmptyApi(framework.VppTestCase):
# lb initializes with a default VIP
rv = self.vapi.lb_vip_dump()
# print(rv)
- self.assertEqual(rv, [], 'Expected: [] Received: %r.' % rv)
+ self.assertEqual(rv, [], "Expected: [] Received: %r." % rv)
def test_lb_empty_as_dump(self):
# no records should return []
rv = self.vapi.lb_as_dump()
# print(rv)
- self.assertEqual(rv, [], 'Expected: [] Received: %r.' % rv)
+ self.assertEqual(rv, [], "Expected: [] Received: %r." % rv)
class TestLbApi(framework.VppTestCase):
- """TestLbApi """
+ """TestLbApi"""
def test_lb_vip_dump(self):
# add some vips
@@ -49,14 +49,17 @@ class TestLbApi(framework.VppTestCase):
self.vapi.cli("lb vip 2001::/16 encap gre6")
rv = self.vapi.lb_vip_dump()
# print(rv)
- self.assertEqual(str(rv[-1].vip.pfx), "2001::/16",
- 'Expected: 2001::/16 Received: %r.' % rv[-1].vip.pfx)
+ self.assertEqual(
+ str(rv[-1].vip.pfx),
+ "2001::/16",
+ "Expected: 2001::/16 Received: %r." % rv[-1].vip.pfx,
+ )
self.vapi.cli("lb vip 2001::/16 del")
class TestLbAsApi(framework.VppTestCase):
- """TestLbAsApi """
+ """TestLbAsApi"""
def test_lb_as_dump(self):
# add some vips
@@ -70,7 +73,13 @@ class TestLbAsApi(framework.VppTestCase):
# print(rv)
rv = self.vapi.lb_as_dump()
# print(rv)
- self.assertEqual(str(rv[0].vip.pfx), "2001::/16",
- 'Expected: "2001::/16" Received: %r.' % rv[0].vip.pfx)
- self.assertEqual(str(rv[0].app_srv), "2000::1",
- 'Expected: "2000::1" Received: %r.' % rv[0].app_srv)
+ self.assertEqual(
+ str(rv[0].vip.pfx),
+ "2001::/16",
+ 'Expected: "2001::/16" Received: %r.' % rv[0].vip.pfx,
+ )
+ self.assertEqual(
+ str(rv[0].app_srv),
+ "2000::1",
+ 'Expected: "2000::1" Received: %r.' % rv[0].app_srv,
+ )
diff --git a/test/test_linux_cp.py b/test/test_linux_cp.py
index b683954e1da..2d7669b717a 100644
--- a/test/test_linux_cp.py
+++ b/test/test_linux_cp.py
@@ -10,10 +10,20 @@ from util import reassemble4
from vpp_object import VppObject
from framework import VppTestCase, VppTestRunner
from vpp_ipip_tun_interface import VppIpIpTunInterface
-from template_ipsec import TemplateIpsec, IpsecTun4Tests, \
- IpsecTun4, mk_scapy_crypt_key, config_tun_params
-from template_ipsec import TemplateIpsec, IpsecTun4Tests, \
- IpsecTun4, mk_scapy_crypt_key, config_tun_params
+from template_ipsec import (
+ TemplateIpsec,
+ IpsecTun4Tests,
+ IpsecTun4,
+ mk_scapy_crypt_key,
+ config_tun_params,
+)
+from template_ipsec import (
+ TemplateIpsec,
+ IpsecTun4Tests,
+ IpsecTun4,
+ mk_scapy_crypt_key,
+ config_tun_params,
+)
from test_ipsec_tun_if_esp import TemplateIpsecItf4
from vpp_ipsec import VppIpsecSA, VppIpsecTunProtect, VppIpsecInterface
@@ -25,39 +35,43 @@ class VppLcpPair(VppObject):
self.host = host
def add_vpp_config(self):
- self._test.vapi.cli("test lcp add phy %s host %s" %
- (self.phy, self.host))
+ self._test.vapi.cli("test lcp add phy %s host %s" % (self.phy, self.host))
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
- self._test.vapi.cli("test lcp del phy %s host %s" %
- (self.phy, self.host))
+ self._test.vapi.cli("test lcp del phy %s host %s" % (self.phy, self.host))
def object_id(self):
- return "lcp:%d:%d" % (self.phy.sw_if_index,
- self.host.sw_if_index)
+ return "lcp:%d:%d" % (self.phy.sw_if_index, self.host.sw_if_index)
def query_vpp_config(self):
- pairs = list(self._test.vapi.vpp.details_iter(
- self._test.vapi.lcp_itf_pair_get))
+ pairs = list(self._test.vapi.vpp.details_iter(self._test.vapi.lcp_itf_pair_get))
for p in pairs:
- if p.phy_sw_if_index == self.phy.sw_if_index and \
- p.host_sw_if_index == self.host.sw_if_index:
+ if (
+ p.phy_sw_if_index == self.phy.sw_if_index
+ and p.host_sw_if_index == self.host.sw_if_index
+ ):
return True
return False
class TestLinuxCP(VppTestCase):
- """ Linux Control Plane """
-
- extra_vpp_plugin_config = ["plugin",
- "linux_cp_plugin.so",
- "{", "enable", "}",
- "plugin",
- "linux_cp_unittest_plugin.so",
- "{", "enable", "}"]
+ """Linux Control Plane"""
+
+ extra_vpp_plugin_config = [
+ "plugin",
+ "linux_cp_plugin.so",
+ "{",
+ "enable",
+ "}",
+ "plugin",
+ "linux_cp_unittest_plugin.so",
+ "{",
+ "enable",
+ "}",
+ ]
@classmethod
def setUpClass(cls):
@@ -86,7 +100,7 @@ class TestLinuxCP(VppTestCase):
super(TestLinuxCP, self).tearDown()
def test_linux_cp_tap(self):
- """ Linux CP TAP """
+ """Linux CP TAP"""
#
# Setup
@@ -117,12 +131,12 @@ class TestLinuxCP(VppTestCase):
# hosts to phys
for phy, host in zip(phys, hosts):
for j in range(N_HOSTS):
- p = (Ether(src=phy.local_mac,
- dst=phy.remote_hosts[j].mac) /
- IP(src=phy.local_ip4,
- dst=phy.remote_hosts[j].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(src=phy.local_mac, dst=phy.remote_hosts[j].mac)
+ / IP(src=phy.local_ip4, dst=phy.remote_hosts[j].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
rxs = self.send_and_expect(host, [p], phy)
@@ -131,13 +145,13 @@ class TestLinuxCP(VppTestCase):
self.assertEqual(p.show2(True), rx.show2(True))
# ARPs x-connect to phy
- p = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=phy.remote_hosts[j].mac) /
- ARP(op="who-has",
- hwdst=phy.remote_hosts[j].mac,
- hwsrc=phy.local_mac,
- psrc=phy.local_ip4,
- pdst=phy.remote_hosts[j].ip4))
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=phy.remote_hosts[j].mac) / ARP(
+ op="who-has",
+ hwdst=phy.remote_hosts[j].mac,
+ hwsrc=phy.local_mac,
+ psrc=phy.local_ip4,
+ pdst=phy.remote_hosts[j].ip4,
+ )
rxs = self.send_and_expect(host, [p], phy)
@@ -148,12 +162,12 @@ class TestLinuxCP(VppTestCase):
# phy to host
for phy, host in zip(phys, hosts):
for j in range(N_HOSTS):
- p = (Ether(dst=phy.local_mac,
- src=phy.remote_hosts[j].mac) /
- IP(dst=phy.local_ip4,
- src=phy.remote_hosts[j].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=phy.local_mac, src=phy.remote_hosts[j].mac)
+ / IP(dst=phy.local_ip4, src=phy.remote_hosts[j].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
rxs = self.send_and_expect(phy, [p], host)
@@ -162,13 +176,13 @@ class TestLinuxCP(VppTestCase):
self.assertEqual(p.show2(True), rx.show2(True))
# ARPs rx'd on the phy are sent to the host
- p = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=phy.remote_hosts[j].mac) /
- ARP(op="is-at",
- hwsrc=phy.remote_hosts[j].mac,
- hwdst=phy.local_mac,
- pdst=phy.local_ip4,
- psrc=phy.remote_hosts[j].ip4))
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=phy.remote_hosts[j].mac) / ARP(
+ op="is-at",
+ hwsrc=phy.remote_hosts[j].mac,
+ hwdst=phy.local_mac,
+ pdst=phy.local_ip4,
+ psrc=phy.remote_hosts[j].ip4,
+ )
rxs = self.send_and_expect(phy, [p], host)
@@ -181,7 +195,7 @@ class TestLinuxCP(VppTestCase):
phy.unconfig_ip4()
def test_linux_cp_tun(self):
- """ Linux CP TUN """
+ """Linux CP TUN"""
#
# Setup
@@ -198,15 +212,11 @@ class TestLinuxCP(VppTestCase):
phy.resolve_ndp()
tun4 = VppIpIpTunInterface(
- self,
- phy,
- phy.local_ip4,
- phy.remote_ip4).add_vpp_config()
+ self, phy, phy.local_ip4, phy.remote_ip4
+ ).add_vpp_config()
tun6 = VppIpIpTunInterface(
- self,
- phy,
- phy.local_ip6,
- phy.remote_ip6).add_vpp_config()
+ self, phy, phy.local_ip6, phy.remote_ip6
+ ).add_vpp_config()
tuns = [tun4, tun6]
tun4.admin_up()
@@ -226,9 +236,7 @@ class TestLinuxCP(VppTestCase):
#
# host to phy for v4
- p = (IP(src=tun4.local_ip4, dst="2.2.2.2") /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = IP(src=tun4.local_ip4, dst="2.2.2.2") / UDP(sport=1234, dport=1234) / Raw()
rxs = self.send_and_expect(self.pg4, p * N_PKTS, phy)
@@ -242,9 +250,7 @@ class TestLinuxCP(VppTestCase):
self.assertEqual(inner.dst, "2.2.2.2")
# host to phy for v6
- p = (IPv6(src=tun6.local_ip6, dst="2::2") /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = IPv6(src=tun6.local_ip6, dst="2::2") / UDP(sport=1234, dport=1234) / Raw()
rxs = self.send_and_expect(self.pg5, p * N_PKTS, phy)
@@ -257,11 +263,13 @@ class TestLinuxCP(VppTestCase):
self.assertEqual(inner.dst, "2::2")
# phy to host v4
- p = (Ether(dst=phy.local_mac, src=phy.remote_mac) /
- IP(dst=phy.local_ip4, src=phy.remote_ip4) /
- IP(dst=tun4.local_ip4, src=tun4.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=phy.local_mac, src=phy.remote_mac)
+ / IP(dst=phy.local_ip4, src=phy.remote_ip4)
+ / IP(dst=tun4.local_ip4, src=tun4.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
rxs = self.send_and_expect(phy, p * N_PKTS, self.pg4)
for rx in rxs:
@@ -270,11 +278,13 @@ class TestLinuxCP(VppTestCase):
self.assertEqual(rx[IP].src, tun4.remote_ip4)
# phy to host v6
- p = (Ether(dst=phy.local_mac, src=phy.remote_mac) /
- IPv6(dst=phy.local_ip6, src=phy.remote_ip6) /
- IPv6(dst=tun6.local_ip6, src=tun6.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=phy.local_mac, src=phy.remote_mac)
+ / IPv6(dst=phy.local_ip6, src=phy.remote_ip6)
+ / IPv6(dst=tun6.local_ip6, src=tun6.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
rxs = self.send_and_expect(phy, p * N_PKTS, self.pg5)
for rx in rxs:
@@ -290,17 +300,21 @@ class TestLinuxCP(VppTestCase):
tun6.unconfig_ip6()
-class TestLinuxCPIpsec(TemplateIpsec,
- TemplateIpsecItf4,
- IpsecTun4):
- """ IPsec Interface IPv4 """
+class TestLinuxCPIpsec(TemplateIpsec, TemplateIpsecItf4, IpsecTun4):
+ """IPsec Interface IPv4"""
- extra_vpp_plugin_config = ["plugin",
- "linux_cp_plugin.so",
- "{", "enable", "}",
- "plugin",
- "linux_cp_unittest_plugin.so",
- "{", "enable", "}"]
+ extra_vpp_plugin_config = [
+ "plugin",
+ "linux_cp_plugin.so",
+ "{",
+ "enable",
+ "}",
+ "plugin",
+ "linux_cp_unittest_plugin.so",
+ "{",
+ "enable",
+ "}",
+ ]
def setUp(self):
super(TestLinuxCPIpsec, self).setUp()
@@ -347,16 +361,19 @@ class TestLinuxCPIpsec(TemplateIpsec,
self.assert_equal(rx[IP].dst, p.tun_if.local_ip4)
self.assert_packet_checksums_valid(rx)
- def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1,
- payload_size=54):
- return [Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac) /
- sa.encrypt(IP(src=src, dst=dst) /
- UDP(sport=1111, dport=2222) /
- Raw(b'X' * payload_size))
- for i in range(count)]
+ def gen_encrypt_pkts(self, p, sa, sw_intf, src, dst, count=1, payload_size=54):
+ return [
+ Ether(src=sw_intf.remote_mac, dst=sw_intf.local_mac)
+ / sa.encrypt(
+ IP(src=src, dst=dst)
+ / UDP(sport=1111, dport=2222)
+ / Raw(b"X" * payload_size)
+ )
+ for i in range(count)
+ ]
def test_linux_cp_ipsec4_tun(self):
- """ Linux CP Ipsec TUN """
+ """Linux CP Ipsec TUN"""
#
# Setup
@@ -370,9 +387,7 @@ class TestLinuxCPIpsec(TemplateIpsec,
p = self.ipv4_params
self.config_network(p)
- self.config_sa_tun(p,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ self.config_sa_tun(p, self.pg0.local_ip4, self.pg0.remote_ip4)
self.config_protect(p)
pair = VppLcpPair(self, p.tun_if, self.host).add_vpp_config()
@@ -386,19 +401,24 @@ class TestLinuxCPIpsec(TemplateIpsec,
#
# host to phy for v4
- pkt = (IP(src=p.tun_if.local_ip4,
- dst=p.tun_if.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ pkt = (
+ IP(src=p.tun_if.local_ip4, dst=p.tun_if.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
rxs = self.send_and_expect(self.host, pkt * N_PKTS, self.tun_if)
self.verify_encrypted(p, p.vpp_tun_sa, rxs)
# phy to host for v4
- pkts = self.gen_encrypt_pkts(p, p.scapy_tun_sa, self.tun_if,
- src=p.tun_if.remote_ip4,
- dst=p.tun_if.local_ip4,
- count=N_PKTS)
+ pkts = self.gen_encrypt_pkts(
+ p,
+ p.scapy_tun_sa,
+ self.tun_if,
+ src=p.tun_if.remote_ip4,
+ dst=p.tun_if.local_ip4,
+ count=N_PKTS,
+ )
rxs = self.send_and_expect(self.tun_if, pkts, self.host)
self.verify_decrypted(p, rxs)
@@ -409,5 +429,5 @@ class TestLinuxCPIpsec(TemplateIpsec,
self.unconfig_network(p)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_lisp.py b/test/test_lisp.py
index 0a6e7525159..5ff9de13d24 100644
--- a/test/test_lisp.py
+++ b/test/test_lisp.py
@@ -9,8 +9,14 @@ from scapy.layers.inet import IP, UDP, Ether
from scapy.layers.inet6 import IPv6
from framework import VppTestCase, VppTestRunner
-from lisp import VppLocalMapping, VppLispAdjacency, VppLispLocator, \
- VppLispLocatorSet, VppRemoteMapping, LispRemoteLocator
+from lisp import (
+ VppLocalMapping,
+ VppLispAdjacency,
+ VppLispLocator,
+ VppLispLocatorSet,
+ VppRemoteMapping,
+ LispRemoteLocator,
+)
from util import ppp
# From py_lispnetworking.lisp.py: # GNU General Public License v2.0
@@ -24,6 +30,8 @@ class LISP_GPE_Header(Packet):
ByteField("next_proto", 0),
IntField("iid", 0),
]
+
+
bind_layers(UDP, LISP_GPE_Header, dport=4341)
bind_layers(UDP, LISP_GPE_Header, sport=4341)
bind_layers(LISP_GPE_Header, IP, next_proto=1)
@@ -34,8 +42,8 @@ bind_layers(LISP_GPE_Header, Ether, next_proto=3)
class ForeignAddressFactory(object):
count = 0
prefix_len = 24
- net_template = '10.10.10.{}'
- net = net_template.format(0) + '/' + str(prefix_len)
+ net_template = "10.10.10.{}"
+ net = net_template.format(0) + "/" + str(prefix_len)
def get_ip4(self):
if self.count > 255:
@@ -46,13 +54,16 @@ class ForeignAddressFactory(object):
class Driver(metaclass=abc.ABCMeta):
- config_order = ['locator-sets',
- 'locators',
- 'local-mappings',
- 'remote-mappings',
- 'adjacencies']
+ config_order = [
+ "locator-sets",
+ "locators",
+ "local-mappings",
+ "remote-mappings",
+ "adjacencies",
+ ]
""" Basic class for data driven testing """
+
def __init__(self, test, test_cases):
self._test_cases = test_cases
self._test = test
@@ -65,26 +76,29 @@ class Driver(metaclass=abc.ABCMeta):
def test(self):
return self._test
- def create_packet(self, src_if, dst_if, deid, payload=''):
+ def create_packet(self, src_if, dst_if, deid, payload=""):
"""
Create IPv4 packet
param: src_if
param: dst_if
"""
- packet = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=src_if.remote_ip4, dst=deid) /
- Raw(payload))
+ packet = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=src_if.remote_ip4, dst=deid)
+ / Raw(payload)
+ )
return packet
@abc.abstractmethod
def run(self):
- """ testing procedure """
+ """testing procedure"""
pass
class SimpleDriver(Driver):
- """ Implements simple test procedure """
+ """Implements simple test procedure"""
+
def __init__(self, test, test_cases):
super(SimpleDriver, self).__init__(test, test_cases)
@@ -96,27 +110,27 @@ class SimpleDriver(Driver):
:param dst_loc: destination locator address
:param capture: list of captured packets
"""
- self.test.assertEqual(len(capture), 1, "Unexpected number of "
- "packets! Expected 1 but {} received"
- .format(len(capture)))
+ self.test.assertEqual(
+ len(capture),
+ 1,
+ "Unexpected number of "
+ "packets! Expected 1 but {} received".format(len(capture)),
+ )
packet = capture[0]
try:
ip_hdr = packet[IP]
# assert the values match
self.test.assertEqual(ip_hdr.src, src_loc, "IP source address")
- self.test.assertEqual(ip_hdr.dst, dst_loc,
- "IP destination address")
+ self.test.assertEqual(ip_hdr.dst, dst_loc, "IP destination address")
gpe_hdr = packet[LISP_GPE_Header]
- self.test.assertEqual(gpe_hdr.next_proto, 1,
- "next_proto is not ipv4!")
+ self.test.assertEqual(gpe_hdr.next_proto, 1, "next_proto is not ipv4!")
ih = gpe_hdr[IP]
- self.test.assertEqual(ih.src, self.test.pg0.remote_ip4,
- "unexpected source EID!")
- self.test.assertEqual(ih.dst, self.test.deid_ip4,
- "unexpected dest EID!")
+ self.test.assertEqual(
+ ih.src, self.test.pg0.remote_ip4, "unexpected source EID!"
+ )
+ self.test.assertEqual(ih.dst, self.test.deid_ip4, "unexpected dest EID!")
except:
- self.test.logger.error(ppp("Unexpected or invalid packet:",
- packet))
+ self.test.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
def configure_tc(self, tc):
@@ -125,26 +139,26 @@ class SimpleDriver(Driver):
vpp_object.add_vpp_config()
def run(self, dest):
- """ Send traffic for each test case and verify that it
- is encapsulated """
+ """Send traffic for each test case and verify that it
+ is encapsulated"""
for tc in enumerate(self.test_cases):
- self.test.logger.info('Running {}'.format(tc[1]['name']))
+ self.test.logger.info("Running {}".format(tc[1]["name"]))
self.configure_tc(tc[1])
- packet = self.create_packet(self.test.pg0, self.test.pg1, dest,
- 'data')
+ packet = self.create_packet(self.test.pg0, self.test.pg1, dest, "data")
self.test.pg0.add_stream(packet)
self.test.pg0.enable_capture()
self.test.pg1.enable_capture()
self.test.pg_start()
capture = self.test.pg1.get_capture(1)
- self.verify_capture(self.test.pg1.local_ip4,
- self.test.pg1.remote_ip4, capture)
+ self.verify_capture(
+ self.test.pg1.local_ip4, self.test.pg1.remote_ip4, capture
+ )
self.test.pg0.assert_nothing_captured()
class TestLisp(VppTestCase):
- """ Basic LISP test """
+ """Basic LISP test"""
@classmethod
def setUpClass(cls):
@@ -169,26 +183,23 @@ class TestLisp(VppTestCase):
self.deid_ip4_net = self.faf.net
self.deid_ip4 = self.faf.get_ip4()
- self.seid_ip4 = '{!s}/{!s}'.format(self.pg0.local_ip4, 32)
+ self.seid_ip4 = "{!s}/{!s}".format(self.pg0.local_ip4, 32)
self.rloc_ip4 = self.pg1.remote_ip4
test_cases = [
{
- 'name': 'basic ip4 over ip4',
- 'locator-sets': [VppLispLocatorSet(self, 'ls-4o4')],
- 'locators': [
- VppLispLocator(self, self.pg1.sw_if_index, 'ls-4o4')
- ],
- 'local-mappings': [
- VppLocalMapping(self, self.seid_ip4, 'ls-4o4')
+ "name": "basic ip4 over ip4",
+ "locator-sets": [VppLispLocatorSet(self, "ls-4o4")],
+ "locators": [VppLispLocator(self, self.pg1.sw_if_index, "ls-4o4")],
+ "local-mappings": [VppLocalMapping(self, self.seid_ip4, "ls-4o4")],
+ "remote-mappings": [
+ VppRemoteMapping(
+ self, self.deid_ip4_net, [LispRemoteLocator(self.rloc_ip4)]
+ )
],
- 'remote-mappings': [
- VppRemoteMapping(self, self.deid_ip4_net,
- [LispRemoteLocator(self.rloc_ip4)])
- ],
- 'adjacencies': [
+ "adjacencies": [
VppLispAdjacency(self, self.seid_ip4, self.deid_ip4_net)
- ]
+ ],
}
]
self.test_driver = SimpleDriver(self, test_cases)
@@ -196,7 +207,7 @@ class TestLisp(VppTestCase):
class TestLispUT(VppTestCase):
- """ Lisp UT """
+ """Lisp UT"""
@classmethod
def setUpClass(cls):
@@ -207,7 +218,7 @@ class TestLispUT(VppTestCase):
super(TestLispUT, cls).tearDownClass()
def test_fib(self):
- """ LISP Unit Tests """
+ """LISP Unit Tests"""
error = self.vapi.cli("test lisp cp")
if error:
@@ -215,5 +226,5 @@ class TestLispUT(VppTestCase):
self.assertNotIn("Failed", error)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_mactime.py b/test/test_mactime.py
index 1eaeeb53a9d..a9f981e6261 100644
--- a/test/test_mactime.py
+++ b/test/test_mactime.py
@@ -8,7 +8,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
class TestMactime(VppTestCase):
- """ Mactime Unit Test Cases """
+ """Mactime Unit Test Cases"""
@classmethod
def setUpClass(cls):
@@ -25,137 +25,140 @@ class TestMactime(VppTestCase):
super(TestMactime, self).tearDown()
def test_mactime_range_unittest(self):
- """ Time Range Test """
+ """Time Range Test"""
error = self.vapi.cli("test time-range")
if error:
self.logger.critical(error)
- self.assertNotIn('FAILED', error)
+ self.assertNotIn("FAILED", error)
@unittest.skipUnless(config.gcov, "part of code coverage tests")
def test_mactime_unittest(self):
- """ Mactime Plugin Code Coverage Test """
- cmds = ["loopback create",
- "mactime enable-disable disable",
- "mactime enable-disable loop0",
- "mactime enable-disable loop0 disable",
- "mactime enable-disable sw_if_index 9999",
- "bin mactime_enable_disable loop0",
- "bin mactime_enable_disable loop0 disable",
- "bin mactime_enable_disable sw_if_index 1",
- "set interface state loop0 up",
- "clear mactime",
- "set ip neighbor loop0 192.168.1.1 00:d0:2d:5e:86:85",
- "bin mactime_add_del_range name sallow "
- "mac 00:d0:2d:5e:86:85 allow-static del",
- "bin mactime_add_del_range name sallow "
- "mac 00:d0:2d:5e:86:85 allow-static",
- "bin mactime_add_del_range name sallow "
- "mac 00:d0:2d:5e:86:85 allow-static del",
- "bin mactime_add_del_range name sallow "
- "mac 00:d0:2d:5e:86:85 allow-static",
- "bin mactime_add_del_range name sblock "
- "mac 01:00:5e:7f:ff:fa drop-static",
- "bin mactime_add_del_range name ddrop "
- "mac c8:bc:c8:5a:ba:f3 drop-range Sun - Sat "
- "00:00 - 23:59",
- "bin mactime_add_del_range name dallow "
- "mac c8:bc:c8:5a:ba:f4 allow-range Sun - Sat "
- "00:00 - 23:59",
- "bin mactime_add_del_range name multi "
- "mac c8:bc:c8:f0:f0:f0 allow-range Sun - Mon "
- "00:00 - 23:59 Tue - Sat 00:00 - 23:59",
- "bin mactime_add_del_range bogus",
- "bin mactime_add_del_range mac 01:00:5e:7f:f0:f0 allow-static",
- "bin mactime_add_del_range "
- "name tooloooooooooooooooooooooooooooooooooooooooooooooooo"
- "nnnnnnnnnnnnnnnnnnnnnnnnnnnng mac 00:00:de:ad:be:ef "
- "allow-static",
- "packet-generator new {\n"
- " name allow\n"
- " limit 15\n"
- " size 128-128\n"
- " interface loop0\n"
- " node ethernet-input\n"
- " data {\n"
- " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n"
- " ICMP: db00::1 -> db00::2\n"
- " incrementing 30\n"
- " }\n",
- "}\n",
- "packet-generator new {\n"
- " name deny\n"
- " limit 15\n"
- " size 128-128\n"
- " interface loop0\n"
- " node ethernet-input\n"
- " data {\n"
- " IP6: 01:00:5e:7f:ff:fa -> 00:0d:ea:d0:00:00\n"
- " ICMP: db00::1 -> db00::2\n"
- " incrementing 30\n"
- " }\n",
- "}\n",
- "packet-generator new {\n"
- " name ddrop\n"
- " limit 15\n"
- " size 128-128\n"
- " interface loop0\n"
- " node ethernet-input\n"
- " data {\n"
- " IP6: c8:bc:c8:5a:ba:f3 -> 00:0d:ea:d0:00:00\n"
- " ICMP: db00::1 -> db00::2\n"
- " incrementing 30\n"
- " }\n",
- "}\n",
- "packet-generator new {\n"
- " name dallow\n"
- " limit 15\n"
- " size 128-128\n"
- " interface loop0\n"
- " node ethernet-input\n"
- " data {\n"
- " IP6: c8:bc:c8:5a:ba:f4 -> 00:0d:ea:d0:00:00\n"
- " ICMP: db00::1 -> db00::2\n"
- " incrementing 30\n"
- " }\n"
- "}\n"
- "packet-generator new {\n"
- " name makeentry\n"
- " limit 15\n"
- " size 128-128\n"
- " interface loop0\n"
- " node ethernet-input\n"
- " data {\n"
- " IP6: c8:bc:c8:5a:b0:0b -> 00:0d:ea:d0:00:00\n"
- " ICMP: db00::1 -> db00::2\n"
- " incrementing 30\n"
- " }\n"
- "}\n"
- "packet-generator new {\n"
- " name tx\n"
- " limit 15\n"
- " size 128-128\n"
- " interface local0\n"
- " tx-interface loop0\n"
- " node loop0-output\n"
- " data {\n"
- " hex 0x01005e7ffffa000dead000000800"
- "0102030405060708090a0b0c0d0e0f0102030405\n"
- " }\n"
- "}\n"
- "trace add pg-input 2",
- "pa en",
- "show mactime verbose 2",
- "show trace",
- "show error"]
+ """Mactime Plugin Code Coverage Test"""
+ cmds = [
+ "loopback create",
+ "mactime enable-disable disable",
+ "mactime enable-disable loop0",
+ "mactime enable-disable loop0 disable",
+ "mactime enable-disable sw_if_index 9999",
+ "bin mactime_enable_disable loop0",
+ "bin mactime_enable_disable loop0 disable",
+ "bin mactime_enable_disable sw_if_index 1",
+ "set interface state loop0 up",
+ "clear mactime",
+ "set ip neighbor loop0 192.168.1.1 00:d0:2d:5e:86:85",
+ "bin mactime_add_del_range name sallow "
+ "mac 00:d0:2d:5e:86:85 allow-static del",
+ "bin mactime_add_del_range name sallow "
+ "mac 00:d0:2d:5e:86:85 allow-static",
+ "bin mactime_add_del_range name sallow "
+ "mac 00:d0:2d:5e:86:85 allow-static del",
+ "bin mactime_add_del_range name sallow "
+ "mac 00:d0:2d:5e:86:85 allow-static",
+ "bin mactime_add_del_range name sblock "
+ "mac 01:00:5e:7f:ff:fa drop-static",
+ "bin mactime_add_del_range name ddrop "
+ "mac c8:bc:c8:5a:ba:f3 drop-range Sun - Sat "
+ "00:00 - 23:59",
+ "bin mactime_add_del_range name dallow "
+ "mac c8:bc:c8:5a:ba:f4 allow-range Sun - Sat "
+ "00:00 - 23:59",
+ "bin mactime_add_del_range name multi "
+ "mac c8:bc:c8:f0:f0:f0 allow-range Sun - Mon "
+ "00:00 - 23:59 Tue - Sat 00:00 - 23:59",
+ "bin mactime_add_del_range bogus",
+ "bin mactime_add_del_range mac 01:00:5e:7f:f0:f0 allow-static",
+ "bin mactime_add_del_range "
+ "name tooloooooooooooooooooooooooooooooooooooooooooooooooo"
+ "nnnnnnnnnnnnnnnnnnnnnnnnnnnng mac 00:00:de:ad:be:ef "
+ "allow-static",
+ "packet-generator new {\n"
+ " name allow\n"
+ " limit 15\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " node ethernet-input\n"
+ " data {\n"
+ " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n"
+ " ICMP: db00::1 -> db00::2\n"
+ " incrementing 30\n"
+ " }\n",
+ "}\n",
+ "packet-generator new {\n"
+ " name deny\n"
+ " limit 15\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " node ethernet-input\n"
+ " data {\n"
+ " IP6: 01:00:5e:7f:ff:fa -> 00:0d:ea:d0:00:00\n"
+ " ICMP: db00::1 -> db00::2\n"
+ " incrementing 30\n"
+ " }\n",
+ "}\n",
+ "packet-generator new {\n"
+ " name ddrop\n"
+ " limit 15\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " node ethernet-input\n"
+ " data {\n"
+ " IP6: c8:bc:c8:5a:ba:f3 -> 00:0d:ea:d0:00:00\n"
+ " ICMP: db00::1 -> db00::2\n"
+ " incrementing 30\n"
+ " }\n",
+ "}\n",
+ "packet-generator new {\n"
+ " name dallow\n"
+ " limit 15\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " node ethernet-input\n"
+ " data {\n"
+ " IP6: c8:bc:c8:5a:ba:f4 -> 00:0d:ea:d0:00:00\n"
+ " ICMP: db00::1 -> db00::2\n"
+ " incrementing 30\n"
+ " }\n"
+ "}\n"
+ "packet-generator new {\n"
+ " name makeentry\n"
+ " limit 15\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " node ethernet-input\n"
+ " data {\n"
+ " IP6: c8:bc:c8:5a:b0:0b -> 00:0d:ea:d0:00:00\n"
+ " ICMP: db00::1 -> db00::2\n"
+ " incrementing 30\n"
+ " }\n"
+ "}\n"
+ "packet-generator new {\n"
+ " name tx\n"
+ " limit 15\n"
+ " size 128-128\n"
+ " interface local0\n"
+ " tx-interface loop0\n"
+ " node loop0-output\n"
+ " data {\n"
+ " hex 0x01005e7ffffa000dead000000800"
+ "0102030405060708090a0b0c0d0e0f0102030405\n"
+ " }\n"
+ "}\n"
+ "trace add pg-input 2",
+ "pa en",
+ "show mactime verbose 2",
+ "show trace",
+ "show error",
+ ]
for cmd in cmds:
r = self.vapi.cli_return_response(cmd)
if r.retval != 0:
- if hasattr(r, 'reply'):
+ if hasattr(r, "reply"):
self.logger.info(cmd + " FAIL reply " + r.reply)
else:
self.logger.info(cmd + " FAIL retval " + str(r.retval))
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_map.py b/test/test_map.py
index 22fe1e1d20a..16e9607cedc 100644
--- a/test/test_map.py
+++ b/test/test_map.py
@@ -12,12 +12,17 @@ import scapy.compat
from scapy.layers.l2 import Ether
from scapy.packet import Raw
from scapy.layers.inet import IP, UDP, ICMP, TCP
-from scapy.layers.inet6 import IPv6, ICMPv6TimeExceeded, IPv6ExtHdrFragment, \
- ICMPv6EchoRequest, ICMPv6DestUnreach
+from scapy.layers.inet6 import (
+ IPv6,
+ ICMPv6TimeExceeded,
+ IPv6ExtHdrFragment,
+ ICMPv6EchoRequest,
+ ICMPv6DestUnreach,
+)
class TestMAP(VppTestCase):
- """ MAP Test Case """
+ """MAP Test Case"""
@classmethod
def setUpClass(cls):
@@ -69,27 +74,24 @@ class TestMAP(VppTestCase):
self.assertEqual(rx[IPv6].src, ip6_src)
self.assertEqual(rx[IPv6].dst, ip6_dst)
- def send_and_assert_encapped_one(self, packet, ip6_src, ip6_dst,
- dmac=None):
+ def send_and_assert_encapped_one(self, packet, ip6_src, ip6_dst, dmac=None):
return self.send_and_assert_encapped([packet], ip6_src, ip6_dst, dmac)
def test_api_map_domain_dump(self):
- map_dst = '2001::/64'
- map_src = '3000::1/128'
- client_pfx = '192.168.0.0/16'
- tag = 'MAP-E tag.'
- index = self.vapi.map_add_domain(ip4_prefix=client_pfx,
- ip6_prefix=map_dst,
- ip6_src=map_src,
- tag=tag).index
+ map_dst = "2001::/64"
+ map_src = "3000::1/128"
+ client_pfx = "192.168.0.0/16"
+ tag = "MAP-E tag."
+ index = self.vapi.map_add_domain(
+ ip4_prefix=client_pfx, ip6_prefix=map_dst, ip6_src=map_src, tag=tag
+ ).index
rv = self.vapi.map_domain_dump()
# restore the state early so as to not impact subsequent tests.
# If an assert fails, we will not get the chance to do it at the end.
self.vapi.map_del_domain(index=index)
- self.assertGreater(len(rv), 0,
- "Expected output from 'map_domain_dump'")
+ self.assertGreater(len(rv), 0, "Expected output from 'map_domain_dump'")
# typedefs are returned as ipaddress objects.
# wrap results in str() ugh! to avoid the need to call unicode.
@@ -97,8 +99,7 @@ class TestMAP(VppTestCase):
self.assertEqual(str(rv[0].ip6_prefix), map_dst)
self.assertEqual(str(rv[0].ip6_src), map_src)
- self.assertEqual(rv[0].tag, tag,
- "output produced incorrect tag value.")
+ self.assertEqual(rv[0].tag, tag, "output produced incorrect tag value.")
def create_domains(self, ip4_pfx_str, ip6_pfx_str, ip6_src_str):
ip4_pfx = ipaddress.ip_network(ip4_pfx_str)
@@ -106,24 +107,25 @@ class TestMAP(VppTestCase):
mod = ip4_pfx.num_addresses / 1024
indicies = []
for i in range(ip4_pfx.num_addresses):
- rv = self.vapi.map_add_domain(ip6_prefix=ip6_pfx_str,
- ip4_prefix=str(ip4_pfx[i]) + "/32",
- ip6_src=ip6_src_str)
+ rv = self.vapi.map_add_domain(
+ ip6_prefix=ip6_pfx_str,
+ ip4_prefix=str(ip4_pfx[i]) + "/32",
+ ip6_src=ip6_src_str,
+ )
indicies.append(rv.index)
return indicies
def test_api_map_domains_get(self):
# Create a bunch of domains
no_domains = 4096 # This must be large enough to ensure VPP suspends
- domains = self.create_domains('130.67.0.0/20', '2001::/32',
- '2001::1/128')
+ domains = self.create_domains("130.67.0.0/20", "2001::/32", "2001::1/128")
self.assertEqual(len(domains), no_domains)
d = []
cursor = 0
# Invalid cursor
- rv, details = self.vapi.map_domains_get(cursor=no_domains+10)
+ rv, details = self.vapi.map_domains_get(cursor=no_domains + 10)
self.assertEqual(rv.retval, -7)
# Delete a domain in the middle of walk
@@ -144,48 +146,53 @@ class TestMAP(VppTestCase):
self.vapi.map_del_domain(index=i)
def test_map_e_udp(self):
- """ MAP-E UDP"""
+ """MAP-E UDP"""
#
# Add a route to the MAP-BR
#
map_br_pfx = "2001::"
map_br_pfx_len = 32
- map_route = VppIpRoute(self,
- map_br_pfx,
- map_br_pfx_len,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ map_route = VppIpRoute(
+ self,
+ map_br_pfx,
+ map_br_pfx_len,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ )
map_route.add_vpp_config()
#
# Add a domain that maps from pg0 to pg1
#
- map_dst = '2001::/32'
- map_src = '3000::1/128'
- client_pfx = '192.168.0.0/16'
- map_translated_addr = '2001:0:101:7000:0:c0a8:101:7'
- tag = 'MAP-E tag.'
- self.vapi.map_add_domain(ip4_prefix=client_pfx,
- ip6_prefix=map_dst,
- ip6_src=map_src,
- ea_bits_len=20,
- psid_offset=4,
- psid_length=4,
- tag=tag)
+ map_dst = "2001::/32"
+ map_src = "3000::1/128"
+ client_pfx = "192.168.0.0/16"
+ map_translated_addr = "2001:0:101:7000:0:c0a8:101:7"
+ tag = "MAP-E tag."
+ self.vapi.map_add_domain(
+ ip4_prefix=client_pfx,
+ ip6_prefix=map_dst,
+ ip6_src=map_src,
+ ea_bits_len=20,
+ psid_offset=4,
+ psid_length=4,
+ tag=tag,
+ )
self.vapi.map_param_set_security_check(enable=1, fragments=1)
# Enable MAP on interface.
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg0.sw_if_index,
- is_translation=0)
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=0
+ )
# Ensure MAP doesn't steal all packets!
- v4 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 100))
+ v4 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4)
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(self.pg0, v4 * 4, self.pg0)
v4_reply = v4[1]
v4_reply.ttl -= 1
@@ -195,20 +202,24 @@ class TestMAP(VppTestCase):
#
# Fire in a v4 packet that will be encapped to the BR
#
- v4 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst='192.168.1.1') /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 100))
+ v4 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="192.168.1.1")
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_assert_encapped(v4 * 4, "3000::1", map_translated_addr)
#
# Verify reordered fragments are able to pass as well
#
- v4 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(id=1, src=self.pg0.remote_ip4, dst='192.168.1.1') /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 1000))
+ v4 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(id=1, src=self.pg0.remote_ip4, dst="192.168.1.1")
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 1000)
+ )
frags = fragment_rfc791(v4, 400)
frags.reverse()
@@ -216,16 +227,18 @@ class TestMAP(VppTestCase):
self.send_and_assert_encapped(frags, "3000::1", map_translated_addr)
# Enable MAP on interface.
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg1.sw_if_index,
- is_translation=0)
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=0
+ )
# Ensure MAP doesn't steal all packets
- v6 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6) /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 100))
- rx = self.send_and_expect(self.pg1, v6*1, self.pg1)
+ v6 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6)
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 100)
+ )
+ rx = self.send_and_expect(self.pg1, v6 * 1, self.pg1)
v6_reply = v6[1]
v6_reply.hlim -= 1
for p in rx:
@@ -235,11 +248,13 @@ class TestMAP(VppTestCase):
# Fire in a V6 encapped packet.
# expect a decapped packet on the inside ip4 link
#
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(dst='3000::1', src=map_translated_addr) /
- IP(dst=self.pg0.remote_ip4, src='192.168.1.1') /
- UDP(sport=10000, dport=20000) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(dst="3000::1", src=map_translated_addr)
+ / IP(dst=self.pg0.remote_ip4, src="192.168.1.1")
+ / UDP(sport=10000, dport=20000)
+ / Raw(b"\xa5" * 100)
+ )
self.pg1.add_stream(p)
@@ -256,15 +271,20 @@ class TestMAP(VppTestCase):
#
# Verify encapped reordered fragments pass as well
#
- p = (IP(id=1, dst=self.pg0.remote_ip4, src='192.168.1.1') /
- UDP(sport=10000, dport=20000) /
- Raw(b'\xa5' * 1500))
+ p = (
+ IP(id=1, dst=self.pg0.remote_ip4, src="192.168.1.1")
+ / UDP(sport=10000, dport=20000)
+ / Raw(b"\xa5" * 1500)
+ )
frags = fragment_rfc791(p, 400)
frags.reverse()
- stream = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(dst='3000::1', src=map_translated_addr) /
- x for x in frags)
+ stream = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(dst="3000::1", src=map_translated_addr)
+ / x
+ for x in frags
+ )
self.pg1.add_stream(stream)
@@ -279,15 +299,15 @@ class TestMAP(VppTestCase):
self.assertEqual(r[IP].dst, p[IP].dst)
# Verify that fragments pass even if ipv6 layer is fragmented
- stream = (IPv6(dst='3000::1', src=map_translated_addr) / x
- for x in frags)
+ stream = (IPv6(dst="3000::1", src=map_translated_addr) / x for x in frags)
v6_stream = [
Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / x
for i in range(len(frags))
for x in fragment_rfc8200(
- IPv6(dst='3000::1', src=map_translated_addr) / frags[i],
- i, 200)]
+ IPv6(dst="3000::1", src=map_translated_addr) / frags[i], i, 200
+ )
+ ]
self.pg1.add_stream(v6_stream)
@@ -306,32 +326,35 @@ class TestMAP(VppTestCase):
#
self.vapi.ppcli("map params pre-resolve ip6-nh 4001::1")
- self.send_and_assert_no_replies(self.pg0, v4,
- "resolved via default route")
+ self.send_and_assert_no_replies(self.pg0, v4, "resolved via default route")
#
# Add a route to 4001::1. Expect the encapped traffic to be
# sent via that routes next-hop
#
- pre_res_route = VppIpRoute(self, "4001::1", 128,
- [VppRoutePath(self.pg1.remote_hosts[2].ip6,
- self.pg1.sw_if_index)])
+ pre_res_route = VppIpRoute(
+ self,
+ "4001::1",
+ 128,
+ [VppRoutePath(self.pg1.remote_hosts[2].ip6, self.pg1.sw_if_index)],
+ )
pre_res_route.add_vpp_config()
- self.send_and_assert_encapped_one(v4, "3000::1",
- map_translated_addr,
- dmac=self.pg1.remote_hosts[2].mac)
+ self.send_and_assert_encapped_one(
+ v4, "3000::1", map_translated_addr, dmac=self.pg1.remote_hosts[2].mac
+ )
#
# change the route to the pre-solved next-hop
#
- pre_res_route.modify([VppRoutePath(self.pg1.remote_hosts[3].ip6,
- self.pg1.sw_if_index)])
+ pre_res_route.modify(
+ [VppRoutePath(self.pg1.remote_hosts[3].ip6, self.pg1.sw_if_index)]
+ )
pre_res_route.add_vpp_config()
- self.send_and_assert_encapped_one(v4, "3000::1",
- map_translated_addr,
- dmac=self.pg1.remote_hosts[3].mac)
+ self.send_and_assert_encapped_one(
+ v4, "3000::1", map_translated_addr, dmac=self.pg1.remote_hosts[3].mac
+ )
#
# cleanup. The test infra's object registry will ensure
@@ -341,51 +364,56 @@ class TestMAP(VppTestCase):
self.vapi.ppcli("map params pre-resolve del ip6-nh 4001::1")
def test_map_e_inner_frag(self):
- """ MAP-E Inner fragmentation """
+ """MAP-E Inner fragmentation"""
#
# Add a route to the MAP-BR
#
map_br_pfx = "2001::"
map_br_pfx_len = 32
- map_route = VppIpRoute(self,
- map_br_pfx,
- map_br_pfx_len,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ map_route = VppIpRoute(
+ self,
+ map_br_pfx,
+ map_br_pfx_len,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ )
map_route.add_vpp_config()
#
# Add a domain that maps from pg0 to pg1
#
- map_dst = '2001::/32'
- map_src = '3000::1/128'
- client_pfx = '192.168.0.0/16'
- map_translated_addr = '2001:0:101:7000:0:c0a8:101:7'
- tag = 'MAP-E tag.'
- self.vapi.map_add_domain(ip4_prefix=client_pfx,
- ip6_prefix=map_dst,
- ip6_src=map_src,
- ea_bits_len=20,
- psid_offset=4,
- psid_length=4,
- mtu=1000,
- tag=tag)
+ map_dst = "2001::/32"
+ map_src = "3000::1/128"
+ client_pfx = "192.168.0.0/16"
+ map_translated_addr = "2001:0:101:7000:0:c0a8:101:7"
+ tag = "MAP-E tag."
+ self.vapi.map_add_domain(
+ ip4_prefix=client_pfx,
+ ip6_prefix=map_dst,
+ ip6_src=map_src,
+ ea_bits_len=20,
+ psid_offset=4,
+ psid_length=4,
+ mtu=1000,
+ tag=tag,
+ )
# Enable MAP on interface.
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg0.sw_if_index,
- is_translation=0)
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=0
+ )
# Enable inner fragmentation
self.vapi.map_param_set_fragmentation(inner=1)
- v4 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst='192.168.1.1') /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 1300))
+ v4 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="192.168.1.1")
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 1300)
+ )
- self.pg_send(self.pg0, v4*1)
+ self.pg_send(self.pg0, v4 * 1)
rx = self.pg1.get_capture(2)
# 1000-sizeof(ip6_header_t) = 960.
@@ -397,10 +425,8 @@ class TestMAP(VppTestCase):
frags[0].chksum = 0
frags[1].chksum = 0
- v6_reply1 = (IPv6(src='3000::1', dst=map_translated_addr, hlim=63) /
- frags[0])
- v6_reply2 = (IPv6(src='3000::1', dst=map_translated_addr, hlim=63) /
- frags[1])
+ v6_reply1 = IPv6(src="3000::1", dst=map_translated_addr, hlim=63) / frags[0]
+ v6_reply2 = IPv6(src="3000::1", dst=map_translated_addr, hlim=63) / frags[1]
rx[0][1].fl = 0
rx[1][1].fl = 0
rx[0][1][IP].id = 0
@@ -412,45 +438,48 @@ class TestMAP(VppTestCase):
self.validate(rx[1][1], v6_reply2)
def test_map_e_tcp_mss(self):
- """ MAP-E TCP MSS"""
+ """MAP-E TCP MSS"""
#
# Add a route to the MAP-BR
#
map_br_pfx = "2001::"
map_br_pfx_len = 32
- map_route = VppIpRoute(self,
- map_br_pfx,
- map_br_pfx_len,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ map_route = VppIpRoute(
+ self,
+ map_br_pfx,
+ map_br_pfx_len,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ )
map_route.add_vpp_config()
#
# Add a domain that maps from pg0 to pg1
#
- map_dst = '2001::/32'
- map_src = '3000::1/128'
- client_pfx = '192.168.0.0/16'
- map_translated_addr = '2001:0:101:5000:0:c0a8:101:5'
- tag = 'MAP-E TCP tag.'
- self.vapi.map_add_domain(ip4_prefix=client_pfx,
- ip6_prefix=map_dst,
- ip6_src=map_src,
- ea_bits_len=20,
- psid_offset=4,
- psid_length=4,
- tag=tag)
+ map_dst = "2001::/32"
+ map_src = "3000::1/128"
+ client_pfx = "192.168.0.0/16"
+ map_translated_addr = "2001:0:101:5000:0:c0a8:101:5"
+ tag = "MAP-E TCP tag."
+ self.vapi.map_add_domain(
+ ip4_prefix=client_pfx,
+ ip6_prefix=map_dst,
+ ip6_src=map_src,
+ ea_bits_len=20,
+ psid_offset=4,
+ psid_length=4,
+ tag=tag,
+ )
# Enable MAP on pg0 interface.
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg0.sw_if_index,
- is_translation=0)
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=0
+ )
# Enable MAP on pg1 interface.
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg1.sw_if_index,
- is_translation=0)
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=0
+ )
# TCP MSS clamping
mss_clamp = 1300
@@ -460,9 +489,8 @@ class TestMAP(VppTestCase):
# Send a v4 packet that will be encapped.
#
p_ether = Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
- p_ip4 = IP(src=self.pg0.remote_ip4, dst='192.168.1.1')
- p_tcp = TCP(sport=20000, dport=30000, flags="S",
- options=[("MSS", 1455)])
+ p_ip4 = IP(src=self.pg0.remote_ip4, dst="192.168.1.1")
+ p_tcp = TCP(sport=20000, dport=30000, flags="S", options=[("MSS", 1455)])
p4 = p_ether / p_ip4 / p_tcp
self.pg1.add_stream(p4)
@@ -476,8 +504,7 @@ class TestMAP(VppTestCase):
self.assertEqual(rx[IP].src, p4[IP].src)
self.assertEqual(rx[IP].dst, p4[IP].dst)
self.assertEqual(rx[IPv6].src, "3000::1")
- self.assertEqual(rx[TCP].options,
- TCP(options=[('MSS', mss_clamp)]).options)
+ self.assertEqual(rx[TCP].options, TCP(options=[("MSS", mss_clamp)]).options)
def validate(self, rx, expected):
self.assertEqual(rx, expected.__class__(scapy.compat.raw(expected)))
@@ -520,173 +547,202 @@ class TestMAP(VppTestCase):
self.assertEqual(payload_total, payload_len_expected)
def payload(self, len):
- return 'x' * len
+ return "x" * len
def test_map_t(self):
- """ MAP-T """
+ """MAP-T"""
#
# Add a domain that maps from pg0 to pg1
#
- map_dst = '2001:db8::/32'
- map_src = '1234:5678:90ab:cdef::/64'
- ip4_pfx = '192.168.0.0/24'
- tag = 'MAP-T Tag.'
-
- self.vapi.map_add_domain(ip6_prefix=map_dst,
- ip4_prefix=ip4_pfx,
- ip6_src=map_src,
- ea_bits_len=16,
- psid_offset=6,
- psid_length=4,
- mtu=1500,
- tag=tag)
+ map_dst = "2001:db8::/32"
+ map_src = "1234:5678:90ab:cdef::/64"
+ ip4_pfx = "192.168.0.0/24"
+ tag = "MAP-T Tag."
+
+ self.vapi.map_add_domain(
+ ip6_prefix=map_dst,
+ ip4_prefix=ip4_pfx,
+ ip6_src=map_src,
+ ea_bits_len=16,
+ psid_offset=6,
+ psid_length=4,
+ mtu=1500,
+ tag=tag,
+ )
# Enable MAP-T on interfaces.
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg0.sw_if_index,
- is_translation=1)
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg1.sw_if_index,
- is_translation=1)
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=1
+ )
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=1
+ )
# Ensure MAP doesn't steal all packets!
- v4 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 100))
- rx = self.send_and_expect(self.pg0, v4*1, self.pg0)
+ v4 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4)
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 100)
+ )
+ rx = self.send_and_expect(self.pg0, v4 * 1, self.pg0)
v4_reply = v4[1]
v4_reply.ttl -= 1
for p in rx:
self.validate(p[1], v4_reply)
# Ensure MAP doesn't steal all packets
- v6 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6) /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 100))
- rx = self.send_and_expect(self.pg1, v6*1, self.pg1)
+ v6 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6)
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 100)
+ )
+ rx = self.send_and_expect(self.pg1, v6 * 1, self.pg1)
v6_reply = v6[1]
v6_reply.hlim -= 1
for p in rx:
self.validate(p[1], v6_reply)
- map_route = VppIpRoute(self,
- "2001:db8::",
- 32,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index,
- proto=DpoProto.DPO_PROTO_IP6)])
+ map_route = VppIpRoute(
+ self,
+ "2001:db8::",
+ 32,
+ [
+ VppRoutePath(
+ self.pg1.remote_ip6,
+ self.pg1.sw_if_index,
+ proto=DpoProto.DPO_PROTO_IP6,
+ )
+ ],
+ )
map_route.add_vpp_config()
#
# Send a v4 packet that will be translated
#
p_ether = Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
- p_ip4 = IP(src=self.pg0.remote_ip4, dst='192.168.0.1')
- payload = TCP(sport=0xabcd, dport=0xabcd)
-
- p4 = (p_ether / p_ip4 / payload)
- p6_translated = (IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0",
- dst="2001:db8:1f0::c0a8:1:f") / payload)
+ p_ip4 = IP(src=self.pg0.remote_ip4, dst="192.168.0.1")
+ payload = TCP(sport=0xABCD, dport=0xABCD)
+
+ p4 = p_ether / p_ip4 / payload
+ p6_translated = (
+ IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0", dst="2001:db8:1f0::c0a8:1:f")
+ / payload
+ )
p6_translated.hlim -= 1
- rx = self.send_and_expect(self.pg0, p4*1, self.pg1)
+ rx = self.send_and_expect(self.pg0, p4 * 1, self.pg1)
for p in rx:
self.validate(p[1], p6_translated)
# Send back an IPv6 packet that will be "untranslated"
p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
- p_ip6 = IPv6(src='2001:db8:1f0::c0a8:1:f',
- dst='1234:5678:90ab:cdef:ac:1001:200:0')
- p6 = (p_ether6 / p_ip6 / payload)
- p4_translated = (IP(src='192.168.0.1',
- dst=self.pg0.remote_ip4) / payload)
+ p_ip6 = IPv6(
+ src="2001:db8:1f0::c0a8:1:f", dst="1234:5678:90ab:cdef:ac:1001:200:0"
+ )
+ p6 = p_ether6 / p_ip6 / payload
+ p4_translated = IP(src="192.168.0.1", dst=self.pg0.remote_ip4) / payload
p4_translated.id = 0
p4_translated.ttl -= 1
- rx = self.send_and_expect(self.pg1, p6*1, self.pg0)
+ rx = self.send_and_expect(self.pg1, p6 * 1, self.pg0)
for p in rx:
self.validate(p[1], p4_translated)
# IPv4 TTL=0
- ip4_ttl_expired = IP(src=self.pg0.remote_ip4, dst='192.168.0.1', ttl=0)
- p4 = (p_ether / ip4_ttl_expired / payload)
-
- icmp4_reply = (IP(id=0, ttl=254, src=self.pg0.local_ip4,
- dst=self.pg0.remote_ip4) /
- ICMP(type='time-exceeded',
- code='ttl-zero-during-transit') /
- IP(src=self.pg0.remote_ip4,
- dst='192.168.0.1', ttl=0) / payload)
- rx = self.send_and_expect(self.pg0, p4*1, self.pg0)
+ ip4_ttl_expired = IP(src=self.pg0.remote_ip4, dst="192.168.0.1", ttl=0)
+ p4 = p_ether / ip4_ttl_expired / payload
+
+ icmp4_reply = (
+ IP(id=0, ttl=254, src=self.pg0.local_ip4, dst=self.pg0.remote_ip4)
+ / ICMP(type="time-exceeded", code="ttl-zero-during-transit")
+ / IP(src=self.pg0.remote_ip4, dst="192.168.0.1", ttl=0)
+ / payload
+ )
+ rx = self.send_and_expect(self.pg0, p4 * 1, self.pg0)
for p in rx:
self.validate(p[1], icmp4_reply)
# IPv4 TTL=1
- ip4_ttl_expired = IP(src=self.pg0.remote_ip4, dst='192.168.0.1', ttl=1)
- p4 = (p_ether / ip4_ttl_expired / payload)
-
- icmp4_reply = (IP(id=0, ttl=254, src=self.pg0.local_ip4,
- dst=self.pg0.remote_ip4) /
- ICMP(type='time-exceeded',
- code='ttl-zero-during-transit') /
- IP(src=self.pg0.remote_ip4,
- dst='192.168.0.1', ttl=1) / payload)
- rx = self.send_and_expect(self.pg0, p4*1, self.pg0)
+ ip4_ttl_expired = IP(src=self.pg0.remote_ip4, dst="192.168.0.1", ttl=1)
+ p4 = p_ether / ip4_ttl_expired / payload
+
+ icmp4_reply = (
+ IP(id=0, ttl=254, src=self.pg0.local_ip4, dst=self.pg0.remote_ip4)
+ / ICMP(type="time-exceeded", code="ttl-zero-during-transit")
+ / IP(src=self.pg0.remote_ip4, dst="192.168.0.1", ttl=1)
+ / payload
+ )
+ rx = self.send_and_expect(self.pg0, p4 * 1, self.pg0)
for p in rx:
self.validate(p[1], icmp4_reply)
# IPv6 Hop limit at BR
- ip6_hlim_expired = IPv6(hlim=1, src='2001:db8:1ab::c0a8:1:ab',
- dst='1234:5678:90ab:cdef:ac:1001:200:0')
- p6 = (p_ether6 / ip6_hlim_expired / payload)
-
- icmp6_reply = (IPv6(hlim=255, src=self.pg1.local_ip6,
- dst="2001:db8:1ab::c0a8:1:ab") /
- ICMPv6TimeExceeded(code=0) /
- IPv6(src="2001:db8:1ab::c0a8:1:ab",
- dst='1234:5678:90ab:cdef:ac:1001:200:0',
- hlim=1) / payload)
- rx = self.send_and_expect(self.pg1, p6*1, self.pg1)
+ ip6_hlim_expired = IPv6(
+ hlim=1,
+ src="2001:db8:1ab::c0a8:1:ab",
+ dst="1234:5678:90ab:cdef:ac:1001:200:0",
+ )
+ p6 = p_ether6 / ip6_hlim_expired / payload
+
+ icmp6_reply = (
+ IPv6(hlim=255, src=self.pg1.local_ip6, dst="2001:db8:1ab::c0a8:1:ab")
+ / ICMPv6TimeExceeded(code=0)
+ / IPv6(
+ src="2001:db8:1ab::c0a8:1:ab",
+ dst="1234:5678:90ab:cdef:ac:1001:200:0",
+ hlim=1,
+ )
+ / payload
+ )
+ rx = self.send_and_expect(self.pg1, p6 * 1, self.pg1)
for p in rx:
self.validate(p[1], icmp6_reply)
# IPv6 Hop limit beyond BR
- ip6_hlim_expired = IPv6(hlim=0, src='2001:db8:1ab::c0a8:1:ab',
- dst='1234:5678:90ab:cdef:ac:1001:200:0')
- p6 = (p_ether6 / ip6_hlim_expired / payload)
-
- icmp6_reply = (IPv6(hlim=255, src=self.pg1.local_ip6,
- dst="2001:db8:1ab::c0a8:1:ab") /
- ICMPv6TimeExceeded(code=0) /
- IPv6(src="2001:db8:1ab::c0a8:1:ab",
- dst='1234:5678:90ab:cdef:ac:1001:200:0',
- hlim=0) / payload)
- rx = self.send_and_expect(self.pg1, p6*1, self.pg1)
+ ip6_hlim_expired = IPv6(
+ hlim=0,
+ src="2001:db8:1ab::c0a8:1:ab",
+ dst="1234:5678:90ab:cdef:ac:1001:200:0",
+ )
+ p6 = p_ether6 / ip6_hlim_expired / payload
+
+ icmp6_reply = (
+ IPv6(hlim=255, src=self.pg1.local_ip6, dst="2001:db8:1ab::c0a8:1:ab")
+ / ICMPv6TimeExceeded(code=0)
+ / IPv6(
+ src="2001:db8:1ab::c0a8:1:ab",
+ dst="1234:5678:90ab:cdef:ac:1001:200:0",
+ hlim=0,
+ )
+ / payload
+ )
+ rx = self.send_and_expect(self.pg1, p6 * 1, self.pg1)
for p in rx:
self.validate(p[1], icmp6_reply)
# IPv4 Well-known port
- p_ip4 = IP(src=self.pg0.remote_ip4, dst='192.168.0.1')
+ p_ip4 = IP(src=self.pg0.remote_ip4, dst="192.168.0.1")
payload = UDP(sport=200, dport=200)
- p4 = (p_ether / p_ip4 / payload)
- self.send_and_assert_no_replies(self.pg0, p4*1)
+ p4 = p_ether / p_ip4 / payload
+ self.send_and_assert_no_replies(self.pg0, p4 * 1)
# IPv6 Well-known port
payload = UDP(sport=200, dport=200)
- p6 = (p_ether6 / p_ip6 / payload)
- self.send_and_assert_no_replies(self.pg1, p6*1)
+ p6 = p_ether6 / p_ip6 / payload
+ self.send_and_assert_no_replies(self.pg1, p6 * 1)
# UDP packet fragmentation
payload_len = 1453
payload = UDP(sport=40000, dport=4000) / self.payload(payload_len)
- p4 = (p_ether / p_ip4 / payload)
+ p4 = p_ether / p_ip4 / payload
self.pg_enable_capture()
self.pg0.add_stream(p4)
self.pg_start()
rx = self.pg1.get_capture(2)
- p_ip6_translated = IPv6(src='1234:5678:90ab:cdef:ac:1001:200:0',
- dst='2001:db8:1e0::c0a8:1:e')
+ p_ip6_translated = IPv6(
+ src="1234:5678:90ab:cdef:ac:1001:200:0", dst="2001:db8:1e0::c0a8:1:e"
+ )
for p in rx:
self.validate_frag6(p, p_ip6_translated)
@@ -695,7 +751,7 @@ class TestMAP(VppTestCase):
# UDP packet fragmentation send fragments
payload_len = 1453
payload = UDP(sport=40000, dport=4000) / self.payload(payload_len)
- p4 = (p_ether / p_ip4 / payload)
+ p4 = p_ether / p_ip4 / payload
frags = fragment_rfc791(p4, fragsize=1000)
self.pg_enable_capture()
self.pg0.add_stream(frags)
@@ -710,13 +766,14 @@ class TestMAP(VppTestCase):
# Send back an fragmented IPv6 UDP packet that will be "untranslated"
payload = UDP(sport=4000, dport=40000) / self.payload(payload_len)
p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
- p_ip6 = IPv6(src='2001:db8:1e0::c0a8:1:e',
- dst='1234:5678:90ab:cdef:ac:1001:200:0')
- p6 = (p_ether6 / p_ip6 / payload)
- frags6 = fragment_rfc8200(p6, identification=0xdcba, fragsize=1000)
-
- p_ip4_translated = IP(src='192.168.0.1', dst=self.pg0.remote_ip4)
- p4_translated = (p_ip4_translated / payload)
+ p_ip6 = IPv6(
+ src="2001:db8:1e0::c0a8:1:e", dst="1234:5678:90ab:cdef:ac:1001:200:0"
+ )
+ p6 = p_ether6 / p_ip6 / payload
+ frags6 = fragment_rfc8200(p6, identification=0xDCBA, fragsize=1000)
+
+ p_ip4_translated = IP(src="192.168.0.1", dst=self.pg0.remote_ip4)
+ p4_translated = p_ip4_translated / payload
p4_translated.id = 0
p4_translated.ttl -= 1
@@ -732,14 +789,15 @@ class TestMAP(VppTestCase):
# ICMP packet fragmentation
payload = ICMP(id=6529) / self.payload(payload_len)
- p4 = (p_ether / p_ip4 / payload)
+ p4 = p_ether / p_ip4 / payload
self.pg_enable_capture()
self.pg0.add_stream(p4)
self.pg_start()
rx = self.pg1.get_capture(2)
- p_ip6_translated = IPv6(src='1234:5678:90ab:cdef:ac:1001:200:0',
- dst='2001:db8:160::c0a8:1:6')
+ p_ip6_translated = IPv6(
+ src="1234:5678:90ab:cdef:ac:1001:200:0", dst="2001:db8:160::c0a8:1:6"
+ )
for p in rx:
self.validate_frag6(p, p_ip6_translated)
@@ -747,7 +805,7 @@ class TestMAP(VppTestCase):
# ICMP packet fragmentation send fragments
payload = ICMP(id=6529) / self.payload(payload_len)
- p4 = (p_ether / p_ip4 / payload)
+ p4 = p_ether / p_ip4 / payload
frags = fragment_rfc791(p4, fragsize=1000)
self.pg_enable_capture()
self.pg0.add_stream(frags)
@@ -766,30 +824,31 @@ class TestMAP(VppTestCase):
# Send a v4 TCP SYN packet that will be translated and MSS clamped
#
p_ether = Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
- p_ip4 = IP(src=self.pg0.remote_ip4, dst='192.168.0.1')
- payload = TCP(sport=0xabcd, dport=0xabcd, flags="S",
- options=[('MSS', 1460)])
-
- p4 = (p_ether / p_ip4 / payload)
- p6_translated = (IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0",
- dst="2001:db8:1f0::c0a8:1:f") / payload)
+ p_ip4 = IP(src=self.pg0.remote_ip4, dst="192.168.0.1")
+ payload = TCP(sport=0xABCD, dport=0xABCD, flags="S", options=[("MSS", 1460)])
+
+ p4 = p_ether / p_ip4 / payload
+ p6_translated = (
+ IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0", dst="2001:db8:1f0::c0a8:1:f")
+ / payload
+ )
p6_translated.hlim -= 1
- p6_translated[TCP].options = [('MSS', 1300)]
- rx = self.send_and_expect(self.pg0, p4*1, self.pg1)
+ p6_translated[TCP].options = [("MSS", 1300)]
+ rx = self.send_and_expect(self.pg0, p4 * 1, self.pg1)
for p in rx:
self.validate(p[1], p6_translated)
# Send back an IPv6 packet that will be "untranslated"
p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
- p_ip6 = IPv6(src='2001:db8:1f0::c0a8:1:f',
- dst='1234:5678:90ab:cdef:ac:1001:200:0')
- p6 = (p_ether6 / p_ip6 / payload)
- p4_translated = (IP(src='192.168.0.1',
- dst=self.pg0.remote_ip4) / payload)
+ p_ip6 = IPv6(
+ src="2001:db8:1f0::c0a8:1:f", dst="1234:5678:90ab:cdef:ac:1001:200:0"
+ )
+ p6 = p_ether6 / p_ip6 / payload
+ p4_translated = IP(src="192.168.0.1", dst=self.pg0.remote_ip4) / payload
p4_translated.id = 0
p4_translated.ttl -= 1
- p4_translated[TCP].options = [('MSS', 1300)]
- rx = self.send_and_expect(self.pg1, p6*1, self.pg0)
+ p4_translated[TCP].options = [("MSS", 1300)]
+ rx = self.send_and_expect(self.pg1, p6 * 1, self.pg0)
for p in rx:
self.validate(p[1], p4_translated)
@@ -803,19 +862,22 @@ class TestMAP(VppTestCase):
# Send back an IPv6 packet that will be droppped due to security
# check fail
p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
- p_ip6_sec_check_fail = IPv6(src='2001:db8:1fe::c0a8:1:f',
- dst='1234:5678:90ab:cdef:ac:1001:200:0')
- payload = TCP(sport=0xabcd, dport=0xabcd)
- p6 = (p_ether6 / p_ip6_sec_check_fail / payload)
+ p_ip6_sec_check_fail = IPv6(
+ src="2001:db8:1fe::c0a8:1:f", dst="1234:5678:90ab:cdef:ac:1001:200:0"
+ )
+ payload = TCP(sport=0xABCD, dport=0xABCD)
+ p6 = p_ether6 / p_ip6_sec_check_fail / payload
- self.pg_send(self.pg1, p6*1)
+ self.pg_send(self.pg1, p6 * 1)
self.pg0.get_capture(0, timeout=1)
rx = self.pg1.get_capture(1)
- icmp6_reply = (IPv6(hlim=255, src=self.pg1.local_ip6,
- dst='2001:db8:1fe::c0a8:1:f') /
- ICMPv6DestUnreach(code=5) /
- p_ip6_sec_check_fail / payload)
+ icmp6_reply = (
+ IPv6(hlim=255, src=self.pg1.local_ip6, dst="2001:db8:1fe::c0a8:1:f")
+ / ICMPv6DestUnreach(code=5)
+ / p_ip6_sec_check_fail
+ / payload
+ )
for p in rx:
self.validate(p[1], icmp6_reply)
@@ -824,142 +886,160 @@ class TestMAP(VppTestCase):
self.vapi.map_param_set_icmp6(enable_unreachable=0)
def test_map_t_ip6_psid(self):
- """ MAP-T v6->v4 PSID validation"""
+ """MAP-T v6->v4 PSID validation"""
#
# Add a domain that maps from pg0 to pg1
#
- map_dst = '2001:db8::/32'
- map_src = '1234:5678:90ab:cdef::/64'
- ip4_pfx = '192.168.0.0/24'
- tag = 'MAP-T Test Domain'
-
- self.vapi.map_add_domain(ip6_prefix=map_dst,
- ip4_prefix=ip4_pfx,
- ip6_src=map_src,
- ea_bits_len=16,
- psid_offset=6,
- psid_length=4,
- mtu=1500,
- tag=tag)
+ map_dst = "2001:db8::/32"
+ map_src = "1234:5678:90ab:cdef::/64"
+ ip4_pfx = "192.168.0.0/24"
+ tag = "MAP-T Test Domain"
+
+ self.vapi.map_add_domain(
+ ip6_prefix=map_dst,
+ ip4_prefix=ip4_pfx,
+ ip6_src=map_src,
+ ea_bits_len=16,
+ psid_offset=6,
+ psid_length=4,
+ mtu=1500,
+ tag=tag,
+ )
# Enable MAP-T on interfaces.
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg0.sw_if_index,
- is_translation=1)
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg1.sw_if_index,
- is_translation=1)
-
- map_route = VppIpRoute(self,
- "2001:db8::",
- 32,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index,
- proto=DpoProto.DPO_PROTO_IP6)])
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=1
+ )
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=1
+ )
+
+ map_route = VppIpRoute(
+ self,
+ "2001:db8::",
+ 32,
+ [
+ VppRoutePath(
+ self.pg1.remote_ip6,
+ self.pg1.sw_if_index,
+ proto=DpoProto.DPO_PROTO_IP6,
+ )
+ ],
+ )
map_route.add_vpp_config()
p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
- p_ip6 = IPv6(src='2001:db8:1f0::c0a8:1:f',
- dst='1234:5678:90ab:cdef:ac:1001:200:0')
+ p_ip6 = IPv6(
+ src="2001:db8:1f0::c0a8:1:f", dst="1234:5678:90ab:cdef:ac:1001:200:0"
+ )
# Send good IPv6 source port, ensure translated IPv4 received
- payload = TCP(sport=0xabcd, dport=80)
- p6 = (p_ether6 / p_ip6 / payload)
- p4_translated = (IP(src='192.168.0.1',
- dst=self.pg0.remote_ip4) / payload)
+ payload = TCP(sport=0xABCD, dport=80)
+ p6 = p_ether6 / p_ip6 / payload
+ p4_translated = IP(src="192.168.0.1", dst=self.pg0.remote_ip4) / payload
p4_translated.id = 0
p4_translated.ttl -= 1
- rx = self.send_and_expect(self.pg1, p6*1, self.pg0)
+ rx = self.send_and_expect(self.pg1, p6 * 1, self.pg0)
for p in rx:
self.validate(p[1], p4_translated)
# Send bad IPv6 source port, ensure translated IPv4 not received
- payload = TCP(sport=0xdcba, dport=80)
- p6 = (p_ether6 / p_ip6 / payload)
- self.send_and_assert_no_replies(self.pg1, p6*1)
+ payload = TCP(sport=0xDCBA, dport=80)
+ p6 = p_ether6 / p_ip6 / payload
+ self.send_and_assert_no_replies(self.pg1, p6 * 1)
def test_map_t_pre_resolve(self):
- """ MAP-T pre-resolve"""
+ """MAP-T pre-resolve"""
# Add a domain that maps from pg0 to pg1
- map_dst = '2001:db8::/32'
- map_src = '1234:5678:90ab:cdef::/64'
- ip4_pfx = '192.168.0.0/24'
- tag = 'MAP-T Test Domain.'
-
- self.vapi.map_add_domain(ip6_prefix=map_dst,
- ip4_prefix=ip4_pfx,
- ip6_src=map_src,
- ea_bits_len=16,
- psid_offset=6,
- psid_length=4,
- mtu=1500,
- tag=tag)
+ map_dst = "2001:db8::/32"
+ map_src = "1234:5678:90ab:cdef::/64"
+ ip4_pfx = "192.168.0.0/24"
+ tag = "MAP-T Test Domain."
+
+ self.vapi.map_add_domain(
+ ip6_prefix=map_dst,
+ ip4_prefix=ip4_pfx,
+ ip6_src=map_src,
+ ea_bits_len=16,
+ psid_offset=6,
+ psid_length=4,
+ mtu=1500,
+ tag=tag,
+ )
# Enable MAP-T on interfaces.
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg0.sw_if_index,
- is_translation=1)
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg1.sw_if_index,
- is_translation=1)
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=1
+ )
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=1
+ )
# Enable pre-resolve option
- self.vapi.map_param_add_del_pre_resolve(ip4_nh_address="10.1.2.3",
- ip6_nh_address="4001::1",
- is_add=1)
+ self.vapi.map_param_add_del_pre_resolve(
+ ip4_nh_address="10.1.2.3", ip6_nh_address="4001::1", is_add=1
+ )
# Add a route to 4001::1 and expect the translated traffic to be
# sent via that route next-hop.
- pre_res_route6 = VppIpRoute(self, "4001::1", 128,
- [VppRoutePath(self.pg1.remote_hosts[2].ip6,
- self.pg1.sw_if_index)])
+ pre_res_route6 = VppIpRoute(
+ self,
+ "4001::1",
+ 128,
+ [VppRoutePath(self.pg1.remote_hosts[2].ip6, self.pg1.sw_if_index)],
+ )
pre_res_route6.add_vpp_config()
# Add a route to 10.1.2.3 and expect the "untranslated" traffic to be
# sent via that route next-hop.
- pre_res_route4 = VppIpRoute(self, "10.1.2.3", 32,
- [VppRoutePath(self.pg0.remote_hosts[1].ip4,
- self.pg0.sw_if_index)])
+ pre_res_route4 = VppIpRoute(
+ self,
+ "10.1.2.3",
+ 32,
+ [VppRoutePath(self.pg0.remote_hosts[1].ip4, self.pg0.sw_if_index)],
+ )
pre_res_route4.add_vpp_config()
# Send an IPv4 packet that will be translated
p_ether = Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
- p_ip4 = IP(src=self.pg0.remote_ip4, dst='192.168.0.1')
- payload = TCP(sport=0xabcd, dport=0xabcd)
- p4 = (p_ether / p_ip4 / payload)
-
- p6_translated = (IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0",
- dst="2001:db8:1f0::c0a8:1:f") / payload)
+ p_ip4 = IP(src=self.pg0.remote_ip4, dst="192.168.0.1")
+ payload = TCP(sport=0xABCD, dport=0xABCD)
+ p4 = p_ether / p_ip4 / payload
+
+ p6_translated = (
+ IPv6(src="1234:5678:90ab:cdef:ac:1001:200:0", dst="2001:db8:1f0::c0a8:1:f")
+ / payload
+ )
p6_translated.hlim -= 1
- rx = self.send_and_expect(self.pg0, p4*1, self.pg1)
+ rx = self.send_and_expect(self.pg0, p4 * 1, self.pg1)
for p in rx:
self.assertEqual(p[Ether].dst, self.pg1.remote_hosts[2].mac)
self.validate(p[1], p6_translated)
# Send back an IPv6 packet that will be "untranslated"
p_ether6 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
- p_ip6 = IPv6(src='2001:db8:1f0::c0a8:1:f',
- dst='1234:5678:90ab:cdef:ac:1001:200:0')
- p6 = (p_ether6 / p_ip6 / payload)
+ p_ip6 = IPv6(
+ src="2001:db8:1f0::c0a8:1:f", dst="1234:5678:90ab:cdef:ac:1001:200:0"
+ )
+ p6 = p_ether6 / p_ip6 / payload
- p4_translated = (IP(src='192.168.0.1',
- dst=self.pg0.remote_ip4) / payload)
+ p4_translated = IP(src="192.168.0.1", dst=self.pg0.remote_ip4) / payload
p4_translated.id = 0
p4_translated.ttl -= 1
- rx = self.send_and_expect(self.pg1, p6*1, self.pg0)
+ rx = self.send_and_expect(self.pg1, p6 * 1, self.pg0)
for p in rx:
self.assertEqual(p[Ether].dst, self.pg0.remote_hosts[1].mac)
self.validate(p[1], p4_translated)
# Cleanup pre-resolve option
- self.vapi.map_param_add_del_pre_resolve(ip4_nh_address="10.1.2.3",
- ip6_nh_address="4001::1",
- is_add=0)
+ self.vapi.map_param_add_del_pre_resolve(
+ ip4_nh_address="10.1.2.3", ip6_nh_address="4001::1", is_add=0
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_map_br.py b/test/test_map_br.py
index 3fe5c83ab75..ae09e9b7d7a 100644
--- a/test/test_map_br.py
+++ b/test/test_map_br.py
@@ -17,7 +17,7 @@ from scapy.layers.inet6 import ICMPv6EchoRequest, ICMPv6EchoReply, IPerror6
class TestMAPBR(VppTestCase):
- """ MAP-T Test Cases """
+ """MAP-T Test Cases"""
@classmethod
def setUpClass(cls):
@@ -51,36 +51,37 @@ class TestMAPBR(VppTestCase):
#
# BR configuration parameters used for all test.
#
- self.ip4_prefix = '198.18.0.0/24'
- self.ip6_prefix = '2001:db8:f0::/48'
- self.ip6_src = '2001:db8:ffff:ff00::/64'
+ self.ip4_prefix = "198.18.0.0/24"
+ self.ip6_prefix = "2001:db8:f0::/48"
+ self.ip6_src = "2001:db8:ffff:ff00::/64"
self.ea_bits_len = 12
self.psid_offset = 6
self.psid_length = 4
self.mtu = 1500
- self.tag = 'MAP-T BR'
+ self.tag = "MAP-T BR"
self.ipv4_internet_address = self.pg0.remote_ip4
self.ipv4_map_address = "198.18.0.12"
self.ipv4_udp_or_tcp_internet_port = 65000
self.ipv4_udp_or_tcp_map_port = 16606
- self.ipv6_cpe_address = "2001:db8:f0:c30:0:c612:c:3" # 198.18.0.12
- self.ipv6_spoof_address = "2001:db8:f0:c30:0:c612:1c:3" # 198.18.0.28
- self.ipv6_spoof_prefix = "2001:db8:f0:c30:0:a00:c:3" # 10.0.0.12
- self.ipv6_spoof_psid = "2001:db8:f0:c30:0:c612:c:4" # 4
- self.ipv6_spoof_subnet = "2001:db8:f1:c30:0:c612:c:3" # f1
+ self.ipv6_cpe_address = "2001:db8:f0:c30:0:c612:c:3" # 198.18.0.12
+ self.ipv6_spoof_address = "2001:db8:f0:c30:0:c612:1c:3" # 198.18.0.28
+ self.ipv6_spoof_prefix = "2001:db8:f0:c30:0:a00:c:3" # 10.0.0.12
+ self.ipv6_spoof_psid = "2001:db8:f0:c30:0:c612:c:4" # 4
+ self.ipv6_spoof_subnet = "2001:db8:f1:c30:0:c612:c:3" # f1
self.ipv6_udp_or_tcp_internet_port = 65000
self.ipv6_udp_or_tcp_map_port = 16606
self.ipv6_udp_or_tcp_spoof_port = 16862
- self.ipv6_map_address = (
- "2001:db8:ffff:ff00:ac:1001:200:0") # 176.16.1.2
+ self.ipv6_map_address = "2001:db8:ffff:ff00:ac:1001:200:0" # 176.16.1.2
self.ipv6_map_same_rule_diff_addr = (
- "2001:db8:ffff:ff00:c6:1200:1000:0") # 198.18.0.16
+ "2001:db8:ffff:ff00:c6:1200:1000:0" # 198.18.0.16
+ )
self.ipv6_map_same_rule_same_addr = (
- "2001:db8:ffff:ff00:c6:1200:c00:0") # 198.18.0.12
+ "2001:db8:ffff:ff00:c6:1200:c00:0" # 198.18.0.12
+ )
self.map_br_prefix = "2001:db8:f0::"
self.map_br_prefix_len = 48
@@ -89,24 +90,27 @@ class TestMAPBR(VppTestCase):
#
# Add an IPv6 route to the MAP-BR.
#
- map_route = VppIpRoute(self,
- self.map_br_prefix,
- self.map_br_prefix_len,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ map_route = VppIpRoute(
+ self,
+ self.map_br_prefix,
+ self.map_br_prefix_len,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ )
map_route.add_vpp_config()
#
# Add a MAP BR domain that maps from pg0 to pg1.
#
- self.vapi.map_add_domain(ip4_prefix=self.ip4_prefix,
- ip6_prefix=self.ip6_prefix,
- ip6_src=self.ip6_src,
- ea_bits_len=self.ea_bits_len,
- psid_offset=self.psid_offset,
- psid_length=self.psid_length,
- mtu=self.mtu,
- tag=self.tag)
+ self.vapi.map_add_domain(
+ ip4_prefix=self.ip4_prefix,
+ ip6_prefix=self.ip6_prefix,
+ ip6_src=self.ip6_src,
+ ea_bits_len=self.ea_bits_len,
+ psid_offset=self.psid_offset,
+ psid_length=self.psid_length,
+ mtu=self.mtu,
+ tag=self.tag,
+ )
#
# Set BR parameters.
@@ -119,17 +123,17 @@ class TestMAPBR(VppTestCase):
#
# Enable MAP-T on interfaces.
#
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg0.sw_if_index,
- is_translation=1)
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg0.sw_if_index, is_translation=1
+ )
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg1.sw_if_index,
- is_translation=1)
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=1
+ )
- self.vapi.map_if_enable_disable(is_enable=1,
- sw_if_index=self.pg1.sw_if_index,
- is_translation=1)
+ self.vapi.map_if_enable_disable(
+ is_enable=1, sw_if_index=self.pg1.sw_if_index, is_translation=1
+ )
def tearDown(self):
super(TestMAPBR, self).tearDown()
@@ -162,15 +166,14 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_udp_ip4_to_ip6(self):
- """ MAP-T UDP IPv4 -> IPv6 """
-
- eth = Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac)
- ip = IP(src=self.pg0.remote_ip4,
- dst=self.ipv4_map_address,
- tos=0)
- udp = UDP(sport=self.ipv4_udp_or_tcp_internet_port,
- dport=self.ipv4_udp_or_tcp_map_port)
+ """MAP-T UDP IPv4 -> IPv6"""
+
+ eth = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ ip = IP(src=self.pg0.remote_ip4, dst=self.ipv4_map_address, tos=0)
+ udp = UDP(
+ sport=self.ipv4_udp_or_tcp_internet_port,
+ dport=self.ipv4_udp_or_tcp_map_port,
+ )
payload = "a" * 82
tx_pkt = eth / ip / udp / payload
@@ -181,7 +184,7 @@ class TestMAPBR(VppTestCase):
self.v6_address_check(rx_pkt)
self.v6_port_check(rx_pkt, UDP)
- self.assertEqual(rx_pkt[IPv6].tc, 0) # IPv4 ToS passed to v6 TC
+ self.assertEqual(rx_pkt[IPv6].tc, 0) # IPv4 ToS passed to v6 TC
self.assertEqual(rx_pkt[IPv6].nh, IPv6(nh="UDP").nh)
#
@@ -192,15 +195,14 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_tcp_ip4_to_ip6(self):
- """ MAP-T TCP IPv4 -> IPv6 """
-
- eth = Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac)
- ip = IP(src=self.pg0.remote_ip4,
- dst=self.ipv4_map_address,
- tos=0)
- tcp = TCP(sport=self.ipv4_udp_or_tcp_internet_port,
- dport=self.ipv4_udp_or_tcp_map_port)
+ """MAP-T TCP IPv4 -> IPv6"""
+
+ eth = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ ip = IP(src=self.pg0.remote_ip4, dst=self.ipv4_map_address, tos=0)
+ tcp = TCP(
+ sport=self.ipv4_udp_or_tcp_internet_port,
+ dport=self.ipv4_udp_or_tcp_map_port,
+ )
payload = "a" * 82
tx_pkt = eth / ip / tcp / payload
@@ -211,7 +213,7 @@ class TestMAPBR(VppTestCase):
self.v6_address_check(rx_pkt)
self.v6_port_check(rx_pkt, TCP)
- self.assertEqual(rx_pkt[IPv6].tc, 0) # IPv4 ToS passed to v6 TC
+ self.assertEqual(rx_pkt[IPv6].tc, 0) # IPv4 ToS passed to v6 TC
self.assertEqual(rx_pkt[IPv6].nh, IPv6(nh="TCP").nh)
#
@@ -221,14 +223,14 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_udp_ip6_to_ip4(self):
- """ MAP-T UDP IPv6 -> IPv4 """
-
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_cpe_address,
- dst=self.ipv6_map_address)
- udp = UDP(sport=self.ipv6_udp_or_tcp_map_port,
- dport=self.ipv6_udp_or_tcp_internet_port)
+ """MAP-T UDP IPv6 -> IPv4"""
+
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address)
+ udp = UDP(
+ sport=self.ipv6_udp_or_tcp_map_port,
+ dport=self.ipv6_udp_or_tcp_internet_port,
+ )
payload = "a" * 82
tx_pkt = eth / ip / udp / payload
@@ -240,7 +242,7 @@ class TestMAPBR(VppTestCase):
self.v4_address_check(rx_pkt)
self.v4_port_check(rx_pkt, UDP)
self.assertEqual(rx_pkt[IP].proto, IP(proto="udp").proto)
- self.assertEqual(rx_pkt[IP].tos, 0) # IPv6 TC passed to v4 ToS
+ self.assertEqual(rx_pkt[IP].tos, 0) # IPv6 TC passed to v4 ToS
df_bit = IP(flags="DF").flags
self.assertNotEqual(rx_pkt[IP].flags & df_bit, df_bit)
@@ -251,14 +253,14 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_tcp_ip6_to_ip4(self):
- """ MAP-T TCP IPv6 -> IPv4 """
-
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_cpe_address,
- dst=self.ipv6_map_address)
- tcp = TCP(sport=self.ipv6_udp_or_tcp_map_port,
- dport=self.ipv6_udp_or_tcp_internet_port)
+ """MAP-T TCP IPv6 -> IPv4"""
+
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address)
+ tcp = TCP(
+ sport=self.ipv6_udp_or_tcp_map_port,
+ dport=self.ipv6_udp_or_tcp_internet_port,
+ )
payload = "a" * 82
tx_pkt = eth / ip / tcp / payload
@@ -270,7 +272,7 @@ class TestMAPBR(VppTestCase):
self.v4_address_check(rx_pkt)
self.v4_port_check(rx_pkt, TCP)
self.assertEqual(rx_pkt[IP].proto, IP(proto="tcp").proto)
- self.assertEqual(rx_pkt[IP].tos, 0) # IPv6 TC passed to v4 ToS
+ self.assertEqual(rx_pkt[IP].tos, 0) # IPv6 TC passed to v4 ToS
df_bit = IP(flags="DF").flags
self.assertNotEqual(rx_pkt[IP].flags & df_bit, df_bit)
@@ -280,14 +282,11 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_echo_request_ip4_to_ip6(self):
- """ MAP-T echo request IPv4 -> IPv6 """
-
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IP(src=self.pg0.remote_ip4,
- dst=self.ipv4_map_address)
- icmp = ICMP(type="echo-request",
- id=self.ipv6_udp_or_tcp_map_port)
+ """MAP-T echo request IPv4 -> IPv6"""
+
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IP(src=self.pg0.remote_ip4, dst=self.ipv4_map_address)
+ icmp = ICMP(type="echo-request", id=self.ipv6_udp_or_tcp_map_port)
payload = "H" * 10
tx_pkt = eth / ip / icmp / payload
@@ -297,11 +296,11 @@ class TestMAPBR(VppTestCase):
rx_pkt = rx_pkts[0]
self.assertEqual(rx_pkt[IPv6].nh, IPv6(nh="ICMPv6").nh)
- self.assertEqual(rx_pkt[ICMPv6EchoRequest].type,
- ICMPv6EchoRequest(type="Echo Request").type)
+ self.assertEqual(
+ rx_pkt[ICMPv6EchoRequest].type, ICMPv6EchoRequest(type="Echo Request").type
+ )
self.assertEqual(rx_pkt[ICMPv6EchoRequest].code, 0)
- self.assertEqual(rx_pkt[ICMPv6EchoRequest].id,
- self.ipv6_udp_or_tcp_map_port)
+ self.assertEqual(rx_pkt[ICMPv6EchoRequest].id, self.ipv6_udp_or_tcp_map_port)
#
# Translation of ICMP Echo Reply v4 -> v6 direction
@@ -309,14 +308,11 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_echo_reply_ip4_to_ip6(self):
- """ MAP-T echo reply IPv4 -> IPv6 """
-
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IP(src=self.pg0.remote_ip4,
- dst=self.ipv4_map_address)
- icmp = ICMP(type="echo-reply",
- id=self.ipv6_udp_or_tcp_map_port)
+ """MAP-T echo reply IPv4 -> IPv6"""
+
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IP(src=self.pg0.remote_ip4, dst=self.ipv4_map_address)
+ icmp = ICMP(type="echo-reply", id=self.ipv6_udp_or_tcp_map_port)
payload = "H" * 10
tx_pkt = eth / ip / icmp / payload
@@ -326,11 +322,11 @@ class TestMAPBR(VppTestCase):
rx_pkt = rx_pkts[0]
self.assertEqual(rx_pkt[IPv6].nh, IPv6(nh="ICMPv6").nh)
- self.assertEqual(rx_pkt[ICMPv6EchoReply].type,
- ICMPv6EchoReply(type="Echo Reply").type)
+ self.assertEqual(
+ rx_pkt[ICMPv6EchoReply].type, ICMPv6EchoReply(type="Echo Reply").type
+ )
self.assertEqual(rx_pkt[ICMPv6EchoReply].code, 0)
- self.assertEqual(rx_pkt[ICMPv6EchoReply].id,
- self.ipv6_udp_or_tcp_map_port)
+ self.assertEqual(rx_pkt[ICMPv6EchoReply].id, self.ipv6_udp_or_tcp_map_port)
#
# Translation of ICMP Time Exceeded v4 -> v6 direction
@@ -338,17 +334,16 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_time_exceeded_ip4_to_ip6(self):
- """ MAP-T time exceeded IPv4 -> IPv6 """
+ """MAP-T time exceeded IPv4 -> IPv6"""
- eth = Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac)
- ip = IP(src=self.pg0.remote_ip4,
- dst=self.ipv4_map_address)
+ eth = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ ip = IP(src=self.pg0.remote_ip4, dst=self.ipv4_map_address)
icmp = ICMP(type="time-exceeded", code="ttl-zero-during-transit")
- ip_inner = IP(dst=self.pg0.remote_ip4,
- src=self.ipv4_map_address, ttl=1)
- udp_inner = UDP(sport=self.ipv4_udp_or_tcp_map_port,
- dport=self.ipv4_udp_or_tcp_internet_port)
+ ip_inner = IP(dst=self.pg0.remote_ip4, src=self.ipv4_map_address, ttl=1)
+ udp_inner = UDP(
+ sport=self.ipv4_udp_or_tcp_map_port,
+ dport=self.ipv4_udp_or_tcp_internet_port,
+ )
payload = "H" * 10
tx_pkt = eth / ip / icmp / ip_inner / udp_inner / payload
@@ -359,19 +354,18 @@ class TestMAPBR(VppTestCase):
self.v6_address_check(rx_pkt)
self.assertEqual(rx_pkt[IPv6].nh, IPv6(nh="ICMPv6").nh)
- self.assertEqual(rx_pkt[ICMPv6TimeExceeded].type,
- ICMPv6TimeExceeded().type)
- self.assertEqual(rx_pkt[ICMPv6TimeExceeded].code,
- ICMPv6TimeExceeded(
- code="hop limit exceeded in transit").code)
+ self.assertEqual(rx_pkt[ICMPv6TimeExceeded].type, ICMPv6TimeExceeded().type)
+ self.assertEqual(
+ rx_pkt[ICMPv6TimeExceeded].code,
+ ICMPv6TimeExceeded(code="hop limit exceeded in transit").code,
+ )
self.assertEqual(rx_pkt[ICMPv6TimeExceeded].hlim, tx_pkt[IP][1].ttl)
self.assertTrue(rx_pkt.haslayer(IPerror6))
self.assertTrue(rx_pkt.haslayer(UDPerror))
self.assertEqual(rx_pkt[IPv6].src, rx_pkt[IPerror6].dst)
self.assertEqual(rx_pkt[IPv6].dst, rx_pkt[IPerror6].src)
self.assertEqual(rx_pkt[UDPerror].sport, self.ipv6_udp_or_tcp_map_port)
- self.assertEqual(rx_pkt[UDPerror].dport,
- self.ipv6_udp_or_tcp_internet_port)
+ self.assertEqual(rx_pkt[UDPerror].dport, self.ipv6_udp_or_tcp_internet_port)
#
# Translation of ICMP Echo Request v6 -> v4 direction
@@ -379,12 +373,10 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_echo_request_ip6_to_ip4(self):
- """ MAP-T echo request IPv6 -> IPv4 """
+ """MAP-T echo request IPv6 -> IPv4"""
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_cpe_address,
- dst=self.ipv6_map_address)
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address)
icmp = ICMPv6EchoRequest()
icmp.id = self.ipv6_udp_or_tcp_map_port
payload = "H" * 10
@@ -406,12 +398,10 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_echo_reply_ip6_to_ip4(self):
- """ MAP-T echo reply IPv6 -> IPv4 """
+ """MAP-T echo reply IPv6 -> IPv4"""
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_cpe_address,
- dst=self.ipv6_map_address)
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address)
icmp = ICMPv6EchoReply(id=self.ipv6_udp_or_tcp_map_port)
payload = "H" * 10
tx_pkt = eth / ip / icmp / payload
@@ -432,17 +422,16 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_packet_too_big_ip6_to_ip4(self):
- """ MAP-T packet too big IPv6 -> IPv4 """
+ """MAP-T packet too big IPv6 -> IPv4"""
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_cpe_address,
- dst=self.ipv6_map_address)
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address)
icmp = ICMPv6PacketTooBig(mtu=1280)
- ip_inner = IPv6(src=self.ipv6_map_address,
- dst=self.ipv6_cpe_address)
- udp_inner = UDP(sport=self.ipv6_udp_or_tcp_internet_port,
- dport=self.ipv6_udp_or_tcp_map_port)
+ ip_inner = IPv6(src=self.ipv6_map_address, dst=self.ipv6_cpe_address)
+ udp_inner = UDP(
+ sport=self.ipv6_udp_or_tcp_internet_port,
+ dport=self.ipv6_udp_or_tcp_map_port,
+ )
payload = "H" * 10
tx_pkt = eth / ip / icmp / ip_inner / udp_inner / payload
@@ -454,16 +443,13 @@ class TestMAPBR(VppTestCase):
self.v4_address_check(rx_pkt)
self.assertEqual(rx_pkt[IP].proto, IP(proto="icmp").proto)
self.assertEqual(rx_pkt[ICMP].type, ICMP(type="dest-unreach").type)
- self.assertEqual(rx_pkt[ICMP].code,
- ICMP(code="fragmentation-needed").code)
- self.assertEqual(rx_pkt[ICMP].nexthopmtu,
- tx_pkt[ICMPv6PacketTooBig].mtu - 20)
+ self.assertEqual(rx_pkt[ICMP].code, ICMP(code="fragmentation-needed").code)
+ self.assertEqual(rx_pkt[ICMP].nexthopmtu, tx_pkt[ICMPv6PacketTooBig].mtu - 20)
self.assertTrue(rx_pkt.haslayer(IPerror))
self.assertTrue(rx_pkt.haslayer(UDPerror))
self.assertEqual(rx_pkt[IP].src, rx_pkt[IPerror].dst)
self.assertEqual(rx_pkt[IP].dst, rx_pkt[IPerror].src)
- self.assertEqual(rx_pkt[UDPerror].sport,
- self.ipv4_udp_or_tcp_internet_port)
+ self.assertEqual(rx_pkt[UDPerror].sport, self.ipv4_udp_or_tcp_internet_port)
self.assertEqual(rx_pkt[UDPerror].dport, self.ipv4_udp_or_tcp_map_port)
#
@@ -472,17 +458,16 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_time_exceeded_ip6_to_ip4(self):
- """ MAP-T time exceeded IPv6 -> IPv4 """
+ """MAP-T time exceeded IPv6 -> IPv4"""
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_cpe_address,
- dst=self.ipv6_map_address)
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address)
icmp = ICMPv6TimeExceeded()
- ip_inner = IPv6(src=self.ipv6_map_address,
- dst=self.ipv6_cpe_address, hlim=1)
- udp_inner = UDP(sport=self.ipv6_udp_or_tcp_internet_port,
- dport=self.ipv6_udp_or_tcp_map_port)
+ ip_inner = IPv6(src=self.ipv6_map_address, dst=self.ipv6_cpe_address, hlim=1)
+ udp_inner = UDP(
+ sport=self.ipv6_udp_or_tcp_internet_port,
+ dport=self.ipv6_udp_or_tcp_map_port,
+ )
payload = "H" * 10
tx_pkt = eth / ip / icmp / ip_inner / udp_inner / payload
@@ -494,15 +479,13 @@ class TestMAPBR(VppTestCase):
self.v4_address_check(rx_pkt)
self.assertEqual(rx_pkt[IP].proto, IP(proto="icmp").proto)
self.assertEqual(rx_pkt[ICMP].type, ICMP(type="time-exceeded").type)
- self.assertEqual(rx_pkt[ICMP].code,
- ICMP(code="ttl-zero-during-transit").code)
+ self.assertEqual(rx_pkt[ICMP].code, ICMP(code="ttl-zero-during-transit").code)
self.assertEqual(rx_pkt[ICMP].ttl, tx_pkt[IPv6][1].hlim)
self.assertTrue(rx_pkt.haslayer(IPerror))
self.assertTrue(rx_pkt.haslayer(UDPerror))
self.assertEqual(rx_pkt[IP].src, rx_pkt[IPerror].dst)
self.assertEqual(rx_pkt[IP].dst, rx_pkt[IPerror].src)
- self.assertEqual(rx_pkt[UDPerror].sport,
- self.ipv4_udp_or_tcp_internet_port)
+ self.assertEqual(rx_pkt[UDPerror].sport, self.ipv4_udp_or_tcp_internet_port)
self.assertEqual(rx_pkt[UDPerror].dport, self.ipv4_udp_or_tcp_map_port)
#
@@ -514,22 +497,21 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_spoof_ipv4_src_addr_ip6_to_ip4(self):
- """ MAP-T spoof ipv4 src addr IPv6 -> IPv4 """
-
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_spoof_address,
- dst=self.ipv6_map_address)
- udp = UDP(sport=self.ipv6_udp_or_tcp_map_port,
- dport=self.ipv6_udp_or_tcp_internet_port)
+ """MAP-T spoof ipv4 src addr IPv6 -> IPv4"""
+
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_spoof_address, dst=self.ipv6_map_address)
+ udp = UDP(
+ sport=self.ipv6_udp_or_tcp_map_port,
+ dport=self.ipv6_udp_or_tcp_internet_port,
+ )
payload = "a" * 82
tx_pkt = eth / ip / udp / payload
self.pg_send(self.pg1, tx_pkt * 1)
self.pg0.get_capture(0, timeout=1)
- self.pg0.assert_nothing_captured(
- remark="Should drop IPv4 spoof address")
+ self.pg0.assert_nothing_captured(remark="Should drop IPv4 spoof address")
#
# Spoofed IPv4 Source Prefix v6 -> v4 direction
@@ -539,22 +521,21 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_spoof_ipv4_src_prefix_ip6_to_ip4(self):
- """ MAP-T spoof ipv4 src prefix IPv6 -> IPv4 """
-
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_spoof_prefix,
- dst=self.ipv6_map_address)
- udp = UDP(sport=self.ipv6_udp_or_tcp_map_port,
- dport=self.ipv6_udp_or_tcp_internet_port)
+ """MAP-T spoof ipv4 src prefix IPv6 -> IPv4"""
+
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_spoof_prefix, dst=self.ipv6_map_address)
+ udp = UDP(
+ sport=self.ipv6_udp_or_tcp_map_port,
+ dport=self.ipv6_udp_or_tcp_internet_port,
+ )
payload = "a" * 82
tx_pkt = eth / ip / udp / payload
self.pg_send(self.pg1, tx_pkt * 1)
self.pg0.get_capture(0, timeout=1)
- self.pg0.assert_nothing_captured(
- remark="Should drop IPv4 spoof prefix")
+ self.pg0.assert_nothing_captured(remark="Should drop IPv4 spoof prefix")
#
# Spoofed IPv6 PSID v6 -> v4 direction
@@ -563,22 +544,21 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_spoof_psid_ip6_to_ip4(self):
- """ MAP-T spoof psid IPv6 -> IPv4 """
-
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_spoof_psid,
- dst=self.ipv6_map_address)
- udp = UDP(sport=self.ipv6_udp_or_tcp_map_port,
- dport=self.ipv6_udp_or_tcp_internet_port)
+ """MAP-T spoof psid IPv6 -> IPv4"""
+
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_spoof_psid, dst=self.ipv6_map_address)
+ udp = UDP(
+ sport=self.ipv6_udp_or_tcp_map_port,
+ dport=self.ipv6_udp_or_tcp_internet_port,
+ )
payload = "a" * 82
tx_pkt = eth / ip / udp / payload
self.pg_send(self.pg1, tx_pkt * 1)
self.pg0.get_capture(0, timeout=1)
- self.pg0.assert_nothing_captured(
- remark="Should drop IPv6 spoof PSID")
+ self.pg0.assert_nothing_captured(remark="Should drop IPv6 spoof PSID")
#
# Spoofed IPv6 subnet field v6 -> v4 direction
@@ -587,22 +567,21 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_spoof_subnet_ip6_to_ip4(self):
- """ MAP-T spoof subnet IPv6 -> IPv4 """
-
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_spoof_subnet,
- dst=self.ipv6_map_address)
- udp = UDP(sport=self.ipv6_udp_or_tcp_map_port,
- dport=self.ipv6_udp_or_tcp_internet_port)
+ """MAP-T spoof subnet IPv6 -> IPv4"""
+
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_spoof_subnet, dst=self.ipv6_map_address)
+ udp = UDP(
+ sport=self.ipv6_udp_or_tcp_map_port,
+ dport=self.ipv6_udp_or_tcp_internet_port,
+ )
payload = "a" * 82
tx_pkt = eth / ip / udp / payload
self.pg_send(self.pg1, tx_pkt * 1)
self.pg0.get_capture(0, timeout=1)
- self.pg0.assert_nothing_captured(
- remark="Should drop IPv6 spoof subnet")
+ self.pg0.assert_nothing_captured(remark="Should drop IPv6 spoof subnet")
#
# Spoofed IPv6 port PSID v6 -> v4 direction
@@ -611,22 +590,21 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_spoof_port_psid_ip6_to_ip4(self):
- """ MAP-T spoof port psid IPv6 -> IPv4 """
-
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_cpe_address,
- dst=self.ipv6_map_address)
- udp = UDP(sport=self.ipv6_udp_or_tcp_spoof_port,
- dport=self.ipv6_udp_or_tcp_internet_port)
+ """MAP-T spoof port psid IPv6 -> IPv4"""
+
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address)
+ udp = UDP(
+ sport=self.ipv6_udp_or_tcp_spoof_port,
+ dport=self.ipv6_udp_or_tcp_internet_port,
+ )
payload = "a" * 82
tx_pkt = eth / ip / udp / payload
self.pg_send(self.pg1, tx_pkt * 1)
self.pg0.get_capture(0, timeout=1)
- self.pg0.assert_nothing_captured(
- remark="Should drop IPv6 spoof port PSID")
+ self.pg0.assert_nothing_captured(remark="Should drop IPv6 spoof port PSID")
#
# Spoofed IPv6 ICMP ID PSID v6 -> v4 direction
@@ -635,12 +613,10 @@ class TestMAPBR(VppTestCase):
#
def test_map_t_spoof_icmp_id_psid_ip6_to_ip4(self):
- """ MAP-T spoof ICMP id psid IPv6 -> IPv4 """
+ """MAP-T spoof ICMP id psid IPv6 -> IPv4"""
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_cpe_address,
- dst=self.ipv6_map_address)
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_address)
icmp = ICMPv6EchoRequest()
icmp.id = self.ipv6_udp_or_tcp_spoof_port
payload = "H" * 10
@@ -649,8 +625,7 @@ class TestMAPBR(VppTestCase):
self.pg_send(self.pg1, tx_pkt * 1)
self.pg0.get_capture(0, timeout=1)
- self.pg0.assert_nothing_captured(
- remark="Should drop IPv6 spoof port PSID")
+ self.pg0.assert_nothing_captured(remark="Should drop IPv6 spoof port PSID")
#
# Map to Map - same rule, different address
@@ -658,14 +633,11 @@ class TestMAPBR(VppTestCase):
@unittest.skip("Fixme: correct behavior needs clarification")
def test_map_t_same_rule_diff_addr_ip6_to_ip4(self):
- """ MAP-T same rule, diff addr IPv6 -> IPv6 """
-
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_cpe_address,
- dst=self.ipv6_map_same_rule_diff_addr)
- udp = UDP(sport=self.ipv6_udp_or_tcp_map_port,
- dport=1025)
+ """MAP-T same rule, diff addr IPv6 -> IPv6"""
+
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_same_rule_diff_addr)
+ udp = UDP(sport=self.ipv6_udp_or_tcp_map_port, dport=1025)
payload = "a" * 82
tx_pkt = eth / ip / udp / payload
@@ -680,14 +652,11 @@ class TestMAPBR(VppTestCase):
@unittest.skip("Fixme: correct behavior needs clarification")
def test_map_t_same_rule_same_addr_ip6_to_ip4(self):
- """ MAP-T same rule, same addr IPv6 -> IPv6 """
-
- eth = Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac)
- ip = IPv6(src=self.ipv6_cpe_address,
- dst=self.ipv6_map_same_rule_same_addr)
- udp = UDP(sport=self.ipv6_udp_or_tcp_map_port,
- dport=1025)
+ """MAP-T same rule, same addr IPv6 -> IPv6"""
+
+ eth = Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ ip = IPv6(src=self.ipv6_cpe_address, dst=self.ipv6_map_same_rule_same_addr)
+ udp = UDP(sport=self.ipv6_udp_or_tcp_map_port, dport=1025)
payload = "a" * 82
tx_pkt = eth / ip / udp / payload
@@ -697,5 +666,5 @@ class TestMAPBR(VppTestCase):
rx_pkt = rx_pkts[0]
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_memif.py b/test/test_memif.py
index 26e44f29485..9b15cd0005b 100644
--- a/test/test_memif.py
+++ b/test/test_memif.py
@@ -7,26 +7,25 @@ from scapy.layers.inet import IP, ICMP
from framework import VppTestCase, VppTestRunner
from framework import tag_run_solo
from remote_test import RemoteClass, RemoteVppTestCase
-from vpp_memif import remove_all_memif_vpp_config, \
- VppSocketFilename, VppMemif
+from vpp_memif import remove_all_memif_vpp_config, VppSocketFilename, VppMemif
from vpp_ip_route import VppIpRoute, VppRoutePath
from vpp_papi import VppEnum
@tag_run_solo
class TestMemif(VppTestCase):
- """ Memif Test Case """
+ """Memif Test Case"""
+
remote_class = RemoteVppTestCase
@classmethod
def get_cpus_required(cls):
- return (super().get_cpus_required() +
- cls.remote_class.get_cpus_required())
+ return super().get_cpus_required() + cls.remote_class.get_cpus_required()
@classmethod
def assign_cpus(cls, cpus):
- remote_cpus = cpus[:cls.remote_class.get_cpus_required()]
- my_cpus = cpus[cls.remote_class.get_cpus_required():]
+ remote_cpus = cpus[: cls.remote_class.get_cpus_required()]
+ my_cpus = cpus[cls.remote_class.get_cpus_required() :]
cls.remote_class.assign_cpus(remote_cpus)
super().assign_cpus(my_cpus)
@@ -61,56 +60,47 @@ class TestMemif(VppTestCase):
def _check_socket_filename(self, dump, socket_id, filename):
for d in dump:
- if (d.socket_id == socket_id) and (
- d.socket_filename == filename):
+ if (d.socket_id == socket_id) and (d.socket_filename == filename):
return True
return False
def test_memif_socket_filename_add_del(self):
- """ Memif socket filename add/del """
+ """Memif socket filename add/del"""
# dump default socket filename
dump = self.vapi.memif_socket_filename_dump()
self.assertTrue(
- self._check_socket_filename(
- dump, 0, "%s/memif.sock" % self.tempdir))
+ self._check_socket_filename(dump, 0, "%s/memif.sock" % self.tempdir)
+ )
memif_sockets = []
# existing path
memif_sockets.append(
- VppSocketFilename(
- self, 1, "%s/memif1.sock" % self.tempdir))
+ VppSocketFilename(self, 1, "%s/memif1.sock" % self.tempdir)
+ )
# default path (test tempdir)
memif_sockets.append(
- VppSocketFilename(
- self,
- 2,
- "memif2.sock",
- add_default_folder=True))
+ VppSocketFilename(self, 2, "memif2.sock", add_default_folder=True)
+ )
# create new folder in default folder
memif_sockets.append(
- VppSocketFilename(
- self,
- 3,
- "sock/memif3.sock",
- add_default_folder=True))
+ VppSocketFilename(self, 3, "sock/memif3.sock", add_default_folder=True)
+ )
for sock in memif_sockets:
sock.add_vpp_config()
dump = sock.query_vpp_config()
self.assertTrue(
- self._check_socket_filename(
- dump,
- sock.socket_id,
- sock.socket_filename))
+ self._check_socket_filename(dump, sock.socket_id, sock.socket_filename)
+ )
for sock in memif_sockets:
sock.remove_vpp_config()
dump = self.vapi.memif_socket_filename_dump()
self.assertTrue(
- self._check_socket_filename(
- dump, 0, "%s/memif.sock" % self.tempdir))
+ self._check_socket_filename(dump, 0, "%s/memif.sock" % self.tempdir)
+ )
def _create_delete_test_one_interface(self, memif):
memif.add_vpp_config()
@@ -121,7 +111,7 @@ class TestMemif(VppTestCase):
self.assertEqual(dump.sw_if_index, memif.sw_if_index)
self.assertEqual(dump.role, memif.role)
self.assertEqual(dump.mode, memif.mode)
- if (memif.socket_id is not None):
+ if memif.socket_id is not None:
self.assertEqual(dump.socket_id, memif.socket_id)
memif.remove_vpp_config()
@@ -155,43 +145,39 @@ class TestMemif(VppTestCase):
memif1.remove_vpp_config()
def test_memif_create_delete(self):
- """ Memif create/delete interface """
+ """Memif create/delete interface"""
memif = VppMemif(
self,
VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE,
- VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET)
+ VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
+ )
self._create_delete_test_one_interface(memif)
memif.role = VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_MASTER
self._create_delete_test_one_interface(memif)
def test_memif_create_custom_socket(self):
- """ Memif create with non-default socket filename """
+ """Memif create with non-default socket filename"""
memif_sockets = []
# existing path
memif_sockets.append(
- VppSocketFilename(
- self, 1, "%s/memif1.sock" % self.tempdir))
+ VppSocketFilename(self, 1, "%s/memif1.sock" % self.tempdir)
+ )
# default path (test tempdir)
memif_sockets.append(
- VppSocketFilename(
- self,
- 2,
- "memif2.sock",
- add_default_folder=True))
+ VppSocketFilename(self, 2, "memif2.sock", add_default_folder=True)
+ )
# create new folder in default folder
memif_sockets.append(
- VppSocketFilename(
- self,
- 3,
- "sock/memif3.sock",
- add_default_folder=True))
+ VppSocketFilename(self, 3, "sock/memif3.sock", add_default_folder=True)
+ )
memif = VppMemif(
self,
VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE,
- VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET)
+ VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
+ )
for sock in memif_sockets:
sock.add_vpp_config()
@@ -202,17 +188,19 @@ class TestMemif(VppTestCase):
self._create_delete_test_one_interface(memif)
def test_memif_connect(self):
- """ Memif connect """
+ """Memif connect"""
memif = VppMemif(
self,
VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE,
VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
ring_size=1024,
buffer_size=2048,
- secret="abc")
+ secret="abc",
+ )
- remote_socket = VppSocketFilename(self.remote_test, 1,
- "%s/memif.sock" % self.tempdir)
+ remote_socket = VppSocketFilename(
+ self.remote_test, 1, "%s/memif.sock" % self.tempdir
+ )
remote_socket.add_vpp_config()
remote_memif = VppMemif(
@@ -222,7 +210,8 @@ class TestMemif(VppTestCase):
socket_id=1,
ring_size=1024,
buffer_size=2048,
- secret="abc")
+ secret="abc",
+ )
self._connect_test_interface_pair(memif, remote_memif)
@@ -234,10 +223,11 @@ class TestMemif(VppTestCase):
def _create_icmp(self, pg, memif, num):
pkts = []
for i in range(num):
- pkt = (Ether(dst=pg.local_mac, src=pg.remote_mac) /
- IP(src=pg.remote_ip4,
- dst=str(memif.ip_prefix.network_address)) /
- ICMP(id=memif.if_id, type='echo-request', seq=i))
+ pkt = (
+ Ether(dst=pg.local_mac, src=pg.remote_mac)
+ / IP(src=pg.remote_ip4, dst=str(memif.ip_prefix.network_address))
+ / ICMP(id=memif.if_id, type="echo-request", seq=i)
+ )
pkts.append(pkt)
return pkts
@@ -252,22 +242,25 @@ class TestMemif(VppTestCase):
self.assertEqual(icmp.seq, seq)
def test_memif_ping(self):
- """ Memif ping """
+ """Memif ping"""
memif = VppMemif(
self,
VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE,
- VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET)
+ VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
+ )
- remote_socket = VppSocketFilename(self.remote_test, 1,
- "%s/memif.sock" % self.tempdir)
+ remote_socket = VppSocketFilename(
+ self.remote_test, 1, "%s/memif.sock" % self.tempdir
+ )
remote_socket.add_vpp_config()
remote_memif = VppMemif(
self.remote_test,
VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_MASTER,
VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
- socket_id=1)
+ socket_id=1,
+ )
memif.add_vpp_config()
memif.config_ip4()
@@ -281,10 +274,13 @@ class TestMemif(VppTestCase):
self.assertTrue(remote_memif.wait_for_link_up(5))
# add routing to remote vpp
- route = VppIpRoute(self.remote_test, self.pg0._local_ip4_subnet, 24,
- [VppRoutePath(memif.ip_prefix.network_address,
- 0xffffffff)],
- register=False)
+ route = VppIpRoute(
+ self.remote_test,
+ self.pg0._local_ip4_subnet,
+ 24,
+ [VppRoutePath(memif.ip_prefix.network_address, 0xFFFFFFFF)],
+ register=False,
+ )
route.add_vpp_config()
@@ -304,17 +300,19 @@ class TestMemif(VppTestCase):
route.remove_vpp_config()
def test_memif_admin_up_down_up(self):
- """ Memif admin up/down/up """
+ """Memif admin up/down/up"""
memif = VppMemif(
self,
VppEnum.vl_api_memif_role_t.MEMIF_ROLE_API_SLAVE,
VppEnum.vl_api_memif_mode_t.MEMIF_MODE_API_ETHERNET,
ring_size=1024,
buffer_size=2048,
- secret="abc")
+ secret="abc",
+ )
- remote_socket = VppSocketFilename(self.remote_test, 1,
- "%s/memif.sock" % self.tempdir)
+ remote_socket = VppSocketFilename(
+ self.remote_test, 1, "%s/memif.sock" % self.tempdir
+ )
remote_socket.add_vpp_config()
remote_memif = VppMemif(
@@ -324,7 +322,8 @@ class TestMemif(VppTestCase):
socket_id=1,
ring_size=1024,
buffer_size=2048,
- secret="abc")
+ secret="abc",
+ )
memif.add_vpp_config()
remote_memif.add_vpp_config()
@@ -344,5 +343,5 @@ class TestMemif(VppTestCase):
remote_socket.remove_vpp_config()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_mpcap.py b/test/test_mpcap.py
index bfa4385ed1a..e075214a202 100644
--- a/test/test_mpcap.py
+++ b/test/test_mpcap.py
@@ -8,7 +8,7 @@ import os
class TestMpcap(VppTestCase):
- """ Mpcap Unit Test Cases """
+ """Mpcap Unit Test Cases"""
@classmethod
def setUpClass(cls):
@@ -25,22 +25,24 @@ class TestMpcap(VppTestCase):
super(TestMpcap, self).tearDown()
def test_mpcap_unittest(self):
- """ Mapped pcap file test """
- cmds = ["packet-generator new {\n"
- " name mpcap\n"
- " limit 15\n"
- " size 128-128\n"
- " interface local0\n"
- " node mpcap-unittest\n"
- " data {\n"
- " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n"
- " ICMP: db00::1 -> db00::2\n"
- " incrementing 30\n"
- " }\n",
- "trace add pg-input 15",
- "pa en",
- "show trace",
- "show error"]
+ """Mapped pcap file test"""
+ cmds = [
+ "packet-generator new {\n"
+ " name mpcap\n"
+ " limit 15\n"
+ " size 128-128\n"
+ " interface local0\n"
+ " node mpcap-unittest\n"
+ " data {\n"
+ " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n"
+ " ICMP: db00::1 -> db00::2\n"
+ " incrementing 30\n"
+ " }\n",
+ "trace add pg-input 15",
+ "pa en",
+ "show trace",
+ "show error",
+ ]
for cmd in cmds:
self.logger.info(self.vapi.cli(cmd))
@@ -49,7 +51,8 @@ class TestMpcap(VppTestCase):
os.remove("/tmp/mpcap_unittest.pcap")
if size != 2184:
self.logger.critical("BUG: file size %d not 2184" % size)
- self.assertNotIn('WrongMPCAPFileSize', 'WrongMPCAPFileSize')
+ self.assertNotIn("WrongMPCAPFileSize", "WrongMPCAPFileSize")
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_mpls.py b/test/test_mpls.py
index a568f849aed..6e01a03aea1 100644
--- a/test/test_mpls.py
+++ b/test/test_mpls.py
@@ -6,11 +6,24 @@ import socket
from framework import tag_fixme_vpp_workers
from framework import VppTestCase, VppTestRunner
from vpp_ip import DpoProto, INVALID_INDEX
-from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsRoute, \
- VppMplsIpBind, VppIpMRoute, VppMRoutePath, \
- VppIpTable, VppMplsTable, \
- VppMplsLabel, MplsLspMode, find_mpls_route, \
- FibPathProto, FibPathType, FibPathFlags, VppMplsLabel, MplsLspMode
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ VppMplsRoute,
+ VppMplsIpBind,
+ VppIpMRoute,
+ VppMRoutePath,
+ VppIpTable,
+ VppMplsTable,
+ VppMplsLabel,
+ MplsLspMode,
+ find_mpls_route,
+ FibPathProto,
+ FibPathType,
+ FibPathFlags,
+ VppMplsLabel,
+ MplsLspMode,
+)
from vpp_mpls_tunnel_interface import VppMPLSTunnelInterface
from vpp_papi import VppEnum
@@ -18,8 +31,12 @@ import scapy.compat
from scapy.packet import Raw
from scapy.layers.l2 import Ether, ARP
from scapy.layers.inet import IP, UDP, ICMP, icmptypes, icmpcodes
-from scapy.layers.inet6 import IPv6, ICMPv6TimeExceeded, ICMPv6EchoRequest, \
- ICMPv6PacketTooBig
+from scapy.layers.inet6 import (
+ IPv6,
+ ICMPv6TimeExceeded,
+ ICMPv6EchoRequest,
+ ICMPv6PacketTooBig,
+)
from scapy.contrib.mpls import MPLS
NUM_PKTS = 67
@@ -63,7 +80,7 @@ def verify_mpls_stack(tst, rx, mpls_labels):
@tag_fixme_vpp_workers
class TestMPLS(VppTestCase):
- """ MPLS Test Case """
+ """MPLS Test Case"""
@classmethod
def setUpClass(cls):
@@ -120,15 +137,16 @@ class TestMPLS(VppTestCase):
# the default of 64 matches the IP packet TTL default
def create_stream_labelled_ip4(
- self,
- src_if,
- mpls_labels,
- ping=0,
- ip_itf=None,
- dst_ip=None,
- chksum=None,
- ip_ttl=64,
- n=257):
+ self,
+ src_if,
+ mpls_labels,
+ ping=0,
+ ip_itf=None,
+ dst_ip=None,
+ chksum=None,
+ ip_ttl=64,
+ n=257,
+ ):
self.reset_packet_infos()
pkts = []
for i in range(0, n):
@@ -137,25 +155,32 @@ class TestMPLS(VppTestCase):
p = Ether(dst=src_if.local_mac, src=src_if.remote_mac)
for ii in range(len(mpls_labels)):
- p = p / MPLS(label=mpls_labels[ii].value,
- ttl=mpls_labels[ii].ttl,
- cos=mpls_labels[ii].exp)
+ p = p / MPLS(
+ label=mpls_labels[ii].value,
+ ttl=mpls_labels[ii].ttl,
+ cos=mpls_labels[ii].exp,
+ )
if not ping:
if not dst_ip:
- p = (p / IP(src=src_if.local_ip4,
- dst=src_if.remote_ip4,
- ttl=ip_ttl) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ p
+ / IP(src=src_if.local_ip4, dst=src_if.remote_ip4, ttl=ip_ttl)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
else:
- p = (p / IP(src=src_if.local_ip4, dst=dst_ip, ttl=ip_ttl) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ p
+ / IP(src=src_if.local_ip4, dst=dst_ip, ttl=ip_ttl)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
else:
- p = (p / IP(src=ip_itf.remote_ip4,
- dst=ip_itf.local_ip4,
- ttl=ip_ttl) /
- ICMP())
+ p = (
+ p
+ / IP(src=ip_itf.remote_ip4, dst=ip_itf.local_ip4, ttl=ip_ttl)
+ / ICMP()
+ )
if chksum:
p[IP].chksum = chksum
@@ -163,18 +188,20 @@ class TestMPLS(VppTestCase):
pkts.append(p)
return pkts
- def create_stream_ip4(self, src_if, dst_ip, ip_ttl=64,
- ip_dscp=0, payload_size=None):
+ def create_stream_ip4(
+ self, src_if, dst_ip, ip_ttl=64, ip_dscp=0, payload_size=None
+ ):
self.reset_packet_infos()
pkts = []
for i in range(0, 257):
info = self.create_packet_info(src_if, src_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=src_if.remote_ip4, dst=dst_ip,
- ttl=ip_ttl, tos=ip_dscp) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=src_if.remote_ip4, dst=dst_ip, ttl=ip_ttl, tos=ip_dscp)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
if payload_size:
self.extend_packet(p, payload_size)
@@ -187,18 +214,19 @@ class TestMPLS(VppTestCase):
for i in range(0, 257):
info = self.create_packet_info(src_if, src_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IPv6(src=src_if.remote_ip6, dst=dst_ip,
- hlim=ip_ttl, tc=ip_dscp) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IPv6(src=src_if.remote_ip6, dst=dst_ip, hlim=ip_ttl, tc=ip_dscp)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
pkts.append(p)
return pkts
- def create_stream_labelled_ip6(self, src_if, mpls_labels,
- hlim=64, dst_ip=None,
- ping=0, ip_itf=None):
+ def create_stream_labelled_ip6(
+ self, src_if, mpls_labels, hlim=64, dst_ip=None, ping=0, ip_itf=None
+ ):
if dst_ip is None:
dst_ip = src_if.remote_ip6
self.reset_packet_infos()
@@ -211,19 +239,23 @@ class TestMPLS(VppTestCase):
p = p / MPLS(label=l.value, ttl=l.ttl, cos=l.exp)
if ping:
- p = p / (IPv6(src=ip_itf.remote_ip6,
- dst=ip_itf.local_ip6) /
- ICMPv6EchoRequest())
+ p = p / (
+ IPv6(src=ip_itf.remote_ip6, dst=ip_itf.local_ip6)
+ / ICMPv6EchoRequest()
+ )
else:
- p = p / (IPv6(src=src_if.remote_ip6, dst=dst_ip, hlim=hlim) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = p / (
+ IPv6(src=src_if.remote_ip6, dst=dst_ip, hlim=hlim)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
pkts.append(p)
return pkts
- def verify_capture_ip4(self, src_if, capture, sent, ping_resp=0,
- ip_ttl=None, ip_dscp=0):
+ def verify_capture_ip4(
+ self, src_if, capture, sent, ping_resp=0, ip_ttl=None, ip_dscp=0
+ ):
try:
capture = verify_filter(capture, sent)
@@ -256,8 +288,9 @@ class TestMPLS(VppTestCase):
except:
raise
- def verify_capture_labelled_ip4(self, src_if, capture, sent,
- mpls_labels, ip_ttl=None):
+ def verify_capture_labelled_ip4(
+ self, src_if, capture, sent, mpls_labels, ip_ttl=None
+ ):
try:
capture = verify_filter(capture, sent)
@@ -282,8 +315,9 @@ class TestMPLS(VppTestCase):
except:
raise
- def verify_capture_labelled_ip6(self, src_if, capture, sent,
- mpls_labels, ip_ttl=None):
+ def verify_capture_labelled_ip6(
+ self, src_if, capture, sent, mpls_labels, ip_ttl=None
+ ):
try:
capture = verify_filter(capture, sent)
@@ -330,8 +364,7 @@ class TestMPLS(VppTestCase):
except:
raise
- def verify_capture_labelled(self, src_if, capture, sent,
- mpls_labels):
+ def verify_capture_labelled(self, src_if, capture, sent, mpls_labels):
try:
capture = verify_filter(capture, sent)
@@ -343,9 +376,9 @@ class TestMPLS(VppTestCase):
except:
raise
- def verify_capture_ip6(self, src_if, capture, sent,
- ip_hlim=None, ip_dscp=0,
- ping_resp=0):
+ def verify_capture_ip6(
+ self, src_if, capture, sent, ip_hlim=None, ip_dscp=0, ping_resp=0
+ ):
try:
self.assertEqual(len(capture), len(sent))
@@ -363,7 +396,7 @@ class TestMPLS(VppTestCase):
if not ping_resp:
self.assertEqual(rx_ip.src, tx_ip.src)
self.assertEqual(rx_ip.dst, tx_ip.dst)
- self.assertEqual(rx_ip.tc, ip_dscp)
+ self.assertEqual(rx_ip.tc, ip_dscp)
# IP processing post pop has decremented the TTL
if not ip_hlim:
self.assertEqual(rx_ip.hlim + 1, tx_ip.hlim)
@@ -402,8 +435,9 @@ class TestMPLS(VppTestCase):
except:
raise
- def verify_capture_fragmented_labelled_ip4(self, src_if, capture, sent,
- mpls_labels, ip_ttl=None):
+ def verify_capture_fragmented_labelled_ip4(
+ self, src_if, capture, sent, mpls_labels, ip_ttl=None
+ ):
try:
capture = verify_filter(capture, sent)
@@ -426,8 +460,9 @@ class TestMPLS(VppTestCase):
except:
raise
- def verify_capture_fragmented_labelled_ip6(self, src_if, capture, sent,
- mpls_labels, ip_ttl=None):
+ def verify_capture_fragmented_labelled_ip6(
+ self, src_if, capture, sent, mpls_labels, ip_ttl=None
+ ):
try:
capture = verify_filter(capture, sent)
@@ -452,82 +487,115 @@ class TestMPLS(VppTestCase):
raise
def test_swap(self):
- """ MPLS label swap tests """
+ """MPLS label swap tests"""
#
# A simple MPLS xconnect - eos label in label out
#
- route_32_eos = VppMplsRoute(self, 32, 1,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(33)])])
+ route_32_eos = VppMplsRoute(
+ self,
+ 32,
+ 1,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(33)]
+ )
+ ],
+ )
route_32_eos.add_vpp_config()
self.assertTrue(
- find_mpls_route(self, 0, 32, 1,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(33)])]))
+ find_mpls_route(
+ self,
+ 0,
+ 32,
+ 1,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4,
+ self.pg0.sw_if_index,
+ labels=[VppMplsLabel(33)],
+ )
+ ],
+ )
+ )
#
# a stream that matches the route for 10.0.0.1
# PG0 is in the default table
#
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(32, ttl=32, exp=1)])
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(32, ttl=32, exp=1)]
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled(self.pg0, rx, tx,
- [VppMplsLabel(33, ttl=31, exp=1)])
+ self.verify_capture_labelled(
+ self.pg0, rx, tx, [VppMplsLabel(33, ttl=31, exp=1)]
+ )
- self.assertEqual(route_32_eos.get_stats_to()['packets'], 257)
+ self.assertEqual(route_32_eos.get_stats_to()["packets"], 257)
#
# A simple MPLS xconnect - non-eos label in label out
#
- route_32_neos = VppMplsRoute(self, 32, 0,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(33)])])
+ route_32_neos = VppMplsRoute(
+ self,
+ 32,
+ 0,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(33)]
+ )
+ ],
+ )
route_32_neos.add_vpp_config()
#
# a stream that matches the route for 10.0.0.1
# PG0 is in the default table
#
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(32, ttl=21, exp=7),
- VppMplsLabel(99)])
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(32, ttl=21, exp=7), VppMplsLabel(99)]
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled(self.pg0, rx, tx,
- [VppMplsLabel(33, ttl=20, exp=7),
- VppMplsLabel(99)])
- self.assertEqual(route_32_neos.get_stats_to()['packets'], 257)
+ self.verify_capture_labelled(
+ self.pg0, rx, tx, [VppMplsLabel(33, ttl=20, exp=7), VppMplsLabel(99)]
+ )
+ self.assertEqual(route_32_neos.get_stats_to()["packets"], 257)
#
# A simple MPLS xconnect - non-eos label in label out, uniform mode
#
route_42_neos = VppMplsRoute(
- self, 42, 0,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(43, MplsLspMode.UNIFORM)])])
+ self,
+ 42,
+ 0,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4,
+ self.pg0.sw_if_index,
+ labels=[VppMplsLabel(43, MplsLspMode.UNIFORM)],
+ )
+ ],
+ )
route_42_neos.add_vpp_config()
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(42, ttl=21, exp=7),
- VppMplsLabel(99)])
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(42, ttl=21, exp=7), VppMplsLabel(99)]
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled(self.pg0, rx, tx,
- [VppMplsLabel(43, ttl=20, exp=7),
- VppMplsLabel(99)])
+ self.verify_capture_labelled(
+ self.pg0, rx, tx, [VppMplsLabel(43, ttl=20, exp=7), VppMplsLabel(99)]
+ )
#
# An MPLS xconnect - EOS label in IP out
#
- route_33_eos = VppMplsRoute(self, 33, 1,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[])])
+ route_33_eos = VppMplsRoute(
+ self,
+ 33,
+ 1,
+ [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[])],
+ )
route_33_eos.add_vpp_config()
tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(33)])
@@ -537,30 +605,36 @@ class TestMPLS(VppTestCase):
#
# disposed packets have an invalid IPv4 checksum
#
- tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(33)],
- dst_ip=self.pg0.remote_ip4,
- n=65,
- chksum=1)
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(33)], dst_ip=self.pg0.remote_ip4, n=65, chksum=1
+ )
self.send_and_assert_no_replies(self.pg0, tx, "Invalid Checksum")
#
# An MPLS xconnect - EOS label in IP out, uniform mode
#
route_3333_eos = VppMplsRoute(
- self, 3333, 1,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(3, MplsLspMode.UNIFORM)])])
+ self,
+ 3333,
+ 1,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4,
+ self.pg0.sw_if_index,
+ labels=[VppMplsLabel(3, MplsLspMode.UNIFORM)],
+ )
+ ],
+ )
route_3333_eos.add_vpp_config()
tx = self.create_stream_labelled_ip4(
- self.pg0,
- [VppMplsLabel(3333, ttl=55, exp=3)])
+ self.pg0, [VppMplsLabel(3333, ttl=55, exp=3)]
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
self.verify_capture_ip4(self.pg0, rx, tx, ip_ttl=54, ip_dscp=0x60)
tx = self.create_stream_labelled_ip4(
- self.pg0,
- [VppMplsLabel(3333, ttl=66, exp=4)])
+ self.pg0, [VppMplsLabel(3333, ttl=66, exp=4)]
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
self.verify_capture_ip4(self.pg0, rx, tx, ip_ttl=65, ip_dscp=0x80)
@@ -568,11 +642,12 @@ class TestMPLS(VppTestCase):
# An MPLS xconnect - EOS label in IPv6 out
#
route_333_eos = VppMplsRoute(
- self, 333, 1,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index,
- labels=[])],
- eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)
+ self,
+ 333,
+ 1,
+ [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index, labels=[])],
+ eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
route_333_eos.add_vpp_config()
tx = self.create_stream_labelled_ip6(self.pg0, [VppMplsLabel(333)])
@@ -582,10 +657,9 @@ class TestMPLS(VppTestCase):
#
# disposed packets have an TTL expired
#
- tx = self.create_stream_labelled_ip6(self.pg0,
- [VppMplsLabel(333, ttl=64)],
- dst_ip=self.pg1.remote_ip6,
- hlim=1)
+ tx = self.create_stream_labelled_ip6(
+ self.pg0, [VppMplsLabel(333, ttl=64)], dst_ip=self.pg1.remote_ip6, hlim=1
+ )
rx = self.send_and_expect_some(self.pg0, tx, self.pg0)
self.verify_capture_ip6_icmp(self.pg0, rx, tx)
@@ -593,15 +667,19 @@ class TestMPLS(VppTestCase):
# An MPLS xconnect - EOS label in IPv6 out w imp-null
#
route_334_eos = VppMplsRoute(
- self, 334, 1,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(3)])],
- eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)
+ self,
+ 334,
+ 1,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip6, self.pg0.sw_if_index, labels=[VppMplsLabel(3)]
+ )
+ ],
+ eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
route_334_eos.add_vpp_config()
- tx = self.create_stream_labelled_ip6(self.pg0,
- [VppMplsLabel(334, ttl=64)])
+ tx = self.create_stream_labelled_ip6(self.pg0, [VppMplsLabel(334, ttl=64)])
rx = self.send_and_expect(self.pg0, tx, self.pg0)
self.verify_capture_ip6(self.pg0, rx, tx)
@@ -609,25 +687,32 @@ class TestMPLS(VppTestCase):
# An MPLS xconnect - EOS label in IPv6 out w imp-null in uniform mode
#
route_335_eos = VppMplsRoute(
- self, 335, 1,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(3, MplsLspMode.UNIFORM)])],
- eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)
+ self,
+ 335,
+ 1,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip6,
+ self.pg0.sw_if_index,
+ labels=[VppMplsLabel(3, MplsLspMode.UNIFORM)],
+ )
+ ],
+ eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
route_335_eos.add_vpp_config()
tx = self.create_stream_labelled_ip6(
- self.pg0,
- [VppMplsLabel(335, ttl=27, exp=4)])
+ self.pg0, [VppMplsLabel(335, ttl=27, exp=4)]
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
self.verify_capture_ip6(self.pg0, rx, tx, ip_hlim=26, ip_dscp=0x80)
#
# disposed packets have an TTL expired
#
- tx = self.create_stream_labelled_ip6(self.pg0, [VppMplsLabel(334)],
- dst_ip=self.pg1.remote_ip6,
- hlim=0)
+ tx = self.create_stream_labelled_ip6(
+ self.pg0, [VppMplsLabel(334)], dst_ip=self.pg1.remote_ip6, hlim=0
+ )
rx = self.send_and_expect_some(self.pg0, tx, self.pg0)
self.verify_capture_ip6_icmp(self.pg0, rx, tx)
@@ -635,104 +720,136 @@ class TestMPLS(VppTestCase):
# An MPLS xconnect - non-EOS label in IP out - an invalid configuration
# so this traffic should be dropped.
#
- route_33_neos = VppMplsRoute(self, 33, 0,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[])])
+ route_33_neos = VppMplsRoute(
+ self,
+ 33,
+ 0,
+ [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[])],
+ )
route_33_neos.add_vpp_config()
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(33),
- VppMplsLabel(99)])
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(33), VppMplsLabel(99)]
+ )
self.send_and_assert_no_replies(
- self.pg0, tx,
- "MPLS non-EOS packets popped and forwarded")
+ self.pg0, tx, "MPLS non-EOS packets popped and forwarded"
+ )
#
# A recursive EOS x-connect, which resolves through another x-connect
# in pipe mode
#
- route_34_eos = VppMplsRoute(self, 34, 1,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_via_label=32,
- labels=[VppMplsLabel(44),
- VppMplsLabel(45)])])
+ route_34_eos = VppMplsRoute(
+ self,
+ 34,
+ 1,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ nh_via_label=32,
+ labels=[VppMplsLabel(44), VppMplsLabel(45)],
+ )
+ ],
+ )
route_34_eos.add_vpp_config()
self.logger.info(self.vapi.cli("sh mpls fib 34"))
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(34, ttl=3)])
+ tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(34, ttl=3)])
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled(self.pg0, rx, tx,
- [VppMplsLabel(33),
- VppMplsLabel(44),
- VppMplsLabel(45, ttl=2)])
+ self.verify_capture_labelled(
+ self.pg0,
+ rx,
+ tx,
+ [VppMplsLabel(33), VppMplsLabel(44), VppMplsLabel(45, ttl=2)],
+ )
- self.assertEqual(route_34_eos.get_stats_to()['packets'], 257)
- self.assertEqual(route_32_neos.get_stats_via()['packets'], 257)
+ self.assertEqual(route_34_eos.get_stats_to()["packets"], 257)
+ self.assertEqual(route_32_neos.get_stats_via()["packets"], 257)
#
# A recursive EOS x-connect, which resolves through another x-connect
# in uniform mode
#
route_35_eos = VppMplsRoute(
- self, 35, 1,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_via_label=42,
- labels=[VppMplsLabel(44)])])
+ self,
+ 35,
+ 1,
+ [
+ VppRoutePath(
+ "0.0.0.0", 0xFFFFFFFF, nh_via_label=42, labels=[VppMplsLabel(44)]
+ )
+ ],
+ )
route_35_eos.add_vpp_config()
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(35, ttl=3)])
+ tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(35, ttl=3)])
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled(self.pg0, rx, tx,
- [VppMplsLabel(43, ttl=2),
- VppMplsLabel(44, ttl=2)])
+ self.verify_capture_labelled(
+ self.pg0, rx, tx, [VppMplsLabel(43, ttl=2), VppMplsLabel(44, ttl=2)]
+ )
#
# A recursive non-EOS x-connect, which resolves through another
# x-connect
#
- route_34_neos = VppMplsRoute(self, 34, 0,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_via_label=32,
- labels=[VppMplsLabel(44),
- VppMplsLabel(46)])])
+ route_34_neos = VppMplsRoute(
+ self,
+ 34,
+ 0,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ nh_via_label=32,
+ labels=[VppMplsLabel(44), VppMplsLabel(46)],
+ )
+ ],
+ )
route_34_neos.add_vpp_config()
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(34, ttl=45),
- VppMplsLabel(99)])
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(34, ttl=45), VppMplsLabel(99)]
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
# it's the 2nd (counting from 0) label in the stack that is swapped
- self.verify_capture_labelled(self.pg0, rx, tx,
- [VppMplsLabel(33),
- VppMplsLabel(44),
- VppMplsLabel(46, ttl=44),
- VppMplsLabel(99)])
+ self.verify_capture_labelled(
+ self.pg0,
+ rx,
+ tx,
+ [
+ VppMplsLabel(33),
+ VppMplsLabel(44),
+ VppMplsLabel(46, ttl=44),
+ VppMplsLabel(99),
+ ],
+ )
#
# an recursive IP route that resolves through the recursive non-eos
# x-connect
#
- ip_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_via_label=34,
- labels=[VppMplsLabel(55)])])
+ ip_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0", 0xFFFFFFFF, nh_via_label=34, labels=[VppMplsLabel(55)]
+ )
+ ],
+ )
ip_10_0_0_1.add_vpp_config()
tx = self.create_stream_ip4(self.pg0, "10.0.0.1")
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(33),
- VppMplsLabel(44),
- VppMplsLabel(46),
- VppMplsLabel(55)])
- self.assertEqual(ip_10_0_0_1.get_stats_to()['packets'], 257)
+ self.verify_capture_labelled_ip4(
+ self.pg0,
+ rx,
+ tx,
+ [VppMplsLabel(33), VppMplsLabel(44), VppMplsLabel(46), VppMplsLabel(55)],
+ )
+ self.assertEqual(ip_10_0_0_1.get_stats_to()["packets"], 257)
ip_10_0_0_1.remove_vpp_config()
route_34_neos.remove_vpp_config()
@@ -743,15 +860,21 @@ class TestMPLS(VppTestCase):
route_32_eos.remove_vpp_config()
def test_bind(self):
- """ MPLS Local Label Binding test """
+ """MPLS Local Label Binding test"""
#
# Add a non-recursive route with a single out label
#
- route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(45)])])
+ route_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(45)]
+ )
+ ],
+ )
route_10_0_0_1.add_vpp_config()
# bind a local label to the route
@@ -759,19 +882,18 @@ class TestMPLS(VppTestCase):
binding.add_vpp_config()
# non-EOS stream
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(44),
- VppMplsLabel(99)])
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(44), VppMplsLabel(99)]
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled(self.pg0, rx, tx,
- [VppMplsLabel(45, ttl=63),
- VppMplsLabel(99)])
+ self.verify_capture_labelled(
+ self.pg0, rx, tx, [VppMplsLabel(45, ttl=63), VppMplsLabel(99)]
+ )
# EOS stream
tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(44)])
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled(self.pg0, rx, tx,
- [VppMplsLabel(45, ttl=63)])
+ self.verify_capture_labelled(self.pg0, rx, tx, [VppMplsLabel(45, ttl=63)])
# IP stream
tx = self.create_stream_ip4(self.pg0, "10.0.0.1")
@@ -785,15 +907,21 @@ class TestMPLS(VppTestCase):
route_10_0_0_1.remove_vpp_config()
def test_imposition(self):
- """ MPLS label imposition test """
+ """MPLS label imposition test"""
#
# Add a non-recursive route with a single out label
#
- route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(32)])])
+ route_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(32)]
+ )
+ ],
+ )
route_10_0_0_1.add_vpp_config()
#
@@ -807,65 +935,86 @@ class TestMPLS(VppTestCase):
#
# Add a non-recursive route with a 3 out labels
#
- route_10_0_0_2 = VppIpRoute(self, "10.0.0.2", 32,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(32),
- VppMplsLabel(33),
- VppMplsLabel(34)])])
+ route_10_0_0_2 = VppIpRoute(
+ self,
+ "10.0.0.2",
+ 32,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4,
+ self.pg0.sw_if_index,
+ labels=[VppMplsLabel(32), VppMplsLabel(33), VppMplsLabel(34)],
+ )
+ ],
+ )
route_10_0_0_2.add_vpp_config()
- tx = self.create_stream_ip4(self.pg0, "10.0.0.2",
- ip_ttl=44, ip_dscp=0xff)
+ tx = self.create_stream_ip4(self.pg0, "10.0.0.2", ip_ttl=44, ip_dscp=0xFF)
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32),
- VppMplsLabel(33),
- VppMplsLabel(34)],
- ip_ttl=43)
+ self.verify_capture_labelled_ip4(
+ self.pg0,
+ rx,
+ tx,
+ [VppMplsLabel(32), VppMplsLabel(33), VppMplsLabel(34)],
+ ip_ttl=43,
+ )
#
# Add a non-recursive route with a single out label in uniform mode
#
route_10_0_0_3 = VppIpRoute(
- self, "10.0.0.3", 32,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(32,
- mode=MplsLspMode.UNIFORM)])])
+ self,
+ "10.0.0.3",
+ 32,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4,
+ self.pg0.sw_if_index,
+ labels=[VppMplsLabel(32, mode=MplsLspMode.UNIFORM)],
+ )
+ ],
+ )
route_10_0_0_3.add_vpp_config()
- tx = self.create_stream_ip4(self.pg0, "10.0.0.3",
- ip_ttl=54, ip_dscp=0xbe)
+ tx = self.create_stream_ip4(self.pg0, "10.0.0.3", ip_ttl=54, ip_dscp=0xBE)
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32, ttl=53, exp=5)])
+ self.verify_capture_labelled_ip4(
+ self.pg0, rx, tx, [VppMplsLabel(32, ttl=53, exp=5)]
+ )
#
# Add a IPv6 non-recursive route with a single out label in
# uniform mode
#
route_2001_3 = VppIpRoute(
- self, "2001::3", 128,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(32,
- mode=MplsLspMode.UNIFORM)])])
+ self,
+ "2001::3",
+ 128,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip6,
+ self.pg0.sw_if_index,
+ labels=[VppMplsLabel(32, mode=MplsLspMode.UNIFORM)],
+ )
+ ],
+ )
route_2001_3.add_vpp_config()
- tx = self.create_stream_ip6(self.pg0, "2001::3",
- ip_ttl=54, ip_dscp=0xbe)
+ tx = self.create_stream_ip6(self.pg0, "2001::3", ip_ttl=54, ip_dscp=0xBE)
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled_ip6(self.pg0, rx, tx,
- [VppMplsLabel(32, ttl=53, exp=5)])
+ self.verify_capture_labelled_ip6(
+ self.pg0, rx, tx, [VppMplsLabel(32, ttl=53, exp=5)]
+ )
#
# add a recursive path, with output label, via the 1 label route
#
- route_11_0_0_1 = VppIpRoute(self, "11.0.0.1", 32,
- [VppRoutePath("10.0.0.1",
- 0xffffffff,
- labels=[VppMplsLabel(44)])])
+ route_11_0_0_1 = VppIpRoute(
+ self,
+ "11.0.0.1",
+ 32,
+ [VppRoutePath("10.0.0.1", 0xFFFFFFFF, labels=[VppMplsLabel(44)])],
+ )
route_11_0_0_1.add_vpp_config()
#
@@ -874,20 +1023,25 @@ class TestMPLS(VppTestCase):
#
tx = self.create_stream_ip4(self.pg0, "11.0.0.1")
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32),
- VppMplsLabel(44)])
+ self.verify_capture_labelled_ip4(
+ self.pg0, rx, tx, [VppMplsLabel(32), VppMplsLabel(44)]
+ )
- self.assertEqual(route_11_0_0_1.get_stats_to()['packets'], 257)
+ self.assertEqual(route_11_0_0_1.get_stats_to()["packets"], 257)
#
# add a recursive path, with 2 labels, via the 3 label route
#
- route_11_0_0_2 = VppIpRoute(self, "11.0.0.2", 32,
- [VppRoutePath("10.0.0.2",
- 0xffffffff,
- labels=[VppMplsLabel(44),
- VppMplsLabel(45)])])
+ route_11_0_0_2 = VppIpRoute(
+ self,
+ "11.0.0.2",
+ 32,
+ [
+ VppRoutePath(
+ "10.0.0.2", 0xFFFFFFFF, labels=[VppMplsLabel(44), VppMplsLabel(45)]
+ )
+ ],
+ )
route_11_0_0_2.add_vpp_config()
#
@@ -896,24 +1050,36 @@ class TestMPLS(VppTestCase):
#
tx = self.create_stream_ip4(self.pg0, "11.0.0.2")
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32),
- VppMplsLabel(33),
- VppMplsLabel(34),
- VppMplsLabel(44),
- VppMplsLabel(45)])
-
- self.assertEqual(route_11_0_0_2.get_stats_to()['packets'], 257)
+ self.verify_capture_labelled_ip4(
+ self.pg0,
+ rx,
+ tx,
+ [
+ VppMplsLabel(32),
+ VppMplsLabel(33),
+ VppMplsLabel(34),
+ VppMplsLabel(44),
+ VppMplsLabel(45),
+ ],
+ )
+
+ self.assertEqual(route_11_0_0_2.get_stats_to()["packets"], 257)
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32),
- VppMplsLabel(33),
- VppMplsLabel(34),
- VppMplsLabel(44),
- VppMplsLabel(45)])
+ self.verify_capture_labelled_ip4(
+ self.pg0,
+ rx,
+ tx,
+ [
+ VppMplsLabel(32),
+ VppMplsLabel(33),
+ VppMplsLabel(34),
+ VppMplsLabel(44),
+ VppMplsLabel(45),
+ ],
+ )
- self.assertEqual(route_11_0_0_2.get_stats_to()['packets'], 514)
+ self.assertEqual(route_11_0_0_2.get_stats_to()["packets"], 514)
#
# cleanup
@@ -924,20 +1090,32 @@ class TestMPLS(VppTestCase):
route_10_0_0_1.remove_vpp_config()
def test_imposition_fragmentation(self):
- """ MPLS label imposition fragmentation test """
+ """MPLS label imposition fragmentation test"""
#
# Add a ipv4 non-recursive route with a single out label
#
- route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(32)])])
+ route_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(32)]
+ )
+ ],
+ )
route_10_0_0_1.add_vpp_config()
- route_1000_1 = VppIpRoute(self, "1000::1", 128,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(32)])])
+ route_1000_1 = VppIpRoute(
+ self,
+ "1000::1",
+ 128,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip6, self.pg0.sw_if_index, labels=[VppMplsLabel(32)]
+ )
+ ],
+ )
route_1000_1.add_vpp_config()
#
@@ -952,24 +1130,29 @@ class TestMPLS(VppTestCase):
# 5 fragments per packet (257*5=1285)
#
rx = self.send_and_expect(self.pg0, tx, self.pg0, 1285)
- self.verify_capture_fragmented_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32)])
+ self.verify_capture_fragmented_labelled_ip4(
+ self.pg0, rx, tx, [VppMplsLabel(32)]
+ )
# packets with DF bit set generate ICMP
for t in tx:
- t[IP].flags = 'DF'
+ t[IP].flags = "DF"
rxs = self.send_and_expect_some(self.pg0, tx, self.pg0)
for rx in rxs:
self.assertEqual(icmptypes[rx[ICMP].type], "dest-unreach")
- self.assertEqual(icmpcodes[rx[ICMP].type][rx[ICMP].code],
- "fragmentation-needed")
+ self.assertEqual(
+ icmpcodes[rx[ICMP].type][rx[ICMP].code], "fragmentation-needed"
+ )
# the link MTU is 9000, the MPLS over head is 4 bytes
self.assertEqual(rx[ICMP].nexthopmtu, 9000 - 4)
- self.assertEqual(self.statistics.get_err_counter(
- "/err/mpls-frag/can't fragment this packet"),
- len(tx))
+ self.assertEqual(
+ self.statistics.get_err_counter(
+ "/err/mpls-frag/can't fragment this packet"
+ ),
+ len(tx),
+ )
#
# a stream that matches the route for 1000::1/128
# PG0 is in the default table
@@ -988,26 +1171,30 @@ class TestMPLS(VppTestCase):
route_10_0_0_1.remove_vpp_config()
def test_tunnel_pipe(self):
- """ MPLS Tunnel Tests - Pipe """
+ """MPLS Tunnel Tests - Pipe"""
#
# Create a tunnel with two out labels
#
mpls_tun = VppMPLSTunnelInterface(
self,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(44),
- VppMplsLabel(46)])])
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4,
+ self.pg0.sw_if_index,
+ labels=[VppMplsLabel(44), VppMplsLabel(46)],
+ )
+ ],
+ )
mpls_tun.add_vpp_config()
mpls_tun.admin_up()
#
# add an unlabelled route through the new tunnel
#
- route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32,
- [VppRoutePath("0.0.0.0",
- mpls_tun._sw_if_index)])
+ route_10_0_0_3 = VppIpRoute(
+ self, "10.0.0.3", 32, [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index)]
+ )
route_10_0_0_3.add_vpp_config()
self.vapi.cli("clear trace")
@@ -1018,17 +1205,19 @@ class TestMPLS(VppTestCase):
self.pg_start()
rx = self.pg0.get_capture()
- self.verify_capture_tunneled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(44),
- VppMplsLabel(46)])
+ self.verify_capture_tunneled_ip4(
+ self.pg0, rx, tx, [VppMplsLabel(44), VppMplsLabel(46)]
+ )
#
# add a labelled route through the new tunnel
#
- route_10_0_0_4 = VppIpRoute(self, "10.0.0.4", 32,
- [VppRoutePath("0.0.0.0",
- mpls_tun._sw_if_index,
- labels=[33])])
+ route_10_0_0_4 = VppIpRoute(
+ self,
+ "10.0.0.4",
+ 32,
+ [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index, labels=[33])],
+ )
route_10_0_0_4.add_vpp_config()
self.vapi.cli("clear trace")
@@ -1039,10 +1228,12 @@ class TestMPLS(VppTestCase):
self.pg_start()
rx = self.pg0.get_capture()
- self.verify_capture_tunneled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(44),
- VppMplsLabel(46),
- VppMplsLabel(33, ttl=255)])
+ self.verify_capture_tunneled_ip4(
+ self.pg0,
+ rx,
+ tx,
+ [VppMplsLabel(44), VppMplsLabel(46), VppMplsLabel(33, ttl=255)],
+ )
#
# change tunnel's MTU to a low value
@@ -1050,34 +1241,34 @@ class TestMPLS(VppTestCase):
mpls_tun.set_l3_mtu(1200)
# send IP into the tunnel to be fragmented
- tx = self.create_stream_ip4(self.pg0, "10.0.0.3",
- payload_size=1500)
- rx = self.send_and_expect(self.pg0, tx, self.pg0, len(tx)*2)
+ tx = self.create_stream_ip4(self.pg0, "10.0.0.3", payload_size=1500)
+ rx = self.send_and_expect(self.pg0, tx, self.pg0, len(tx) * 2)
fake_tx = []
for p in tx:
fake_tx.append(p)
fake_tx.append(p)
- self.verify_capture_tunneled_ip4(self.pg0, rx, fake_tx,
- [VppMplsLabel(44),
- VppMplsLabel(46)])
+ self.verify_capture_tunneled_ip4(
+ self.pg0, rx, fake_tx, [VppMplsLabel(44), VppMplsLabel(46)]
+ )
# send MPLS into the tunnel to be fragmented
- tx = self.create_stream_ip4(self.pg0, "10.0.0.4",
- payload_size=1500)
- rx = self.send_and_expect(self.pg0, tx, self.pg0, len(tx)*2)
+ tx = self.create_stream_ip4(self.pg0, "10.0.0.4", payload_size=1500)
+ rx = self.send_and_expect(self.pg0, tx, self.pg0, len(tx) * 2)
fake_tx = []
for p in tx:
fake_tx.append(p)
fake_tx.append(p)
- self.verify_capture_tunneled_ip4(self.pg0, rx, fake_tx,
- [VppMplsLabel(44),
- VppMplsLabel(46),
- VppMplsLabel(33, ttl=255)])
+ self.verify_capture_tunneled_ip4(
+ self.pg0,
+ rx,
+ fake_tx,
+ [VppMplsLabel(44), VppMplsLabel(46), VppMplsLabel(33, ttl=255)],
+ )
def test_tunnel_uniform(self):
- """ MPLS Tunnel Tests - Uniform """
+ """MPLS Tunnel Tests - Uniform"""
#
# Create a tunnel with a single out label
@@ -1085,19 +1276,26 @@ class TestMPLS(VppTestCase):
#
mpls_tun = VppMPLSTunnelInterface(
self,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(44, ttl=32),
- VppMplsLabel(46, MplsLspMode.UNIFORM)])])
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4,
+ self.pg0.sw_if_index,
+ labels=[
+ VppMplsLabel(44, ttl=32),
+ VppMplsLabel(46, MplsLspMode.UNIFORM),
+ ],
+ )
+ ],
+ )
mpls_tun.add_vpp_config()
mpls_tun.admin_up()
#
# add an unlabelled route through the new tunnel
#
- route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32,
- [VppRoutePath("0.0.0.0",
- mpls_tun._sw_if_index)])
+ route_10_0_0_3 = VppIpRoute(
+ self, "10.0.0.3", 32, [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index)]
+ )
route_10_0_0_3.add_vpp_config()
self.vapi.cli("clear trace")
@@ -1108,18 +1306,23 @@ class TestMPLS(VppTestCase):
self.pg_start()
rx = self.pg0.get_capture()
- self.verify_capture_tunneled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(44, ttl=32),
- VppMplsLabel(46, ttl=23)])
+ self.verify_capture_tunneled_ip4(
+ self.pg0, rx, tx, [VppMplsLabel(44, ttl=32), VppMplsLabel(46, ttl=23)]
+ )
#
# add a labelled route through the new tunnel
#
route_10_0_0_4 = VppIpRoute(
- self, "10.0.0.4", 32,
- [VppRoutePath("0.0.0.0",
- mpls_tun._sw_if_index,
- labels=[VppMplsLabel(33, ttl=47)])])
+ self,
+ "10.0.0.4",
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0", mpls_tun._sw_if_index, labels=[VppMplsLabel(33, ttl=47)]
+ )
+ ],
+ )
route_10_0_0_4.add_vpp_config()
self.vapi.cli("clear trace")
@@ -1130,45 +1333,63 @@ class TestMPLS(VppTestCase):
self.pg_start()
rx = self.pg0.get_capture()
- self.verify_capture_tunneled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(44, ttl=32),
- VppMplsLabel(46, ttl=47),
- VppMplsLabel(33, ttl=47)])
+ self.verify_capture_tunneled_ip4(
+ self.pg0,
+ rx,
+ tx,
+ [
+ VppMplsLabel(44, ttl=32),
+ VppMplsLabel(46, ttl=47),
+ VppMplsLabel(33, ttl=47),
+ ],
+ )
def test_mpls_tunnel_many(self):
- """ MPLS Multiple Tunnels """
+ """MPLS Multiple Tunnels"""
for ii in range(100):
mpls_tun = VppMPLSTunnelInterface(
self,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(44, ttl=32),
- VppMplsLabel(46, MplsLspMode.UNIFORM)])])
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4,
+ self.pg0.sw_if_index,
+ labels=[
+ VppMplsLabel(44, ttl=32),
+ VppMplsLabel(46, MplsLspMode.UNIFORM),
+ ],
+ )
+ ],
+ )
mpls_tun.add_vpp_config()
mpls_tun.admin_up()
for ii in range(100):
mpls_tun = VppMPLSTunnelInterface(
self,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(44, ttl=32),
- VppMplsLabel(46, MplsLspMode.UNIFORM)])],
- is_l2=1)
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4,
+ self.pg0.sw_if_index,
+ labels=[
+ VppMplsLabel(44, ttl=32),
+ VppMplsLabel(46, MplsLspMode.UNIFORM),
+ ],
+ )
+ ],
+ is_l2=1,
+ )
mpls_tun.add_vpp_config()
mpls_tun.admin_up()
def test_v4_exp_null(self):
- """ MPLS V4 Explicit NULL test """
+ """MPLS V4 Explicit NULL test"""
#
# The first test case has an MPLS TTL of 0
# all packet should be dropped
#
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(0, ttl=0)])
- self.send_and_assert_no_replies(self.pg0, tx,
- "MPLS TTL=0 packets forwarded")
+ tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(0, ttl=0)])
+ self.send_and_assert_no_replies(self.pg0, tx, "MPLS TTL=0 packets forwarded")
#
# a stream with a non-zero MPLS TTL
@@ -1188,7 +1409,7 @@ class TestMPLS(VppTestCase):
self.verify_capture_ip4(self.pg1, rx, tx)
def test_v6_exp_null(self):
- """ MPLS V6 Explicit NULL test """
+ """MPLS V6 Explicit NULL test"""
#
# a stream with a non-zero MPLS TTL
@@ -1208,42 +1429,40 @@ class TestMPLS(VppTestCase):
self.verify_capture_ip6(self.pg0, rx, tx)
def test_deag(self):
- """ MPLS Deagg """
+ """MPLS Deagg"""
#
# A de-agg route - next-hop lookup in default table
#
- route_34_eos = VppMplsRoute(self, 34, 1,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=0)])
+ route_34_eos = VppMplsRoute(
+ self, 34, 1, [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)]
+ )
route_34_eos.add_vpp_config()
#
# ping an interface in the default table
# PG0 is in the default table
#
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(34)],
- ping=1,
- ip_itf=self.pg0)
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(34)], ping=1, ip_itf=self.pg0
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg0)
self.verify_capture_ip4(self.pg0, rx, tx, ping_resp=1)
#
# A de-agg route - next-hop lookup in non-default table
#
- route_35_eos = VppMplsRoute(self, 35, 1,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=1)])
+ route_35_eos = VppMplsRoute(
+ self, 35, 1, [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)]
+ )
route_35_eos.add_vpp_config()
route_356_eos = VppMplsRoute(
- self, 356, 1,
- [VppRoutePath("0::0",
- 0xffffffff,
- nh_table_id=1)],
- eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)
+ self,
+ 356,
+ 1,
+ [VppRoutePath("0::0", 0xFFFFFFFF, nh_table_id=1)],
+ eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
route_356_eos.add_vpp_config()
#
@@ -1252,26 +1471,25 @@ class TestMPLS(VppTestCase):
# default table and egress unlabelled in the non-default
#
tx = self.create_stream_labelled_ip4(
- self.pg0, [VppMplsLabel(35)], ping=1, ip_itf=self.pg1)
+ self.pg0, [VppMplsLabel(35)], ping=1, ip_itf=self.pg1
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg1)
self.verify_capture_ip4(self.pg1, rx, tx, ping_resp=1)
tx = self.create_stream_labelled_ip6(
- self.pg0, [VppMplsLabel(356)], ping=1, ip_itf=self.pg1)
+ self.pg0, [VppMplsLabel(356)], ping=1, ip_itf=self.pg1
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg1)
self.verify_capture_ip6(self.pg1, rx, tx, ping_resp=1)
#
# Double pop
#
- route_36_neos = VppMplsRoute(self, 36, 0,
- [VppRoutePath("0.0.0.0",
- 0xffffffff)])
+ route_36_neos = VppMplsRoute(self, 36, 0, [VppRoutePath("0.0.0.0", 0xFFFFFFFF)])
route_36_neos.add_vpp_config()
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(36),
- VppMplsLabel(35)],
- ping=1, ip_itf=self.pg1)
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(36), VppMplsLabel(35)], ping=1, ip_itf=self.pg1
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg1)
self.verify_capture_ip4(self.pg1, rx, tx, ping_resp=1)
@@ -1280,16 +1498,19 @@ class TestMPLS(VppTestCase):
route_34_eos.remove_vpp_config()
def test_interface_rx(self):
- """ MPLS Interface Receive """
+ """MPLS Interface Receive"""
#
# Add a non-recursive route that will forward the traffic
# post-interface-rx
#
- route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- table_id=1,
- paths=[VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ table_id=1,
+ paths=[VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_10_0_0_1.add_vpp_config()
#
@@ -1301,33 +1522,43 @@ class TestMPLS(VppTestCase):
# so as to have matched the route in table 1
#
route_34_eos = VppMplsRoute(
- self, 34, 1,
- [VppRoutePath("0.0.0.0",
- self.pg1.sw_if_index,
- type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX)])
+ self,
+ 34,
+ 1,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ self.pg1.sw_if_index,
+ type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX,
+ )
+ ],
+ )
route_34_eos.add_vpp_config()
#
# ping an interface in the default table
# PG0 is in the default table
#
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(34)],
- dst_ip="10.0.0.1")
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(34)], dst_ip="10.0.0.1"
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg1)
self.verify_capture_ip4(self.pg1, rx, tx)
def test_mcast_mid_point(self):
- """ MPLS Multicast Mid Point """
+ """MPLS Multicast Mid Point"""
#
# Add a non-recursive route that will forward the traffic
# post-interface-rx
#
- route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- table_id=1,
- paths=[VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ table_id=1,
+ paths=[VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_10_0_0_1.add_vpp_config()
#
@@ -1335,17 +1566,28 @@ class TestMPLS(VppTestCase):
# and replicate to a interface-rx (like a bud node would)
#
route_3400_eos = VppMplsRoute(
- self, 3400, 1,
- [VppRoutePath(self.pg2.remote_ip4,
- self.pg2.sw_if_index,
- labels=[VppMplsLabel(3401)]),
- VppRoutePath(self.pg3.remote_ip4,
- self.pg3.sw_if_index,
- labels=[VppMplsLabel(3402)]),
- VppRoutePath("0.0.0.0",
- self.pg1.sw_if_index,
- type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX)],
- is_multicast=1)
+ self,
+ 3400,
+ 1,
+ [
+ VppRoutePath(
+ self.pg2.remote_ip4,
+ self.pg2.sw_if_index,
+ labels=[VppMplsLabel(3401)],
+ ),
+ VppRoutePath(
+ self.pg3.remote_ip4,
+ self.pg3.sw_if_index,
+ labels=[VppMplsLabel(3402)],
+ ),
+ VppRoutePath(
+ "0.0.0.0",
+ self.pg1.sw_if_index,
+ type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX,
+ ),
+ ],
+ is_multicast=1,
+ )
route_3400_eos.add_vpp_config()
#
@@ -1353,10 +1595,9 @@ class TestMPLS(VppTestCase):
# PG0 is in the default table
#
self.vapi.cli("clear trace")
- tx = self.create_stream_labelled_ip4(self.pg0,
- [VppMplsLabel(3400, ttl=64)],
- n=257,
- dst_ip="10.0.0.1")
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(3400, ttl=64)], n=257, dst_ip="10.0.0.1"
+ )
self.pg0.add_stream(tx)
self.pg_enable_capture(self.pg_interfaces)
@@ -1366,14 +1607,12 @@ class TestMPLS(VppTestCase):
self.verify_capture_ip4(self.pg1, rx, tx)
rx = self.pg2.get_capture(257)
- self.verify_capture_labelled(self.pg2, rx, tx,
- [VppMplsLabel(3401, ttl=63)])
+ self.verify_capture_labelled(self.pg2, rx, tx, [VppMplsLabel(3401, ttl=63)])
rx = self.pg3.get_capture(257)
- self.verify_capture_labelled(self.pg3, rx, tx,
- [VppMplsLabel(3402, ttl=63)])
+ self.verify_capture_labelled(self.pg3, rx, tx, [VppMplsLabel(3402, ttl=63)])
def test_mcast_head(self):
- """ MPLS Multicast Head-end """
+ """MPLS Multicast Head-end"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -1383,22 +1622,25 @@ class TestMPLS(VppTestCase):
#
mpls_tun = VppMPLSTunnelInterface(
self,
- [VppRoutePath(self.pg2.remote_ip4,
- self.pg2.sw_if_index,
- labels=[VppMplsLabel(42)]),
- VppRoutePath(self.pg3.remote_ip4,
- self.pg3.sw_if_index,
- labels=[VppMplsLabel(43)])],
- is_multicast=1)
+ [
+ VppRoutePath(
+ self.pg2.remote_ip4, self.pg2.sw_if_index, labels=[VppMplsLabel(42)]
+ ),
+ VppRoutePath(
+ self.pg3.remote_ip4, self.pg3.sw_if_index, labels=[VppMplsLabel(43)]
+ ),
+ ],
+ is_multicast=1,
+ )
mpls_tun.add_vpp_config()
mpls_tun.admin_up()
#
# add an unlabelled route through the new tunnel
#
- route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32,
- [VppRoutePath("0.0.0.0",
- mpls_tun._sw_if_index)])
+ route_10_0_0_3 = VppIpRoute(
+ self, "10.0.0.3", 32, [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index)]
+ )
route_10_0_0_3.add_vpp_config()
self.vapi.cli("clear trace")
@@ -1421,12 +1663,18 @@ class TestMPLS(VppTestCase):
route_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
- [VppMRoutePath(self.pg0.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT),
- VppMRoutePath(mpls_tun._sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ [
+ VppMRoutePath(
+ self.pg0.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_ACCEPT
+ ),
+ VppMRoutePath(
+ mpls_tun._sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ ),
+ ],
+ )
route_232_1_1_1.add_vpp_config()
self.logger.info(self.vapi.cli("sh ip mfib index 0"))
@@ -1443,7 +1691,7 @@ class TestMPLS(VppTestCase):
self.verify_capture_tunneled_ip4(self.pg0, rx, tx, [VppMplsLabel(43)])
def test_mcast_ip4_tail(self):
- """ MPLS IPv4 Multicast Tail """
+ """MPLS IPv4 Multicast Tail"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -1455,11 +1703,16 @@ class TestMPLS(VppTestCase):
route_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
- "232.1.1.1", 32,
+ "232.1.1.1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
table_id=1,
- paths=[VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD)])
+ paths=[
+ VppMRoutePath(
+ self.pg1.sw_if_index, MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD
+ )
+ ],
+ )
route_232_1_1_1.add_vpp_config()
#
@@ -1471,13 +1724,13 @@ class TestMPLS(VppTestCase):
# table 1
#
route_34_eos = VppMplsRoute(
- self, 34, 1,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=1,
- rpf_id=55)],
+ self,
+ 34,
+ 1,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1, rpf_id=55)],
is_multicast=1,
- eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)
+ eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ )
route_34_eos.add_vpp_config()
@@ -1485,8 +1738,9 @@ class TestMPLS(VppTestCase):
# Drop due to interface lookup miss
#
self.vapi.cli("clear trace")
- tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(34)],
- dst_ip="232.1.1.1", n=1)
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(34)], dst_ip="232.1.1.1", n=1
+ )
self.send_and_assert_no_replies(self.pg0, tx, "RPF-ID drop none")
#
@@ -1495,29 +1749,31 @@ class TestMPLS(VppTestCase):
route_232_1_1_1.update_rpf_id(55)
self.logger.info(self.vapi.cli("sh ip mfib index 1 232.1.1.1"))
- tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(34)],
- dst_ip="232.1.1.1")
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(34)], dst_ip="232.1.1.1"
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg1)
self.verify_capture_ip4(self.pg1, rx, tx)
#
# disposed packets have an invalid IPv4 checksum
#
- tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(34)],
- dst_ip="232.1.1.1", n=65,
- chksum=1)
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(34)], dst_ip="232.1.1.1", n=65, chksum=1
+ )
self.send_and_assert_no_replies(self.pg0, tx, "Invalid Checksum")
#
# set the RPF-ID of the entry to not match the input packet's
#
route_232_1_1_1.update_rpf_id(56)
- tx = self.create_stream_labelled_ip4(self.pg0, [VppMplsLabel(34)],
- dst_ip="232.1.1.1")
+ tx = self.create_stream_labelled_ip4(
+ self.pg0, [VppMplsLabel(34)], dst_ip="232.1.1.1"
+ )
self.send_and_assert_no_replies(self.pg0, tx, "RPF-ID drop 56")
def test_mcast_ip6_tail(self):
- """ MPLS IPv6 Multicast Tail """
+ """MPLS IPv6 Multicast Tail"""
MRouteItfFlags = VppEnum.vl_api_mfib_itf_flags_t
MRouteEntryFlags = VppEnum.vl_api_mfib_entry_flags_t
@@ -1529,12 +1785,18 @@ class TestMPLS(VppTestCase):
route_ff = VppIpMRoute(
self,
"::",
- "ff01::1", 32,
+ "ff01::1",
+ 32,
MRouteEntryFlags.MFIB_API_ENTRY_FLAG_NONE,
table_id=1,
- paths=[VppMRoutePath(self.pg1.sw_if_index,
- MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ paths=[
+ VppMRoutePath(
+ self.pg1.sw_if_index,
+ MRouteItfFlags.MFIB_API_ITF_FLAG_FORWARD,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
+ ],
+ )
route_ff.add_vpp_config()
#
@@ -1546,21 +1808,22 @@ class TestMPLS(VppTestCase):
# table 1
#
route_34_eos = VppMplsRoute(
- self, 34, 1,
- [VppRoutePath("::",
- 0xffffffff,
- nh_table_id=1,
- rpf_id=55)],
+ self,
+ 34,
+ 1,
+ [VppRoutePath("::", 0xFFFFFFFF, nh_table_id=1, rpf_id=55)],
is_multicast=1,
- eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)
+ eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
route_34_eos.add_vpp_config()
#
# Drop due to interface lookup miss
#
- tx = self.create_stream_labelled_ip6(self.pg0, [VppMplsLabel(34)],
- dst_ip="ff01::1")
+ tx = self.create_stream_labelled_ip6(
+ self.pg0, [VppMplsLabel(34)], dst_ip="ff01::1"
+ )
self.send_and_assert_no_replies(self.pg0, tx, "RPF Miss")
#
@@ -1568,18 +1831,18 @@ class TestMPLS(VppTestCase):
#
route_ff.update_rpf_id(55)
- tx = self.create_stream_labelled_ip6(self.pg0, [VppMplsLabel(34)],
- dst_ip="ff01::1")
+ tx = self.create_stream_labelled_ip6(
+ self.pg0, [VppMplsLabel(34)], dst_ip="ff01::1"
+ )
rx = self.send_and_expect(self.pg0, tx, self.pg1)
self.verify_capture_ip6(self.pg1, rx, tx)
#
# disposed packets have hop-limit = 1
#
- tx = self.create_stream_labelled_ip6(self.pg0,
- [VppMplsLabel(34)],
- dst_ip="ff01::1",
- hlim=1)
+ tx = self.create_stream_labelled_ip6(
+ self.pg0, [VppMplsLabel(34)], dst_ip="ff01::1", hlim=1
+ )
rx = self.send_and_expect_some(self.pg0, tx, self.pg0)
self.verify_capture_ip6_icmp(self.pg0, rx, tx)
@@ -1587,21 +1850,27 @@ class TestMPLS(VppTestCase):
# set the RPF-ID of the entry to not match the input packet's
#
route_ff.update_rpf_id(56)
- tx = self.create_stream_labelled_ip6(self.pg0,
- [VppMplsLabel(34)],
- dst_ip="ff01::1")
+ tx = self.create_stream_labelled_ip6(
+ self.pg0, [VppMplsLabel(34)], dst_ip="ff01::1"
+ )
self.send_and_assert_no_replies(self.pg0, tx, "RPF-ID drop 56")
def test_6pe(self):
- """ MPLS 6PE """
+ """MPLS 6PE"""
#
# Add a non-recursive route with a single out label
#
- route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(45)])])
+ route_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(45)]
+ )
+ ],
+ )
route_10_0_0_1.add_vpp_config()
# bind a local label to the route
@@ -1612,55 +1881,57 @@ class TestMPLS(VppTestCase):
# a labelled v6 route that resolves through the v4
#
route_2001_3 = VppIpRoute(
- self, "2001::3", 128,
- [VppRoutePath("10.0.0.1",
- INVALID_INDEX,
- labels=[VppMplsLabel(32)])])
+ self,
+ "2001::3",
+ 128,
+ [VppRoutePath("10.0.0.1", INVALID_INDEX, labels=[VppMplsLabel(32)])],
+ )
route_2001_3.add_vpp_config()
tx = self.create_stream_ip6(self.pg0, "2001::3")
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled_ip6(self.pg0, rx, tx,
- [VppMplsLabel(45),
- VppMplsLabel(32)])
+ self.verify_capture_labelled_ip6(
+ self.pg0, rx, tx, [VppMplsLabel(45), VppMplsLabel(32)]
+ )
#
# and a v4 recursive via the v6
#
route_20_3 = VppIpRoute(
- self, "20.0.0.3", 32,
- [VppRoutePath("2001::3",
- INVALID_INDEX,
- labels=[VppMplsLabel(99)])])
+ self,
+ "20.0.0.3",
+ 32,
+ [VppRoutePath("2001::3", INVALID_INDEX, labels=[VppMplsLabel(99)])],
+ )
route_20_3.add_vpp_config()
tx = self.create_stream_ip4(self.pg0, "20.0.0.3")
rx = self.send_and_expect(self.pg0, tx, self.pg0)
- self.verify_capture_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(45),
- VppMplsLabel(32),
- VppMplsLabel(99)])
+ self.verify_capture_labelled_ip4(
+ self.pg0, rx, tx, [VppMplsLabel(45), VppMplsLabel(32), VppMplsLabel(99)]
+ )
def test_attached(self):
- """ Attach Routes with Local Label """
+ """Attach Routes with Local Label"""
#
# test that if a local label is associated with an attached/connected
# prefix, that we can reach hosts in the prefix.
#
- binding = VppMplsIpBind(self, 44,
- self.pg0._local_ip4_subnet,
- self.pg0.local_ip4_prefix_len)
+ binding = VppMplsIpBind(
+ self, 44, self.pg0._local_ip4_subnet, self.pg0.local_ip4_prefix_len
+ )
binding.add_vpp_config()
- tx = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- MPLS(label=44, ttl=64) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ tx = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / MPLS(label=44, ttl=64)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, [tx], self.pg0)
for rx in rxs:
# if there's an ARP then the label is linked to the glean
@@ -1672,7 +1943,7 @@ class TestMPLS(VppTestCase):
class TestMPLSDisabled(VppTestCase):
- """ MPLS disabled """
+ """MPLS disabled"""
@classmethod
def setUpClass(cls):
@@ -1709,26 +1980,29 @@ class TestMPLSDisabled(VppTestCase):
super(TestMPLSDisabled, self).tearDown()
def test_mpls_disabled(self):
- """ MPLS Disabled """
+ """MPLS Disabled"""
self.logger.info(self.vapi.cli("show mpls interface"))
self.logger.info(self.vapi.cli("show mpls interface pg1"))
self.logger.info(self.vapi.cli("show mpls interface pg0"))
- tx = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- MPLS(label=32, ttl=64) /
- IPv6(src="2001::1", dst=self.pg0.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ tx = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / MPLS(label=32, ttl=64)
+ / IPv6(src="2001::1", dst=self.pg0.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# A simple MPLS xconnect - eos label in label out
#
- route_32_eos = VppMplsRoute(self, 32, 1,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[33])])
+ route_32_eos = VppMplsRoute(
+ self,
+ 32,
+ 1,
+ [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[33])],
+ )
route_32_eos.add_vpp_config()
#
@@ -1766,7 +2040,7 @@ class TestMPLSDisabled(VppTestCase):
class TestMPLSPIC(VppTestCase):
- """ MPLS Prefix-Independent Convergence (PIC) edge convergence """
+ """MPLS Prefix-Independent Convergence (PIC) edge convergence"""
@classmethod
def setUpClass(cls):
@@ -1829,7 +2103,7 @@ class TestMPLSPIC(VppTestCase):
super(TestMPLSPIC, self).tearDown()
def test_mpls_ibgp_pic(self):
- """ MPLS iBGP Prefix-Independent Convergence (PIC) edge convergence
+ """MPLS iBGP Prefix-Independent Convergence (PIC) edge convergence
1) setup many iBGP VPN routes via a pair of iBGP peers.
2) Check EMCP forwarding to these peers
@@ -1840,16 +2114,20 @@ class TestMPLSPIC(VppTestCase):
#
# IGP+LDP core routes
#
- core_10_0_0_45 = VppIpRoute(self, "10.0.0.45", 32,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[45])])
+ core_10_0_0_45 = VppIpRoute(
+ self,
+ "10.0.0.45",
+ 32,
+ [VppRoutePath(self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[45])],
+ )
core_10_0_0_45.add_vpp_config()
- core_10_0_0_46 = VppIpRoute(self, "10.0.0.46", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index,
- labels=[46])])
+ core_10_0_0_46 = VppIpRoute(
+ self,
+ "10.0.0.46",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index, labels=[46])],
+ )
core_10_0_0_46.add_vpp_config()
#
@@ -1860,26 +2138,36 @@ class TestMPLSPIC(VppTestCase):
pkts = []
for ii in range(NUM_PKTS):
dst = "192.168.1.%d" % ii
- vpn_routes.append(VppIpRoute(
- self, dst, 32,
- [VppRoutePath(
- "10.0.0.45",
- 0xffffffff,
- labels=[145],
- flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_HOST),
- VppRoutePath(
- "10.0.0.46",
- 0xffffffff,
- labels=[146],
- flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_HOST)],
- table_id=1))
+ vpn_routes.append(
+ VppIpRoute(
+ self,
+ dst,
+ 32,
+ [
+ VppRoutePath(
+ "10.0.0.45",
+ 0xFFFFFFFF,
+ labels=[145],
+ flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_HOST,
+ ),
+ VppRoutePath(
+ "10.0.0.46",
+ 0xFFFFFFFF,
+ labels=[146],
+ flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_HOST,
+ ),
+ ],
+ table_id=1,
+ )
+ )
vpn_routes[ii].add_vpp_config()
- pkts.append(Ether(dst=self.pg2.local_mac,
- src=self.pg2.remote_mac) /
- IP(src=self.pg2.remote_ip4, dst=dst) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkts.append(
+ Ether(dst=self.pg2.local_mac, src=self.pg2.remote_mac)
+ / IP(src=self.pg2.remote_ip4, dst=dst)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# Send the packet stream (one pkt to each VPN route)
@@ -1896,9 +2184,12 @@ class TestMPLSPIC(VppTestCase):
# with the split ratio, just as long as neither is 0
self.assertNotEqual(0, len(rx0))
self.assertNotEqual(0, len(rx1))
- self.assertEqual(len(pkts), len(rx0) + len(rx1),
- "Expected all (%s) packets across both ECMP paths. "
- "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0) + len(rx1),
+ "Expected all (%s) packets across both ECMP paths. "
+ "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)),
+ )
#
# use a test CLI command to stop the FIB walk process, this
@@ -1921,9 +2212,12 @@ class TestMPLSPIC(VppTestCase):
self.pg_start()
rx0 = self.pg0.get_capture(NUM_PKTS)
- self.assertEqual(len(pkts), len(rx0),
- "Expected all (%s) packets across single path. "
- "rx0: %s." % (len(pkts), len(rx0)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0),
+ "Expected all (%s) packets across single path. "
+ "rx0: %s." % (len(pkts), len(rx0)),
+ )
#
# enable the FIB walk process to converge the FIB
@@ -1938,9 +2232,12 @@ class TestMPLSPIC(VppTestCase):
self.pg_start()
rx0 = self.pg0.get_capture(NUM_PKTS)
- self.assertEqual(len(pkts), len(rx0),
- "Expected all (%s) packets across single path. "
- "rx0: %s." % (len(pkts), len(rx0)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0),
+ "Expected all (%s) packets across single path. "
+ "rx0: %s." % (len(pkts), len(rx0)),
+ )
#
# Add the IGP route back and we return to load-balancing
@@ -1955,12 +2252,15 @@ class TestMPLSPIC(VppTestCase):
rx1 = self.pg1._get_capture(NUM_PKTS)
self.assertNotEqual(0, len(rx0))
self.assertNotEqual(0, len(rx1))
- self.assertEqual(len(pkts), len(rx0) + len(rx1),
- "Expected all (%s) packets across both ECMP paths. "
- "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0) + len(rx1),
+ "Expected all (%s) packets across both ECMP paths. "
+ "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)),
+ )
def test_mpls_ebgp_pic(self):
- """ MPLS eBGP Prefix-Independent Convergence (PIC) edge convergence
+ """MPLS eBGP Prefix-Independent Convergence (PIC) edge convergence
1) setup many eBGP VPN routes via a pair of eBGP peers.
2) Check EMCP forwarding to these peers
@@ -1977,31 +2277,42 @@ class TestMPLSPIC(VppTestCase):
for ii in range(NUM_PKTS):
dst = "192.168.1.%d" % ii
local_label = 1600 + ii
- vpn_routes.append(VppIpRoute(
- self, dst, 32,
- [VppRoutePath(
- self.pg2.remote_ip4,
- 0xffffffff,
- nh_table_id=1,
- flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED),
- VppRoutePath(
- self.pg3.remote_ip4,
- 0xffffffff,
- nh_table_id=1,
- flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED)],
- table_id=1))
+ vpn_routes.append(
+ VppIpRoute(
+ self,
+ dst,
+ 32,
+ [
+ VppRoutePath(
+ self.pg2.remote_ip4,
+ 0xFFFFFFFF,
+ nh_table_id=1,
+ flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED,
+ ),
+ VppRoutePath(
+ self.pg3.remote_ip4,
+ 0xFFFFFFFF,
+ nh_table_id=1,
+ flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED,
+ ),
+ ],
+ table_id=1,
+ )
+ )
vpn_routes[ii].add_vpp_config()
- vpn_bindings.append(VppMplsIpBind(self, local_label, dst, 32,
- ip_table_id=1))
+ vpn_bindings.append(
+ VppMplsIpBind(self, local_label, dst, 32, ip_table_id=1)
+ )
vpn_bindings[ii].add_vpp_config()
- pkts.append(Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- MPLS(label=local_label, ttl=64) /
- IP(src=self.pg0.remote_ip4, dst=dst) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkts.append(
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / MPLS(label=local_label, ttl=64)
+ / IP(src=self.pg0.remote_ip4, dst=dst)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# Send the packet stream (one pkt to each VPN route)
@@ -2018,9 +2329,12 @@ class TestMPLSPIC(VppTestCase):
# with the split ratio, just as long as neither is 0
self.assertNotEqual(0, len(rx0))
self.assertNotEqual(0, len(rx1))
- self.assertEqual(len(pkts), len(rx0) + len(rx1),
- "Expected all (%s) packets across both ECMP paths. "
- "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0) + len(rx1),
+ "Expected all (%s) packets across both ECMP paths. "
+ "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)),
+ )
#
# use a test CLI command to stop the FIB walk process, this
@@ -2042,9 +2356,12 @@ class TestMPLSPIC(VppTestCase):
self.pg_start()
rx0 = self.pg3.get_capture(NUM_PKTS)
- self.assertEqual(len(pkts), len(rx0),
- "Expected all (%s) packets across single path. "
- "rx0: %s." % (len(pkts), len(rx0)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0),
+ "Expected all (%s) packets across single path. "
+ "rx0: %s." % (len(pkts), len(rx0)),
+ )
#
# enable the FIB walk process to converge the FIB
@@ -2059,9 +2376,12 @@ class TestMPLSPIC(VppTestCase):
self.pg_start()
rx0 = self.pg3.get_capture(NUM_PKTS)
- self.assertEqual(len(pkts), len(rx0),
- "Expected all (%s) packets across single path. "
- "rx0: %s." % (len(pkts), len(rx0)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0),
+ "Expected all (%s) packets across single path. "
+ "rx0: %s." % (len(pkts), len(rx0)),
+ )
#
# put the connected routes back
@@ -2077,12 +2397,15 @@ class TestMPLSPIC(VppTestCase):
rx1 = self.pg3._get_capture(NUM_PKTS)
self.assertNotEqual(0, len(rx0))
self.assertNotEqual(0, len(rx1))
- self.assertEqual(len(pkts), len(rx0) + len(rx1),
- "Expected all (%s) packets across both ECMP paths. "
- "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0) + len(rx1),
+ "Expected all (%s) packets across both ECMP paths. "
+ "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)),
+ )
def test_mpls_v6_ebgp_pic(self):
- """ MPLSv6 eBGP Prefix-Independent Convergence (PIC) edge convergence
+ """MPLSv6 eBGP Prefix-Independent Convergence (PIC) edge convergence
1) setup many eBGP VPNv6 routes via a pair of eBGP peers
2) Check EMCP forwarding to these peers
@@ -2099,31 +2422,42 @@ class TestMPLSPIC(VppTestCase):
for ii in range(NUM_PKTS):
dst = "3000::%d" % ii
local_label = 1600 + ii
- vpn_routes.append(VppIpRoute(
- self, dst, 128,
- [VppRoutePath(
- self.pg2.remote_ip6,
- 0xffffffff,
- nh_table_id=1,
- flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED),
- VppRoutePath(
- self.pg3.remote_ip6,
- 0xffffffff,
- nh_table_id=1,
- flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED)],
- table_id=1))
+ vpn_routes.append(
+ VppIpRoute(
+ self,
+ dst,
+ 128,
+ [
+ VppRoutePath(
+ self.pg2.remote_ip6,
+ 0xFFFFFFFF,
+ nh_table_id=1,
+ flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED,
+ ),
+ VppRoutePath(
+ self.pg3.remote_ip6,
+ 0xFFFFFFFF,
+ nh_table_id=1,
+ flags=FibPathFlags.FIB_PATH_FLAG_RESOLVE_VIA_ATTACHED,
+ ),
+ ],
+ table_id=1,
+ )
+ )
vpn_routes[ii].add_vpp_config()
- vpn_bindings.append(VppMplsIpBind(self, local_label, dst, 128,
- ip_table_id=1))
+ vpn_bindings.append(
+ VppMplsIpBind(self, local_label, dst, 128, ip_table_id=1)
+ )
vpn_bindings[ii].add_vpp_config()
- pkts.append(Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- MPLS(label=local_label, ttl=64) /
- IPv6(src=self.pg0.remote_ip6, dst=dst) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pkts.append(
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / MPLS(label=local_label, ttl=64)
+ / IPv6(src=self.pg0.remote_ip6, dst=dst)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.logger.info(self.vapi.cli("sh ip6 fib %s" % dst))
self.pg0.add_stream(pkts)
@@ -2134,9 +2468,12 @@ class TestMPLSPIC(VppTestCase):
rx1 = self.pg3._get_capture(NUM_PKTS)
self.assertNotEqual(0, len(rx0))
self.assertNotEqual(0, len(rx1))
- self.assertEqual(len(pkts), len(rx0) + len(rx1),
- "Expected all (%s) packets across both ECMP paths. "
- "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0) + len(rx1),
+ "Expected all (%s) packets across both ECMP paths. "
+ "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)),
+ )
#
# use a test CLI command to stop the FIB walk process, this
@@ -2160,9 +2497,12 @@ class TestMPLSPIC(VppTestCase):
self.pg_start()
rx0 = self.pg3.get_capture(NUM_PKTS)
- self.assertEqual(len(pkts), len(rx0),
- "Expected all (%s) packets across single path. "
- "rx0: %s." % (len(pkts), len(rx0)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0),
+ "Expected all (%s) packets across single path. "
+ "rx0: %s." % (len(pkts), len(rx0)),
+ )
#
# enable the FIB walk process to converge the FIB
@@ -2173,9 +2513,12 @@ class TestMPLSPIC(VppTestCase):
self.pg_start()
rx0 = self.pg3.get_capture(NUM_PKTS)
- self.assertEqual(len(pkts), len(rx0),
- "Expected all (%s) packets across single path. "
- "rx0: %s." % (len(pkts), len(rx0)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0),
+ "Expected all (%s) packets across single path. "
+ "rx0: %s." % (len(pkts), len(rx0)),
+ )
#
# put the connected routes back
@@ -2193,13 +2536,16 @@ class TestMPLSPIC(VppTestCase):
rx1 = self.pg3._get_capture(NUM_PKTS)
self.assertNotEqual(0, len(rx0))
self.assertNotEqual(0, len(rx1))
- self.assertEqual(len(pkts), len(rx0) + len(rx1),
- "Expected all (%s) packets across both ECMP paths. "
- "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)))
+ self.assertEqual(
+ len(pkts),
+ len(rx0) + len(rx1),
+ "Expected all (%s) packets across both ECMP paths. "
+ "rx0: %s rx1: %s." % (len(pkts), len(rx0), len(rx1)),
+ )
class TestMPLSL2(VppTestCase):
- """ MPLS-L2 """
+ """MPLS-L2"""
@classmethod
def setUpClass(cls):
@@ -2274,7 +2620,7 @@ class TestMPLSL2(VppTestCase):
self.assertEqual(arp.pdst, dip)
def test_vpws(self):
- """ Virtual Private Wire Service """
+ """Virtual Private Wire Service"""
#
# Create an MPLS tunnel that pushes 1 label
@@ -2283,10 +2629,15 @@ class TestMPLSL2(VppTestCase):
#
mpls_tun_1 = VppMPLSTunnelInterface(
self,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(42, MplsLspMode.UNIFORM)])],
- is_l2=1)
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4,
+ self.pg0.sw_if_index,
+ labels=[VppMplsLabel(42, MplsLspMode.UNIFORM)],
+ )
+ ],
+ is_l2=1,
+ )
mpls_tun_1.add_vpp_config()
mpls_tun_1.admin_up()
@@ -2294,35 +2645,42 @@ class TestMPLSL2(VppTestCase):
# Create a label entry to for 55 that does L2 input to the tunnel
#
route_55_eos = VppMplsRoute(
- self, 55, 1,
- [VppRoutePath("0.0.0.0",
- mpls_tun_1.sw_if_index,
- type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX,
- proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET)],
- eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET)
+ self,
+ 55,
+ 1,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ mpls_tun_1.sw_if_index,
+ type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET,
+ )
+ ],
+ eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET,
+ )
route_55_eos.add_vpp_config()
#
# Cross-connect the tunnel with one of the customers L2 interfaces
#
- self.vapi.sw_interface_set_l2_xconnect(self.pg1.sw_if_index,
- mpls_tun_1.sw_if_index,
- enable=1)
- self.vapi.sw_interface_set_l2_xconnect(mpls_tun_1.sw_if_index,
- self.pg1.sw_if_index,
- enable=1)
+ self.vapi.sw_interface_set_l2_xconnect(
+ self.pg1.sw_if_index, mpls_tun_1.sw_if_index, enable=1
+ )
+ self.vapi.sw_interface_set_l2_xconnect(
+ mpls_tun_1.sw_if_index, self.pg1.sw_if_index, enable=1
+ )
#
# inject a packet from the core
#
- pcore = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- MPLS(label=55, ttl=64) /
- Ether(dst="00:00:de:ad:ba:be",
- src="00:00:de:ad:be:ef") /
- IP(src="10.10.10.10", dst="11.11.11.11") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ pcore = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / MPLS(label=55, ttl=64)
+ / Ether(dst="00:00:de:ad:ba:be", src="00:00:de:ad:be:ef")
+ / IP(src="10.10.10.10", dst="11.11.11.11")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
tx0 = pcore * NUM_PKTS
rx0 = self.send_and_expect(self.pg0, tx0, self.pg1)
@@ -2339,10 +2697,9 @@ class TestMPLSL2(VppTestCase):
tx1 = pcore[MPLS].payload
rx1 = self.send_and_expect(self.pg1, [tx1], self.pg0)
- self.verify_arp_req(rx1[0],
- self.pg0.local_mac,
- self.pg0.local_ip4,
- self.pg0.remote_ip4)
+ self.verify_arp_req(
+ rx1[0], self.pg0.local_mac, self.pg0.local_ip4, self.pg0.remote_ip4
+ )
#
# resolve the ARP entries and send again
@@ -2354,7 +2711,7 @@ class TestMPLSL2(VppTestCase):
self.verify_capture_tunneled_ethernet(rx1, tx1, [VppMplsLabel(42)])
def test_vpls(self):
- """ Virtual Private LAN Service """
+ """Virtual Private LAN Service"""
# we skipped this in the setup
self.pg0.resolve_arp()
@@ -2364,19 +2721,25 @@ class TestMPLSL2(VppTestCase):
#
mpls_tun1 = VppMPLSTunnelInterface(
self,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(42)])],
- is_l2=1)
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(42)]
+ )
+ ],
+ is_l2=1,
+ )
mpls_tun1.add_vpp_config()
mpls_tun1.admin_up()
mpls_tun2 = VppMPLSTunnelInterface(
self,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(43)])],
- is_l2=1)
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(43)]
+ )
+ ],
+ is_l2=1,
+ )
mpls_tun2.add_vpp_config()
mpls_tun2.admin_up()
@@ -2385,21 +2748,35 @@ class TestMPLSL2(VppTestCase):
# the latter includes a Psuedo Wire Control Word
#
route_55_eos = VppMplsRoute(
- self, 55, 1,
- [VppRoutePath("0.0.0.0",
- mpls_tun1.sw_if_index,
- type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX,
- proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET)],
- eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET)
+ self,
+ 55,
+ 1,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ mpls_tun1.sw_if_index,
+ type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET,
+ )
+ ],
+ eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET,
+ )
route_56_eos = VppMplsRoute(
- self, 56, 1,
- [VppRoutePath("0.0.0.0",
- mpls_tun2.sw_if_index,
- type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX,
- flags=FibPathFlags.FIB_PATH_FLAG_POP_PW_CW,
- proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET)],
- eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET)
+ self,
+ 56,
+ 1,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ mpls_tun2.sw_if_index,
+ type=FibPathType.FIB_PATH_TYPE_INTERFACE_RX,
+ flags=FibPathFlags.FIB_PATH_FLAG_POP_PW_CW,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET,
+ )
+ ],
+ eos_proto=FibPathProto.FIB_PATH_NH_PROTO_ETHERNET,
+ )
# move me
route_56_eos.add_vpp_config()
@@ -2411,43 +2788,48 @@ class TestMPLSL2(VppTestCase):
# add to tunnel to the customers bridge-domain
#
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=mpls_tun1.sw_if_index, bd_id=1)
+ rx_sw_if_index=mpls_tun1.sw_if_index, bd_id=1
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=mpls_tun2.sw_if_index, bd_id=1)
+ rx_sw_if_index=mpls_tun2.sw_if_index, bd_id=1
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg1.sw_if_index, bd_id=1)
+ rx_sw_if_index=self.pg1.sw_if_index, bd_id=1
+ )
#
# Packet from host on the customer interface to each host
# reachable over the core, and vice-versa
#
- p_cust1 = (Ether(dst="00:00:de:ad:ba:b1",
- src="00:00:de:ad:be:ef") /
- IP(src="10.10.10.10", dst="11.11.11.11") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- p_cust2 = (Ether(dst="00:00:de:ad:ba:b2",
- src="00:00:de:ad:be:ef") /
- IP(src="10.10.10.10", dst="11.11.11.12") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- p_core1 = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- MPLS(label=55, ttl=64) /
- Ether(src="00:00:de:ad:ba:b1",
- dst="00:00:de:ad:be:ef") /
- IP(dst="10.10.10.10", src="11.11.11.11") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- p_core2 = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- MPLS(label=56, ttl=64) /
- Raw(b'\x01' * 4) / # PW CW
- Ether(src="00:00:de:ad:ba:b2",
- dst="00:00:de:ad:be:ef") /
- IP(dst="10.10.10.10", src="11.11.11.12") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_cust1 = (
+ Ether(dst="00:00:de:ad:ba:b1", src="00:00:de:ad:be:ef")
+ / IP(src="10.10.10.10", dst="11.11.11.11")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ p_cust2 = (
+ Ether(dst="00:00:de:ad:ba:b2", src="00:00:de:ad:be:ef")
+ / IP(src="10.10.10.10", dst="11.11.11.12")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ p_core1 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / MPLS(label=55, ttl=64)
+ / Ether(src="00:00:de:ad:ba:b1", dst="00:00:de:ad:be:ef")
+ / IP(dst="10.10.10.10", src="11.11.11.11")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ p_core2 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / MPLS(label=56, ttl=64)
+ / Raw(b"\x01" * 4)
+ / Ether(src="00:00:de:ad:ba:b2", dst="00:00:de:ad:be:ef") # PW CW
+ / IP(dst="10.10.10.10", src="11.11.11.12")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
#
# The BD is learning, so send in one of each packet to learn
@@ -2470,12 +2852,14 @@ class TestMPLSL2(VppTestCase):
# now a stream in each direction from each host
#
rx = self.send_and_expect(self.pg1, p_cust1 * NUM_PKTS, self.pg0)
- self.verify_capture_tunneled_ethernet(rx, p_cust1 * NUM_PKTS,
- [VppMplsLabel(42)])
+ self.verify_capture_tunneled_ethernet(
+ rx, p_cust1 * NUM_PKTS, [VppMplsLabel(42)]
+ )
rx = self.send_and_expect(self.pg1, p_cust2 * NUM_PKTS, self.pg0)
- self.verify_capture_tunneled_ethernet(rx, p_cust2 * NUM_PKTS,
- [VppMplsLabel(43)])
+ self.verify_capture_tunneled_ethernet(
+ rx, p_cust2 * NUM_PKTS, [VppMplsLabel(43)]
+ )
rx = self.send_and_expect(self.pg0, p_core1 * NUM_PKTS, self.pg1)
rx = self.send_and_expect(self.pg0, p_core2 * NUM_PKTS, self.pg1)
@@ -2484,12 +2868,15 @@ class TestMPLSL2(VppTestCase):
# remove interfaces from customers bridge-domain
#
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=mpls_tun1.sw_if_index, bd_id=1, enable=0)
+ rx_sw_if_index=mpls_tun1.sw_if_index, bd_id=1, enable=0
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=mpls_tun2.sw_if_index, bd_id=1, enable=0)
+ rx_sw_if_index=mpls_tun2.sw_if_index, bd_id=1, enable=0
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg1.sw_if_index, bd_id=1, enable=0)
+ rx_sw_if_index=self.pg1.sw_if_index, bd_id=1, enable=0
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_mss_clamp.py b/test/test_mss_clamp.py
index 23495b6050b..663ecd37742 100644
--- a/test/test_mss_clamp.py
+++ b/test/test_mss_clamp.py
@@ -11,7 +11,7 @@ from scapy.packet import Raw
class TestMSSClamp(VppTestCase):
- """ TCP MSS Clamping Test Case """
+ """TCP MSS Clamping Test Case"""
def setUp(self):
super(TestMSSClamp, self).setUp()
@@ -40,31 +40,34 @@ class TestMSSClamp(VppTestCase):
tcp_csum = tcp.chksum
del tcp.chksum
ip_csum = 0
- if (rx.haslayer(IP)):
+ if rx.haslayer(IP):
ip_csum = rx[IP].chksum
del rx[IP].chksum
opt = tcp.options
- self.assertEqual(opt[0][0], 'MSS')
+ self.assertEqual(opt[0][0], "MSS")
self.assertEqual(opt[0][1], expected_mss)
# recalculate checksums
rx = rx.__class__(bytes(rx))
tcp = rx[TCP]
self.assertEqual(tcp_csum, tcp.chksum)
- if (rx.haslayer(IP)):
+ if rx.haslayer(IP):
self.assertEqual(ip_csum, rx[IP].chksum)
def send_and_verify_ip4(self, src_pg, dst_pg, mss, expected_mss):
# IPv4 TCP packet with the requested MSS option.
# from a host on src_pg to a host on dst_pg.
- p = (Ether(dst=src_pg.local_mac,
- src=src_pg.remote_mac) /
- IP(src=src_pg.remote_ip4,
- dst=dst_pg.remote_ip4) /
- TCP(sport=1234, dport=1234,
- flags="S",
- options=[('MSS', (mss)), ('EOL', None)]) /
- Raw('\xa5' * 100))
+ p = (
+ Ether(dst=src_pg.local_mac, src=src_pg.remote_mac)
+ / IP(src=src_pg.remote_ip4, dst=dst_pg.remote_ip4)
+ / TCP(
+ sport=1234,
+ dport=1234,
+ flags="S",
+ options=[("MSS", (mss)), ("EOL", None)],
+ )
+ / Raw("\xa5" * 100)
+ )
rxs = self.send_and_expect(src_pg, p * 65, dst_pg)
@@ -76,14 +79,17 @@ class TestMSSClamp(VppTestCase):
# IPv6 TCP packet with the requested MSS option.
# from a host on src_pg to a host on dst_pg.
#
- p = (Ether(dst=src_pg.local_mac,
- src=src_pg.remote_mac) /
- IPv6(src=src_pg.remote_ip6,
- dst=dst_pg.remote_ip6) /
- TCP(sport=1234, dport=1234,
- flags="S",
- options=[('MSS', (mss)), ('EOL', None)]) /
- Raw('\xa5' * 100))
+ p = (
+ Ether(dst=src_pg.local_mac, src=src_pg.remote_mac)
+ / IPv6(src=src_pg.remote_ip6, dst=dst_pg.remote_ip6)
+ / TCP(
+ sport=1234,
+ dport=1234,
+ flags="S",
+ options=[("MSS", (mss)), ("EOL", None)],
+ )
+ / Raw("\xa5" * 100)
+ )
rxs = self.send_and_expect(src_pg, p * 65, dst_pg)
@@ -91,12 +97,16 @@ class TestMSSClamp(VppTestCase):
self.verify_pkt(rx, expected_mss)
def test_tcp_mss_clamping_ip4_tx(self):
- """ IP4 TCP MSS Clamping TX """
+ """IP4 TCP MSS Clamping TX"""
# enable the TCP MSS clamping feature to lower the MSS to 1424.
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=1424, ipv6_mss=0,
- ipv4_direction=3, ipv6_direction=0)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=1424,
+ ipv6_mss=0,
+ ipv4_direction=3,
+ ipv6_direction=0,
+ )
# Verify that the feature is enabled.
rv, reply = self.vapi.mss_clamp_get(sw_if_index=self.pg1.sw_if_index)
@@ -107,8 +117,7 @@ class TestMSSClamp(VppTestCase):
self.send_and_verify_ip4(self.pg0, self.pg1, 1460, 1424)
# check the stats
- stats = self.statistics.get_counter(
- '/err/tcp-mss-clamping-ip4-out/clamped')
+ stats = self.statistics.get_counter("/err/tcp-mss-clamping-ip4-out/clamped")
self.assertEqual(sum(stats), 65)
# Send syn packets with small enough MSS values and verify they are
@@ -117,36 +126,52 @@ class TestMSSClamp(VppTestCase):
# enable the the feature only in TX direction
# and change the max MSS value
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=1420, ipv6_mss=0,
- ipv4_direction=2, ipv6_direction=0)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=1420,
+ ipv6_mss=0,
+ ipv4_direction=2,
+ ipv6_direction=0,
+ )
# Send syn packets and verify that the MSS value is lowered.
self.send_and_verify_ip4(self.pg0, self.pg1, 1460, 1420)
# enable the the feature only in RX direction
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=1424, ipv6_mss=0,
- ipv4_direction=1, ipv6_direction=0)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=1424,
+ ipv6_mss=0,
+ ipv4_direction=1,
+ ipv6_direction=0,
+ )
# Send the packets again and ensure they are unchanged.
self.send_and_verify_ip4(self.pg0, self.pg1, 1460, 1460)
# disable the feature
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=0, ipv6_mss=0,
- ipv4_direction=0, ipv6_direction=0)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=0,
+ ipv6_mss=0,
+ ipv4_direction=0,
+ ipv6_direction=0,
+ )
# Send the packets again and ensure they are unchanged.
self.send_and_verify_ip4(self.pg0, self.pg1, 1460, 1460)
def test_tcp_mss_clamping_ip4_rx(self):
- """ IP4 TCP MSS Clamping RX """
+ """IP4 TCP MSS Clamping RX"""
# enable the TCP MSS clamping feature to lower the MSS to 1424.
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=1424, ipv6_mss=0,
- ipv4_direction=3, ipv6_direction=0)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=1424,
+ ipv6_mss=0,
+ ipv4_direction=3,
+ ipv6_direction=0,
+ )
# Verify that the feature is enabled.
rv, reply = self.vapi.mss_clamp_get(sw_if_index=self.pg1.sw_if_index)
@@ -157,8 +182,7 @@ class TestMSSClamp(VppTestCase):
self.send_and_verify_ip4(self.pg1, self.pg0, 1460, 1424)
# check the stats
- stats = self.statistics.get_counter(
- '/err/tcp-mss-clamping-ip4-in/clamped')
+ stats = self.statistics.get_counter("/err/tcp-mss-clamping-ip4-in/clamped")
self.assertEqual(sum(stats), 65)
# Send syn packets with small enough MSS values and verify they are
@@ -167,36 +191,52 @@ class TestMSSClamp(VppTestCase):
# enable the the feature only in RX direction
# and change the max MSS value
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=1420, ipv6_mss=0,
- ipv4_direction=1, ipv6_direction=0)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=1420,
+ ipv6_mss=0,
+ ipv4_direction=1,
+ ipv6_direction=0,
+ )
# Send syn packets and verify that the MSS value is lowered.
self.send_and_verify_ip4(self.pg1, self.pg0, 1460, 1420)
# enable the the feature only in TX direction
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=1424, ipv6_mss=0,
- ipv4_direction=2, ipv6_direction=0)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=1424,
+ ipv6_mss=0,
+ ipv4_direction=2,
+ ipv6_direction=0,
+ )
# Send the packets again and ensure they are unchanged.
self.send_and_verify_ip4(self.pg1, self.pg0, 1460, 1460)
# disable the feature
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=0, ipv6_mss=0,
- ipv4_direction=0, ipv6_direction=0)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=0,
+ ipv6_mss=0,
+ ipv4_direction=0,
+ ipv6_direction=0,
+ )
# Send the packets again and ensure they are unchanged.
self.send_and_verify_ip4(self.pg1, self.pg0, 1460, 1460)
def test_tcp_mss_clamping_ip6_tx(self):
- """ IP6 TCP MSS Clamping TX """
+ """IP6 TCP MSS Clamping TX"""
# enable the TCP MSS clamping feature to lower the MSS to 1424.
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=0, ipv6_mss=1424,
- ipv4_direction=0, ipv6_direction=3)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=0,
+ ipv6_mss=1424,
+ ipv4_direction=0,
+ ipv6_direction=3,
+ )
# Verify that the feature is enabled.
rv, reply = self.vapi.mss_clamp_get(sw_if_index=self.pg1.sw_if_index)
@@ -207,8 +247,7 @@ class TestMSSClamp(VppTestCase):
self.send_and_verify_ip6(self.pg0, self.pg1, 1460, 1424)
# check the stats
- stats = self.statistics.get_counter(
- '/err/tcp-mss-clamping-ip6-out/clamped')
+ stats = self.statistics.get_counter("/err/tcp-mss-clamping-ip6-out/clamped")
self.assertEqual(sum(stats), 65)
# Send syn packets with small enough MSS values and verify they are
@@ -217,36 +256,52 @@ class TestMSSClamp(VppTestCase):
# enable the the feature only in TX direction
# and change the max MSS value
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=0, ipv6_mss=1420,
- ipv4_direction=0, ipv6_direction=2)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=0,
+ ipv6_mss=1420,
+ ipv4_direction=0,
+ ipv6_direction=2,
+ )
# Send syn packets and verify that the MSS value is lowered.
self.send_and_verify_ip6(self.pg0, self.pg1, 1460, 1420)
# enable the the feature only in RX direction
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=0, ipv6_mss=1424,
- ipv4_direction=0, ipv6_direction=1)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=0,
+ ipv6_mss=1424,
+ ipv4_direction=0,
+ ipv6_direction=1,
+ )
# Send the packets again and ensure they are unchanged.
self.send_and_verify_ip6(self.pg0, self.pg1, 1460, 1460)
# disable the feature
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=0, ipv6_mss=0,
- ipv4_direction=0, ipv6_direction=0)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=0,
+ ipv6_mss=0,
+ ipv4_direction=0,
+ ipv6_direction=0,
+ )
# Send the packets again and ensure they are unchanged.
self.send_and_verify_ip6(self.pg0, self.pg1, 1460, 1460)
def test_tcp_mss_clamping_ip6_rx(self):
- """ IP6 TCP MSS Clamping RX """
+ """IP6 TCP MSS Clamping RX"""
# enable the TCP MSS clamping feature to lower the MSS to 1424.
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=0, ipv6_mss=1424,
- ipv4_direction=0, ipv6_direction=3)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=0,
+ ipv6_mss=1424,
+ ipv4_direction=0,
+ ipv6_direction=3,
+ )
# Verify that the feature is enabled.
rv, reply = self.vapi.mss_clamp_get(sw_if_index=self.pg1.sw_if_index)
@@ -257,8 +312,7 @@ class TestMSSClamp(VppTestCase):
self.send_and_verify_ip6(self.pg1, self.pg0, 1460, 1424)
# check the stats
- stats = self.statistics.get_counter(
- '/err/tcp-mss-clamping-ip6-in/clamped')
+ stats = self.statistics.get_counter("/err/tcp-mss-clamping-ip6-in/clamped")
self.assertEqual(sum(stats), 65)
# Send syn packets with small enough MSS values and verify they are
@@ -267,29 +321,41 @@ class TestMSSClamp(VppTestCase):
# enable the the feature only in RX direction
# and change the max MSS value
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=0, ipv6_mss=1420,
- ipv4_direction=0, ipv6_direction=1)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=0,
+ ipv6_mss=1420,
+ ipv4_direction=0,
+ ipv6_direction=1,
+ )
# Send syn packets and verify that the MSS value is lowered.
self.send_and_verify_ip6(self.pg1, self.pg0, 1460, 1420)
# enable the the feature only in TX direction
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=0, ipv6_mss=1424,
- ipv4_direction=0, ipv6_direction=2)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=0,
+ ipv6_mss=1424,
+ ipv4_direction=0,
+ ipv6_direction=2,
+ )
# Send the packets again and ensure they are unchanged.
self.send_and_verify_ip6(self.pg1, self.pg0, 1460, 1460)
# disable the feature
- self.vapi.mss_clamp_enable_disable(self.pg1.sw_if_index,
- ipv4_mss=0, ipv6_mss=0,
- ipv4_direction=0, ipv6_direction=0)
+ self.vapi.mss_clamp_enable_disable(
+ self.pg1.sw_if_index,
+ ipv4_mss=0,
+ ipv6_mss=0,
+ ipv4_direction=0,
+ ipv6_direction=0,
+ )
# Send the packets again and ensure they are unchanged.
self.send_and_verify_ip6(self.pg1, self.pg0, 1460, 1460)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_mtu.py b/test/test_mtu.py
index 27594e55727..922d83dc5ef 100644
--- a/test/test_mtu.py
+++ b/test/test_mtu.py
@@ -24,7 +24,8 @@ from util import reassemble4
class TestMTU(VppTestCase):
- """ MTU Test Case """
+ """MTU Test Case"""
+
maxDiff = None
@classmethod
@@ -62,7 +63,7 @@ class TestMTU(VppTestCase):
self.assertEqual(rx, expected)
def payload(self, len):
- return 'x' * len
+ return "x" * len
def get_mtu(self, sw_if_index):
rv = self.vapi.sw_interface_dump(sw_if_index=sw_if_index)
@@ -72,21 +73,19 @@ class TestMTU(VppTestCase):
return 0
def test_ip4_mtu(self):
- """ IP4 MTU test """
+ """IP4 MTU test"""
p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
- p_ip4 = IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4,
- flags='DF')
+ p_ip4 = IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, flags="DF")
current_mtu = self.get_mtu(self.pg1.sw_if_index)
- p_payload = UDP(sport=1234, dport=1234) / self.payload(
- current_mtu - 20 - 8)
+ p_payload = UDP(sport=1234, dport=1234) / self.payload(current_mtu - 20 - 8)
p4 = p_ether / p_ip4 / p_payload
p4_reply = p_ip4 / p_payload
p4_reply.ttl -= 1
- rx = self.send_and_expect(self.pg0, p4*11, self.pg1)
+ rx = self.send_and_expect(self.pg0, p4 * 11, self.pg1)
for p in rx:
self.validate(p[1], p4_reply)
@@ -95,16 +94,22 @@ class TestMTU(VppTestCase):
self.assertEqual(576, self.get_mtu(self.pg1.sw_if_index))
# Should fail. Too large MTU
- p_icmp4 = ICMP(type='dest-unreach', code='fragmentation-needed',
- nexthopmtu=576, chksum=0x2dbb)
- icmp4_reply = (IP(src=self.pg0.local_ip4,
- dst=self.pg0.remote_ip4,
- ttl=254, len=576, id=0) /
- p_icmp4 / p_ip4 / p_payload)
+ p_icmp4 = ICMP(
+ type="dest-unreach",
+ code="fragmentation-needed",
+ nexthopmtu=576,
+ chksum=0x2DBB,
+ )
+ icmp4_reply = (
+ IP(src=self.pg0.local_ip4, dst=self.pg0.remote_ip4, ttl=254, len=576, id=0)
+ / p_icmp4
+ / p_ip4
+ / p_payload
+ )
n = icmp4_reply.__class__(icmp4_reply)
s = bytes(icmp4_reply)
icmp4_reply = s[0:576]
- rx = self.send_and_expect_some(self.pg0, p4*11, self.pg0)
+ rx = self.send_and_expect_some(self.pg0, p4 * 11, self.pg0)
for p in rx:
# p.show2()
# n.show2()
@@ -112,8 +117,7 @@ class TestMTU(VppTestCase):
# Now with DF off. Expect fragments.
# First go with 1500 byte packets.
- p_payload = UDP(sport=1234, dport=1234) / self.payload(
- 1500 - 20 - 8)
+ p_payload = UDP(sport=1234, dport=1234) / self.payload(1500 - 20 - 8)
p4 = p_ether / p_ip4 / p_payload
p4.flags = 0
p4_reply = p_ip4 / p_payload
@@ -121,13 +125,13 @@ class TestMTU(VppTestCase):
p4_reply.flags = 0
p4_reply.id = 256
self.pg_enable_capture()
- self.pg0.add_stream(p4*1)
+ self.pg0.add_stream(p4 * 1)
self.pg_start()
rx = self.pg1.get_capture(3)
reass_pkt = reassemble4(rx)
self.validate(reass_pkt, p4_reply)
- '''
+ """
# Now what happens with a 9K frame
p_payload = UDP(sport=1234, dport=1234) / self.payload(
current_mtu - 20 - 8)
@@ -146,27 +150,25 @@ class TestMTU(VppTestCase):
reass_pkt.show2()
p4_reply.show2()
self.validate(reass_pkt, p4_reply)
- '''
+ """
# Reset MTU
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [current_mtu, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [current_mtu, 0, 0, 0])
def test_ip6_mtu(self):
- """ IP6 MTU test """
+ """IP6 MTU test"""
current_mtu = self.get_mtu(self.pg1.sw_if_index)
p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
p_ip6 = IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6)
- p_payload = UDP(sport=1234, dport=1234) / self.payload(
- current_mtu - 40 - 8)
+ p_payload = UDP(sport=1234, dport=1234) / self.payload(current_mtu - 40 - 8)
p6 = p_ether / p_ip6 / p_payload
p6_reply = p_ip6 / p_payload
p6_reply.hlim -= 1
- rx = self.send_and_expect(self.pg0, p6*9, self.pg1)
+ rx = self.send_and_expect(self.pg0, p6 * 9, self.pg1)
for p in rx:
self.validate(p[1], p6_reply)
@@ -175,24 +177,25 @@ class TestMTU(VppTestCase):
self.assertEqual(1280, self.get_mtu(self.pg1.sw_if_index))
# Should fail. Too large MTU
- p_icmp6 = ICMPv6PacketTooBig(mtu=1280, cksum=0x4c7a)
- icmp6_reply = (IPv6(src=self.pg0.local_ip6,
- dst=self.pg0.remote_ip6,
- hlim=255, plen=1240) /
- p_icmp6 / p_ip6 / p_payload)
+ p_icmp6 = ICMPv6PacketTooBig(mtu=1280, cksum=0x4C7A)
+ icmp6_reply = (
+ IPv6(src=self.pg0.local_ip6, dst=self.pg0.remote_ip6, hlim=255, plen=1240)
+ / p_icmp6
+ / p_ip6
+ / p_payload
+ )
icmp6_reply[2].hlim -= 1
n = icmp6_reply.__class__(icmp6_reply)
s = bytes(icmp6_reply)
icmp6_reply_str = s[0:1280]
- rx = self.send_and_expect_some(self.pg0, p6*9, self.pg0)
+ rx = self.send_and_expect_some(self.pg0, p6 * 9, self.pg0)
for p in rx:
self.validate_bytes(bytes(p[1]), icmp6_reply_str)
# Reset MTU
- self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index,
- [current_mtu, 0, 0, 0])
+ self.vapi.sw_interface_set_mtu(self.pg1.sw_if_index, [current_mtu, 0, 0, 0])
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_nat44_ed.py b/test/test_nat44_ed.py
index 21eebb22de4..77459874c09 100644
--- a/test/test_nat44_ed.py
+++ b/test/test_nat44_ed.py
@@ -21,9 +21,9 @@ from util import StatsDiff
class TestNAT44ED(VppTestCase):
- """ NAT44ED Test Case """
+ """NAT44ED Test Case"""
- nat_addr = '10.0.10.3'
+ nat_addr = "10.0.10.3"
tcp_port_in = 6303
tcp_port_out = 6303
@@ -48,8 +48,7 @@ class TestNAT44ED(VppTestCase):
self.plugin_disable()
def plugin_enable(self):
- self.vapi.nat44_ed_plugin_enable_disable(
- sessions=self.max_sessions, enable=1)
+ self.vapi.nat44_ed_plugin_enable_disable(sessions=self.max_sessions, enable=1)
def plugin_disable(self):
self.vapi.nat44_ed_plugin_enable_disable(enable=0)
@@ -87,7 +86,7 @@ class TestNAT44ED(VppTestCase):
@classmethod
def create_and_add_ip4_table(cls, i, table_id=0):
- cls.vapi.ip_table_add_del(is_add=1, table={'table_id': table_id})
+ cls.vapi.ip_table_add_del(is_add=1, table={"table_id": table_id})
i.set_table_ip4(table_id)
@classmethod
@@ -105,32 +104,41 @@ class TestNAT44ED(VppTestCase):
@classmethod
def nat_add_interface_address(cls, i):
- cls.vapi.nat44_add_del_interface_addr(
- sw_if_index=i.sw_if_index, is_add=1)
+ cls.vapi.nat44_add_del_interface_addr(sw_if_index=i.sw_if_index, is_add=1)
def nat_add_inside_interface(self, i):
self.vapi.nat44_interface_add_del_feature(
- flags=self.config_flags.NAT_IS_INSIDE,
- sw_if_index=i.sw_if_index, is_add=1)
+ flags=self.config_flags.NAT_IS_INSIDE, sw_if_index=i.sw_if_index, is_add=1
+ )
def nat_add_outside_interface(self, i):
self.vapi.nat44_interface_add_del_feature(
- flags=self.config_flags.NAT_IS_OUTSIDE,
- sw_if_index=i.sw_if_index, is_add=1)
+ flags=self.config_flags.NAT_IS_OUTSIDE, sw_if_index=i.sw_if_index, is_add=1
+ )
- def nat_add_address(self, address, twice_nat=0,
- vrf_id=0xFFFFFFFF, is_add=1):
+ def nat_add_address(self, address, twice_nat=0, vrf_id=0xFFFFFFFF, is_add=1):
flags = self.config_flags.NAT_IS_TWICE_NAT if twice_nat else 0
- self.vapi.nat44_add_del_address_range(first_ip_address=address,
- last_ip_address=address,
- vrf_id=vrf_id,
- is_add=is_add,
- flags=flags)
+ self.vapi.nat44_add_del_address_range(
+ first_ip_address=address,
+ last_ip_address=address,
+ vrf_id=vrf_id,
+ is_add=is_add,
+ flags=flags,
+ )
- def nat_add_static_mapping(self, local_ip, external_ip='0.0.0.0',
- local_port=0, external_port=0, vrf_id=0,
- is_add=1, external_sw_if_index=0xFFFFFFFF,
- proto=0, tag="", flags=0):
+ def nat_add_static_mapping(
+ self,
+ local_ip,
+ external_ip="0.0.0.0",
+ local_port=0,
+ external_port=0,
+ vrf_id=0,
+ is_add=1,
+ external_sw_if_index=0xFFFFFFFF,
+ proto=0,
+ tag="",
+ flags=0,
+ ):
if not (local_port and external_port):
flags |= self.config_flags.NAT_IS_ADDR_ONLY
@@ -142,9 +150,11 @@ class TestNAT44ED(VppTestCase):
external_sw_if_index=external_sw_if_index,
local_port=local_port,
external_port=external_port,
- vrf_id=vrf_id, protocol=proto,
+ vrf_id=vrf_id,
+ protocol=proto,
flags=flags,
- tag=tag)
+ tag=tag,
+ )
@classmethod
def setUpClass(cls):
@@ -159,14 +169,14 @@ class TestNAT44ED(VppTestCase):
cls.configure_ip4_interface(i, hosts=3)
# test specific (test-multiple-vrf)
- cls.vapi.ip_table_add_del(is_add=1, table={'table_id': 1})
+ cls.vapi.ip_table_add_del(is_add=1, table={"table_id": 1})
# test specific (test-one-armed-nat44-static)
cls.pg4.generate_remote_hosts(2)
cls.pg4.config_ip4()
cls.vapi.sw_interface_add_del_address(
- sw_if_index=cls.pg4.sw_if_index,
- prefix="10.0.0.1/24")
+ sw_if_index=cls.pg4.sw_if_index, prefix="10.0.0.1/24"
+ )
cls.pg4.admin_up()
cls.pg4.resolve_arp()
cls.pg4._remote_hosts[1]._ip4 = cls.pg4._remote_hosts[0]._ip4
@@ -190,58 +200,95 @@ class TestNAT44ED(VppTestCase):
rl = list()
- rl.append(VppIpRoute(cls, "0.0.0.0", 0,
- [VppRoutePath("0.0.0.0", 0xffffffff,
- nh_table_id=0)],
- register=False, table_id=1))
- rl.append(VppIpRoute(cls, "0.0.0.0", 0,
- [VppRoutePath(cls.pg1.local_ip4,
- cls.pg1.sw_if_index)],
- register=False))
- rl.append(VppIpRoute(cls, cls.pg5.remote_ip4, 32,
- [VppRoutePath("0.0.0.0",
- cls.pg5.sw_if_index)],
- register=False, table_id=1))
- rl.append(VppIpRoute(cls, cls.pg6.remote_ip4, 32,
- [VppRoutePath("0.0.0.0",
- cls.pg6.sw_if_index)],
- register=False, table_id=1))
- rl.append(VppIpRoute(cls, cls.pg6.remote_ip4, 16,
- [VppRoutePath("0.0.0.0", 0xffffffff,
- nh_table_id=1)],
- register=False, table_id=0))
+ rl.append(
+ VppIpRoute(
+ cls,
+ "0.0.0.0",
+ 0,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)],
+ register=False,
+ table_id=1,
+ )
+ )
+ rl.append(
+ VppIpRoute(
+ cls,
+ "0.0.0.0",
+ 0,
+ [VppRoutePath(cls.pg1.local_ip4, cls.pg1.sw_if_index)],
+ register=False,
+ )
+ )
+ rl.append(
+ VppIpRoute(
+ cls,
+ cls.pg5.remote_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", cls.pg5.sw_if_index)],
+ register=False,
+ table_id=1,
+ )
+ )
+ rl.append(
+ VppIpRoute(
+ cls,
+ cls.pg6.remote_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", cls.pg6.sw_if_index)],
+ register=False,
+ table_id=1,
+ )
+ )
+ rl.append(
+ VppIpRoute(
+ cls,
+ cls.pg6.remote_ip4,
+ 16,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)],
+ register=False,
+ table_id=0,
+ )
+ )
for r in rl:
r.add_vpp_config()
- cls.no_diff = StatsDiff({
- pg.sw_if_index: {
- '/nat44-ed/in2out/fastpath/tcp': 0,
- '/nat44-ed/in2out/fastpath/udp': 0,
- '/nat44-ed/in2out/fastpath/icmp': 0,
- '/nat44-ed/in2out/fastpath/drops': 0,
- '/nat44-ed/in2out/slowpath/tcp': 0,
- '/nat44-ed/in2out/slowpath/udp': 0,
- '/nat44-ed/in2out/slowpath/icmp': 0,
- '/nat44-ed/in2out/slowpath/drops': 0,
- '/nat44-ed/in2out/fastpath/tcp': 0,
- '/nat44-ed/in2out/fastpath/udp': 0,
- '/nat44-ed/in2out/fastpath/icmp': 0,
- '/nat44-ed/in2out/fastpath/drops': 0,
- '/nat44-ed/in2out/slowpath/tcp': 0,
- '/nat44-ed/in2out/slowpath/udp': 0,
- '/nat44-ed/in2out/slowpath/icmp': 0,
- '/nat44-ed/in2out/slowpath/drops': 0,
+ cls.no_diff = StatsDiff(
+ {
+ pg.sw_if_index: {
+ "/nat44-ed/in2out/fastpath/tcp": 0,
+ "/nat44-ed/in2out/fastpath/udp": 0,
+ "/nat44-ed/in2out/fastpath/icmp": 0,
+ "/nat44-ed/in2out/fastpath/drops": 0,
+ "/nat44-ed/in2out/slowpath/tcp": 0,
+ "/nat44-ed/in2out/slowpath/udp": 0,
+ "/nat44-ed/in2out/slowpath/icmp": 0,
+ "/nat44-ed/in2out/slowpath/drops": 0,
+ "/nat44-ed/in2out/fastpath/tcp": 0,
+ "/nat44-ed/in2out/fastpath/udp": 0,
+ "/nat44-ed/in2out/fastpath/icmp": 0,
+ "/nat44-ed/in2out/fastpath/drops": 0,
+ "/nat44-ed/in2out/slowpath/tcp": 0,
+ "/nat44-ed/in2out/slowpath/udp": 0,
+ "/nat44-ed/in2out/slowpath/icmp": 0,
+ "/nat44-ed/in2out/slowpath/drops": 0,
+ }
+ for pg in cls.pg_interfaces
}
- for pg in cls.pg_interfaces
- })
+ )
def get_err_counter(self, path):
return self.statistics.get_err_counter(path)
- def reass_hairpinning(self, server_addr, server_in_port, server_out_port,
- host_in_port, proto=IP_PROTOS.tcp,
- ignore_port=False):
+ def reass_hairpinning(
+ self,
+ server_addr,
+ server_in_port,
+ server_out_port,
+ host_in_port,
+ proto=IP_PROTOS.tcp,
+ ignore_port=False,
+ ):
layer = self.proto2layer(proto)
if proto == IP_PROTOS.tcp:
@@ -250,19 +297,14 @@ class TestNAT44ED(VppTestCase):
data = b"A" * 16 + b"B" * 16 + b"C" * 3
# send packet from host to server
- pkts = self.create_stream_frag(self.pg0,
- self.nat_addr,
- host_in_port,
- server_out_port,
- data,
- proto)
+ pkts = self.create_stream_frag(
+ self.pg0, self.nat_addr, host_in_port, server_out_port, data, proto
+ )
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg0.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- self.nat_addr,
- server_addr)
+ p = self.reass_frags_and_verify(frags, self.nat_addr, server_addr)
if proto != IP_PROTOS.icmp:
if not ignore_port:
self.assertNotEqual(p[layer].sport, host_in_port)
@@ -272,8 +314,9 @@ class TestNAT44ED(VppTestCase):
self.assertNotEqual(p[layer].id, host_in_port)
self.assertEqual(data, p[Raw].load)
- def frag_out_of_order(self, proto=IP_PROTOS.tcp, dont_translate=False,
- ignore_port=False):
+ def frag_out_of_order(
+ self, proto=IP_PROTOS.tcp, dont_translate=False, ignore_port=False
+ ):
layer = self.proto2layer(proto)
if proto == IP_PROTOS.tcp:
@@ -284,21 +327,22 @@ class TestNAT44ED(VppTestCase):
for i in range(2):
# in2out
- pkts = self.create_stream_frag(self.pg0, self.pg1.remote_ip4,
- self.port_in, 20, data, proto)
+ pkts = self.create_stream_frag(
+ self.pg0, self.pg1.remote_ip4, self.port_in, 20, data, proto
+ )
pkts.reverse()
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg1.get_capture(len(pkts))
if not dont_translate:
- p = self.reass_frags_and_verify(frags,
- self.nat_addr,
- self.pg1.remote_ip4)
+ p = self.reass_frags_and_verify(
+ frags, self.nat_addr, self.pg1.remote_ip4
+ )
else:
- p = self.reass_frags_and_verify(frags,
- self.pg0.remote_ip4,
- self.pg1.remote_ip4)
+ p = self.reass_frags_and_verify(
+ frags, self.pg0.remote_ip4, self.pg1.remote_ip4
+ )
if proto != IP_PROTOS.icmp:
if not dont_translate:
self.assertEqual(p[layer].dport, 20)
@@ -325,17 +369,18 @@ class TestNAT44ED(VppTestCase):
else:
sport = p[layer].id
dport = 0
- pkts = self.create_stream_frag(self.pg1, dst_addr, sport, dport,
- data, proto, echo_reply=True)
+ pkts = self.create_stream_frag(
+ self.pg1, dst_addr, sport, dport, data, proto, echo_reply=True
+ )
pkts.reverse()
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.logger.info(self.vapi.cli("show trace"))
self.pg_start()
frags = self.pg0.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- self.pg1.remote_ip4,
- self.pg0.remote_ip4)
+ p = self.reass_frags_and_verify(
+ frags, self.pg1.remote_ip4, self.pg0.remote_ip4
+ )
if proto != IP_PROTOS.icmp:
self.assertEqual(p[layer].sport, 20)
self.assertEqual(p[layer].dport, self.port_in)
@@ -351,21 +396,20 @@ class TestNAT44ED(VppTestCase):
self.assert_ip_checksum_valid(p)
buffer.seek(p[IP].frag * 8)
buffer.write(bytes(p[IP].payload))
- ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst,
- proto=frags[0][IP].proto)
+ ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst, proto=frags[0][IP].proto)
if ip.proto == IP_PROTOS.tcp:
- p = (ip / TCP(buffer.getvalue()))
+ p = ip / TCP(buffer.getvalue())
self.logger.debug(ppp("Reassembled:", p))
self.assert_tcp_checksum_valid(p)
elif ip.proto == IP_PROTOS.udp:
- p = (ip / UDP(buffer.getvalue()[:8]) /
- Raw(buffer.getvalue()[8:]))
+ p = ip / UDP(buffer.getvalue()[:8]) / Raw(buffer.getvalue()[8:])
elif ip.proto == IP_PROTOS.icmp:
- p = (ip / ICMP(buffer.getvalue()))
+ p = ip / ICMP(buffer.getvalue())
return p
- def frag_in_order(self, proto=IP_PROTOS.tcp, dont_translate=False,
- ignore_port=False):
+ def frag_in_order(
+ self, proto=IP_PROTOS.tcp, dont_translate=False, ignore_port=False
+ ):
layer = self.proto2layer(proto)
if proto == IP_PROTOS.tcp:
@@ -375,20 +419,19 @@ class TestNAT44ED(VppTestCase):
self.port_in = self.random_port()
# in2out
- pkts = self.create_stream_frag(self.pg0, self.pg1.remote_ip4,
- self.port_in, 20, data, proto)
+ pkts = self.create_stream_frag(
+ self.pg0, self.pg1.remote_ip4, self.port_in, 20, data, proto
+ )
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg1.get_capture(len(pkts))
if not dont_translate:
- p = self.reass_frags_and_verify(frags,
- self.nat_addr,
- self.pg1.remote_ip4)
+ p = self.reass_frags_and_verify(frags, self.nat_addr, self.pg1.remote_ip4)
else:
- p = self.reass_frags_and_verify(frags,
- self.pg0.remote_ip4,
- self.pg1.remote_ip4)
+ p = self.reass_frags_and_verify(
+ frags, self.pg0.remote_ip4, self.pg1.remote_ip4
+ )
if proto != IP_PROTOS.icmp:
if not dont_translate:
self.assertEqual(p[layer].dport, 20)
@@ -415,15 +458,14 @@ class TestNAT44ED(VppTestCase):
else:
sport = p[layer].id
dport = 0
- pkts = self.create_stream_frag(self.pg1, dst_addr, sport, dport, data,
- proto, echo_reply=True)
+ pkts = self.create_stream_frag(
+ self.pg1, dst_addr, sport, dport, data, proto, echo_reply=True
+ )
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg0.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- self.pg1.remote_ip4,
- self.pg0.remote_ip4)
+ p = self.reass_frags_and_verify(frags, self.pg1.remote_ip4, self.pg0.remote_ip4)
if proto != IP_PROTOS.icmp:
self.assertEqual(p[layer].sport, 20)
self.assertEqual(p[layer].dport, self.port_in)
@@ -431,8 +473,9 @@ class TestNAT44ED(VppTestCase):
self.assertEqual(p[layer].id, self.port_in)
self.assertEqual(data, p[Raw].load)
- def verify_capture_out(self, capture, nat_ip=None, same_port=False,
- dst_ip=None, ignore_port=False):
+ def verify_capture_out(
+ self, capture, nat_ip=None, same_port=False, dst_ip=None, ignore_port=False
+ ):
if nat_ip is None:
nat_ip = self.nat_addr
for packet in capture:
@@ -444,35 +487,30 @@ class TestNAT44ED(VppTestCase):
if packet.haslayer(TCP):
if not ignore_port:
if same_port:
- self.assertEqual(
- packet[TCP].sport, self.tcp_port_in)
+ self.assertEqual(packet[TCP].sport, self.tcp_port_in)
else:
- self.assertNotEqual(
- packet[TCP].sport, self.tcp_port_in)
+ self.assertNotEqual(packet[TCP].sport, self.tcp_port_in)
self.tcp_port_out = packet[TCP].sport
self.assert_packet_checksums_valid(packet)
elif packet.haslayer(UDP):
if not ignore_port:
if same_port:
- self.assertEqual(
- packet[UDP].sport, self.udp_port_in)
+ self.assertEqual(packet[UDP].sport, self.udp_port_in)
else:
- self.assertNotEqual(
- packet[UDP].sport, self.udp_port_in)
+ self.assertNotEqual(packet[UDP].sport, self.udp_port_in)
self.udp_port_out = packet[UDP].sport
else:
if not ignore_port:
if same_port:
- self.assertEqual(
- packet[ICMP].id, self.icmp_id_in)
+ self.assertEqual(packet[ICMP].id, self.icmp_id_in)
else:
- self.assertNotEqual(
- packet[ICMP].id, self.icmp_id_in)
+ self.assertNotEqual(packet[ICMP].id, self.icmp_id_in)
self.icmp_id_out = packet[ICMP].id
self.assert_packet_checksums_valid(packet)
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(outside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (outside network):", packet)
+ )
raise
def verify_capture_in(self, capture, in_if):
@@ -487,8 +525,9 @@ class TestNAT44ED(VppTestCase):
else:
self.assertEqual(packet[ICMP].id, self.icmp_id_in)
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(inside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (inside network):", packet)
+ )
raise
def create_stream_in(self, in_if, out_if, dst_ip=None, ttl=64):
@@ -497,27 +536,32 @@ class TestNAT44ED(VppTestCase):
pkts = []
# TCP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- TCP(sport=self.tcp_port_in, dport=20))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / TCP(sport=self.tcp_port_in, dport=20)
+ )
pkts.extend([p, p])
# UDP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- UDP(sport=self.udp_port_in, dport=20))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / UDP(sport=self.udp_port_in, dport=20)
+ )
pkts.append(p)
# ICMP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- ICMP(id=self.icmp_id_in, type='echo-request'))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / ICMP(id=self.icmp_id_in, type="echo-request")
+ )
pkts.append(p)
return pkts
- def create_stream_out(self, out_if, dst_ip=None, ttl=64,
- use_inside_ports=False):
+ def create_stream_out(self, out_if, dst_ip=None, ttl=64, use_inside_ports=False):
if dst_ip is None:
dst_ip = self.nat_addr
if not use_inside_ports:
@@ -530,21 +574,27 @@ class TestNAT44ED(VppTestCase):
icmp_id = self.icmp_id_in
pkts = []
# TCP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- TCP(dport=tcp_port, sport=20))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / TCP(dport=tcp_port, sport=20)
+ )
pkts.extend([p, p])
# UDP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- UDP(dport=udp_port, sport=20))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / UDP(dport=udp_port, sport=20)
+ )
pkts.append(p)
# ICMP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- ICMP(id=icmp_id, type='echo-reply'))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / ICMP(id=icmp_id, type="echo-reply")
+ )
pkts.append(p)
return pkts
@@ -554,19 +604,24 @@ class TestNAT44ED(VppTestCase):
port = 6303
for i in range(count):
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=64) /
- TCP(sport=port + i, dport=20))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4, ttl=64)
+ / TCP(sport=port + i, dport=20)
+ )
pkts.append(p)
return pkts
- def create_stream_frag(self, src_if, dst, sport, dport, data,
- proto=IP_PROTOS.tcp, echo_reply=False):
+ def create_stream_frag(
+ self, src_if, dst, sport, dport, data, proto=IP_PROTOS.tcp, echo_reply=False
+ ):
if proto == IP_PROTOS.tcp:
- p = (IP(src=src_if.remote_ip4, dst=dst) /
- TCP(sport=sport, dport=dport) /
- Raw(data))
+ p = (
+ IP(src=src_if.remote_ip4, dst=dst)
+ / TCP(sport=sport, dport=dport)
+ / Raw(data)
+ )
p = p.__class__(scapy.compat.raw(p))
chksum = p[TCP].chksum
proto_header = TCP(sport=sport, dport=dport, chksum=chksum)
@@ -574,9 +629,9 @@ class TestNAT44ED(VppTestCase):
proto_header = UDP(sport=sport, dport=dport)
elif proto == IP_PROTOS.icmp:
if not echo_reply:
- proto_header = ICMP(id=sport, type='echo-request')
+ proto_header = ICMP(id=sport, type="echo-request")
else:
- proto_header = ICMP(id=sport, type='echo-reply')
+ proto_header = ICMP(id=sport, type="echo-reply")
else:
raise Exception("Unsupported protocol")
id = self.random_port()
@@ -585,33 +640,38 @@ class TestNAT44ED(VppTestCase):
raw = Raw(data[0:4])
else:
raw = Raw(data[0:16])
- p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
- IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id) /
- proto_header /
- raw)
+ p = (
+ Ether(src=src_if.remote_mac, dst=src_if.local_mac)
+ / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id)
+ / proto_header
+ / raw
+ )
pkts.append(p)
if proto == IP_PROTOS.tcp:
raw = Raw(data[4:20])
else:
raw = Raw(data[16:32])
- p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
- IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id,
- proto=proto) /
- raw)
+ p = (
+ Ether(src=src_if.remote_mac, dst=src_if.local_mac)
+ / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id, proto=proto)
+ / raw
+ )
pkts.append(p)
if proto == IP_PROTOS.tcp:
raw = Raw(data[20:])
else:
raw = Raw(data[32:])
- p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
- IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto,
- id=id) /
- raw)
+ p = (
+ Ether(src=src_if.remote_mac, dst=src_if.local_mac)
+ / IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto, id=id)
+ / raw
+ )
pkts.append(p)
return pkts
- def frag_in_order_in_plus_out(self, in_addr, out_addr, in_port, out_port,
- proto=IP_PROTOS.tcp):
+ def frag_in_order_in_plus_out(
+ self, in_addr, out_addr, in_port, out_port, proto=IP_PROTOS.tcp
+ ):
layer = self.proto2layer(proto)
@@ -623,16 +683,14 @@ class TestNAT44ED(VppTestCase):
for i in range(2):
# out2in
- pkts = self.create_stream_frag(self.pg0, out_addr,
- port_in, out_port,
- data, proto)
+ pkts = self.create_stream_frag(
+ self.pg0, out_addr, port_in, out_port, data, proto
+ )
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg1.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- self.pg0.remote_ip4,
- in_addr)
+ p = self.reass_frags_and_verify(frags, self.pg0.remote_ip4, in_addr)
if proto != IP_PROTOS.icmp:
self.assertEqual(p[layer].sport, port_in)
self.assertEqual(p[layer].dport, in_port)
@@ -642,20 +700,24 @@ class TestNAT44ED(VppTestCase):
# in2out
if proto != IP_PROTOS.icmp:
- pkts = self.create_stream_frag(self.pg1, self.pg0.remote_ip4,
- in_port,
- p[layer].sport, data, proto)
+ pkts = self.create_stream_frag(
+ self.pg1, self.pg0.remote_ip4, in_port, p[layer].sport, data, proto
+ )
else:
- pkts = self.create_stream_frag(self.pg1, self.pg0.remote_ip4,
- p[layer].id, 0, data, proto,
- echo_reply=True)
+ pkts = self.create_stream_frag(
+ self.pg1,
+ self.pg0.remote_ip4,
+ p[layer].id,
+ 0,
+ data,
+ proto,
+ echo_reply=True,
+ )
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg0.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- out_addr,
- self.pg0.remote_ip4)
+ p = self.reass_frags_and_verify(frags, out_addr, self.pg0.remote_ip4)
if proto != IP_PROTOS.icmp:
self.assertEqual(p[layer].sport, out_port)
self.assertEqual(p[layer].dport, port_in)
@@ -663,8 +725,9 @@ class TestNAT44ED(VppTestCase):
self.assertEqual(p[layer].id, port_in)
self.assertEqual(data, p[Raw].load)
- def frag_out_of_order_in_plus_out(self, in_addr, out_addr, in_port,
- out_port, proto=IP_PROTOS.tcp):
+ def frag_out_of_order_in_plus_out(
+ self, in_addr, out_addr, in_port, out_port, proto=IP_PROTOS.tcp
+ ):
layer = self.proto2layer(proto)
@@ -676,17 +739,15 @@ class TestNAT44ED(VppTestCase):
for i in range(2):
# out2in
- pkts = self.create_stream_frag(self.pg0, out_addr,
- port_in, out_port,
- data, proto)
+ pkts = self.create_stream_frag(
+ self.pg0, out_addr, port_in, out_port, data, proto
+ )
pkts.reverse()
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg1.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- self.pg0.remote_ip4,
- in_addr)
+ p = self.reass_frags_and_verify(frags, self.pg0.remote_ip4, in_addr)
if proto != IP_PROTOS.icmp:
self.assertEqual(p[layer].dport, in_port)
self.assertEqual(p[layer].sport, port_in)
@@ -697,21 +758,25 @@ class TestNAT44ED(VppTestCase):
# in2out
if proto != IP_PROTOS.icmp:
- pkts = self.create_stream_frag(self.pg1, self.pg0.remote_ip4,
- in_port,
- p[layer].sport, data, proto)
+ pkts = self.create_stream_frag(
+ self.pg1, self.pg0.remote_ip4, in_port, p[layer].sport, data, proto
+ )
else:
- pkts = self.create_stream_frag(self.pg1, self.pg0.remote_ip4,
- p[layer].id, 0, data, proto,
- echo_reply=True)
+ pkts = self.create_stream_frag(
+ self.pg1,
+ self.pg0.remote_ip4,
+ p[layer].id,
+ 0,
+ data,
+ proto,
+ echo_reply=True,
+ )
pkts.reverse()
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg0.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- out_addr,
- self.pg0.remote_ip4)
+ p = self.reass_frags_and_verify(frags, out_addr, self.pg0.remote_ip4)
if proto != IP_PROTOS.icmp:
self.assertEqual(p[layer].sport, out_port)
self.assertEqual(p[layer].dport, port_in)
@@ -721,9 +786,11 @@ class TestNAT44ED(VppTestCase):
def init_tcp_session(self, in_if, out_if, in_port, ext_port):
# SYN packet in->out
- p = (Ether(src=in_if.remote_mac, dst=in_if.local_mac) /
- IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) /
- TCP(sport=in_port, dport=ext_port, flags="S"))
+ p = (
+ Ether(src=in_if.remote_mac, dst=in_if.local_mac)
+ / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="S")
+ )
in_if.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -732,18 +799,22 @@ class TestNAT44ED(VppTestCase):
out_port = p[TCP].sport
# SYN + ACK packet out->in
- p = (Ether(src=out_if.remote_mac, dst=out_if.local_mac) /
- IP(src=out_if.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port, flags="SA"))
+ p = (
+ Ether(src=out_if.remote_mac, dst=out_if.local_mac)
+ / IP(src=out_if.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="SA")
+ )
out_if.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
in_if.get_capture(1)
# ACK packet in->out
- p = (Ether(src=in_if.remote_mac, dst=in_if.local_mac) /
- IP(src=in_if.remote_ip4, dst=out_if.remote_ip4) /
- TCP(sport=in_port, dport=ext_port, flags="A"))
+ p = (
+ Ether(src=in_if.remote_mac, dst=in_if.local_mac)
+ / IP(src=in_if.remote_ip4, dst=out_if.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A")
+ )
in_if.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -751,9 +822,10 @@ class TestNAT44ED(VppTestCase):
return out_port
- def twice_nat_common(self, self_twice_nat=False, same_pg=False, lb=False,
- client_id=None):
- twice_nat_addr = '10.0.1.3'
+ def twice_nat_common(
+ self, self_twice_nat=False, same_pg=False, lb=False, client_id=None
+ ):
+ twice_nat_addr = "10.0.1.3"
port_in = 8080
if lb:
@@ -780,8 +852,7 @@ class TestNAT44ED(VppTestCase):
else:
pg1 = self.pg1
- eh_translate = ((not self_twice_nat) or (not lb and same_pg) or
- client_id == 1)
+ eh_translate = (not self_twice_nat) or (not lb and same_pg) or client_id == 1
self.nat_add_address(self.nat_addr)
self.nat_add_address(twice_nat_addr, twice_nat=1)
@@ -793,27 +864,30 @@ class TestNAT44ED(VppTestCase):
flags |= self.config_flags.NAT_IS_TWICE_NAT
if not lb:
- self.nat_add_static_mapping(pg0.remote_ip4, self.nat_addr,
- port_in, port_out,
- proto=IP_PROTOS.tcp,
- flags=flags)
+ self.nat_add_static_mapping(
+ pg0.remote_ip4,
+ self.nat_addr,
+ port_in,
+ port_out,
+ proto=IP_PROTOS.tcp,
+ flags=flags,
+ )
else:
- locals = [{'addr': server1.ip4,
- 'port': port_in1,
- 'probability': 50,
- 'vrf_id': 0},
- {'addr': server2.ip4,
- 'port': port_in2,
- 'probability': 50,
- 'vrf_id': 0}]
+ locals = [
+ {"addr": server1.ip4, "port": port_in1, "probability": 50, "vrf_id": 0},
+ {"addr": server2.ip4, "port": port_in2, "probability": 50, "vrf_id": 0},
+ ]
out_addr = self.nat_addr
- self.vapi.nat44_add_del_lb_static_mapping(is_add=1, flags=flags,
- external_addr=out_addr,
- external_port=port_out,
- protocol=IP_PROTOS.tcp,
- local_num=len(locals),
- locals=locals)
+ self.vapi.nat44_add_del_lb_static_mapping(
+ is_add=1,
+ flags=flags,
+ external_addr=out_addr,
+ external_port=port_out,
+ protocol=IP_PROTOS.tcp,
+ local_num=len(locals),
+ locals=locals,
+ )
self.nat_add_inside_interface(pg0)
self.nat_add_outside_interface(pg1)
@@ -828,9 +902,11 @@ class TestNAT44ED(VppTestCase):
client = self.pg0.remote_hosts[1]
else:
client = pg1.remote_hosts[0]
- p = (Ether(src=pg1.remote_mac, dst=pg1.local_mac) /
- IP(src=client.ip4, dst=self.nat_addr) /
- TCP(sport=eh_port_out, dport=port_out))
+ p = (
+ Ether(src=pg1.remote_mac, dst=pg1.local_mac)
+ / IP(src=client.ip4, dst=self.nat_addr)
+ / TCP(sport=eh_port_out, dport=port_out)
+ )
pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -865,9 +941,11 @@ class TestNAT44ED(VppTestCase):
self.logger.error(ppp("Unexpected or invalid packet:", p))
raise
- p = (Ether(src=server.mac, dst=pg0.local_mac) /
- IP(src=server.ip4, dst=eh_addr_in) /
- TCP(sport=saved_port_in, dport=eh_port_in))
+ p = (
+ Ether(src=server.mac, dst=pg0.local_mac)
+ / IP(src=server.ip4, dst=eh_addr_in)
+ / TCP(sport=saved_port_in, dport=eh_port_in)
+ )
pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -888,24 +966,25 @@ class TestNAT44ED(VppTestCase):
if eh_translate:
sessions = self.vapi.nat44_user_session_dump(server.ip4, 0)
self.assertEqual(len(sessions), 1)
- self.assertTrue(sessions[0].flags &
- self.config_flags.NAT_IS_EXT_HOST_VALID)
- self.assertTrue(sessions[0].flags &
- self.config_flags.NAT_IS_TWICE_NAT)
+ self.assertTrue(sessions[0].flags & self.config_flags.NAT_IS_EXT_HOST_VALID)
+ self.assertTrue(sessions[0].flags & self.config_flags.NAT_IS_TWICE_NAT)
self.logger.info(self.vapi.cli("show nat44 sessions"))
self.vapi.nat44_del_session(
address=sessions[0].inside_ip_address,
port=sessions[0].inside_port,
protocol=sessions[0].protocol,
- flags=(self.config_flags.NAT_IS_INSIDE |
- self.config_flags.NAT_IS_EXT_HOST_VALID),
+ flags=(
+ self.config_flags.NAT_IS_INSIDE
+ | self.config_flags.NAT_IS_EXT_HOST_VALID
+ ),
ext_host_address=sessions[0].ext_host_nat_address,
- ext_host_port=sessions[0].ext_host_nat_port)
+ ext_host_port=sessions[0].ext_host_nat_port,
+ )
sessions = self.vapi.nat44_user_session_dump(server.ip4, 0)
self.assertEqual(len(sessions), 0)
def verify_syslog_sess(self, data, msgid, is_ip6=False):
- message = data.decode('utf-8')
+ message = data.decode("utf-8")
try:
message = SyslogMessage.parse(message)
except ParseError as e:
@@ -913,29 +992,28 @@ class TestNAT44ED(VppTestCase):
raise
else:
self.assertEqual(message.severity, SyslogSeverity.info)
- self.assertEqual(message.appname, 'NAT')
+ self.assertEqual(message.appname, "NAT")
self.assertEqual(message.msgid, msgid)
- sd_params = message.sd.get('nsess')
+ sd_params = message.sd.get("nsess")
self.assertTrue(sd_params is not None)
if is_ip6:
- self.assertEqual(sd_params.get('IATYP'), 'IPv6')
- self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip6)
+ self.assertEqual(sd_params.get("IATYP"), "IPv6")
+ self.assertEqual(sd_params.get("ISADDR"), self.pg0.remote_ip6)
else:
- self.assertEqual(sd_params.get('IATYP'), 'IPv4')
- self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip4)
- self.assertTrue(sd_params.get('SSUBIX') is not None)
- self.assertEqual(sd_params.get('ISPORT'), "%d" % self.tcp_port_in)
- self.assertEqual(sd_params.get('XATYP'), 'IPv4')
- self.assertEqual(sd_params.get('XSADDR'), self.nat_addr)
- self.assertEqual(sd_params.get('XSPORT'), "%d" % self.tcp_port_out)
- self.assertEqual(sd_params.get('PROTO'), "%d" % IP_PROTOS.tcp)
- self.assertEqual(sd_params.get('SVLAN'), '0')
- self.assertEqual(sd_params.get('XDADDR'), self.pg1.remote_ip4)
- self.assertEqual(sd_params.get('XDPORT'),
- "%d" % self.tcp_external_port)
+ self.assertEqual(sd_params.get("IATYP"), "IPv4")
+ self.assertEqual(sd_params.get("ISADDR"), self.pg0.remote_ip4)
+ self.assertTrue(sd_params.get("SSUBIX") is not None)
+ self.assertEqual(sd_params.get("ISPORT"), "%d" % self.tcp_port_in)
+ self.assertEqual(sd_params.get("XATYP"), "IPv4")
+ self.assertEqual(sd_params.get("XSADDR"), self.nat_addr)
+ self.assertEqual(sd_params.get("XSPORT"), "%d" % self.tcp_port_out)
+ self.assertEqual(sd_params.get("PROTO"), "%d" % IP_PROTOS.tcp)
+ self.assertEqual(sd_params.get("SVLAN"), "0")
+ self.assertEqual(sd_params.get("XDADDR"), self.pg1.remote_ip4)
+ self.assertEqual(sd_params.get("XDPORT"), "%d" % self.tcp_external_port)
def test_icmp_error(self):
- """ NAT44ED test ICMP error message with inner header"""
+ """NAT44ED test ICMP error message with inner header"""
payload = "H" * 10
@@ -944,25 +1022,31 @@ class TestNAT44ED(VppTestCase):
self.nat_add_outside_interface(self.pg1)
# in2out (initiate connection)
- p1 = [Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP(sport=21, dport=20) / payload,
- Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=21, dport=20, flags="S") / payload,
- Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- ICMP(type='echo-request', id=7777) / payload,
- ]
+ p1 = [
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=21, dport=20)
+ / payload,
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=21, dport=20, flags="S")
+ / payload,
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / ICMP(type="echo-request", id=7777)
+ / payload,
+ ]
capture = self.send_and_expect(self.pg0, p1, self.pg1)
# out2in (send error message)
- p2 = [Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- ICMP(type='dest-unreach', code='port-unreachable') /
- c[IP:]
- for c in capture]
+ p2 = [
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / ICMP(type="dest-unreach", code="port-unreachable")
+ / c[IP:]
+ for c in capture
+ ]
capture = self.send_and_expect(self.pg1, p2, self.pg0)
@@ -971,20 +1055,21 @@ class TestNAT44ED(VppTestCase):
assert c[IP].dst == self.pg0.remote_ip4
assert c[IPerror].src == self.pg0.remote_ip4
except AssertionError as a:
- raise AssertionError(
- f"Packet {pr(c)} not translated properly") from a
+ raise AssertionError(f"Packet {pr(c)} not translated properly") from a
def test_icmp_echo_reply_trailer(self):
- """ ICMP echo reply with ethernet trailer"""
+ """ICMP echo reply with ethernet trailer"""
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
# in2out
- p1 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- ICMP(type=8, id=0xabcd, seq=0))
+ p1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / ICMP(type=8, id=0xABCD, seq=0)
+ )
self.pg0.add_stream(p1)
self.pg_enable_capture(self.pg_interfaces)
@@ -994,9 +1079,11 @@ class TestNAT44ED(VppTestCase):
self.logger.debug(self.vapi.cli("show trace"))
# out2in
- p2 = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr, id=0xee59) /
- ICMP(type=0, id=c[ICMP].id, seq=0))
+ p2 = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr, id=0xEE59)
+ / ICMP(type=0, id=c[ICMP].id, seq=0)
+ )
# force checksum calculation
p2 = p2.__class__(bytes(p2))
@@ -1019,7 +1106,7 @@ class TestNAT44ED(VppTestCase):
self.pg0.get_capture(1)
def test_users_dump(self):
- """ NAT44ED API test - nat44_user_dump """
+ """NAT44ED API test - nat44_user_dump"""
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
@@ -1061,9 +1148,9 @@ class TestNAT44ED(VppTestCase):
host0 = self.pg0.remote_hosts[0]
self.pg0.remote_hosts[0] = self.pg0.remote_hosts[1]
try:
- pkts = self.create_stream_out(self.pg1,
- dst_ip=self.pg0.remote_ip4,
- use_inside_ports=True)
+ pkts = self.create_stream_out(
+ self.pg1, dst_ip=self.pg0.remote_ip4, use_inside_ports=True
+ )
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1075,8 +1162,7 @@ class TestNAT44ED(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4,
- same_port=True)
+ self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4, same_port=True)
finally:
self.pg0.remote_hosts[0] = host0
@@ -1107,14 +1193,14 @@ class TestNAT44ED(VppTestCase):
self.assertEqual(non_static_user.nsessions, 3)
def test_frag_out_of_order_do_not_translate(self):
- """ NAT44ED don't translate fragments arriving out of order """
+ """NAT44ED don't translate fragments arriving out of order"""
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
self.vapi.nat44_forwarding_enable_disable(enable=True)
self.frag_out_of_order(proto=IP_PROTOS.tcp, dont_translate=True)
def test_forwarding(self):
- """ NAT44ED forwarding test """
+ """NAT44ED forwarding test"""
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
@@ -1123,11 +1209,13 @@ class TestNAT44ED(VppTestCase):
real_ip = self.pg0.remote_ip4
alias_ip = self.nat_addr
flags = self.config_flags.NAT_IS_ADDR_ONLY
- self.vapi.nat44_add_del_static_mapping(is_add=1,
- local_ip_address=real_ip,
- external_ip_address=alias_ip,
- external_sw_if_index=0xFFFFFFFF,
- flags=flags)
+ self.vapi.nat44_add_del_static_mapping(
+ is_add=1,
+ local_ip_address=real_ip,
+ external_ip_address=alias_ip,
+ external_sw_if_index=0xFFFFFFFF,
+ flags=flags,
+ )
try:
# in2out - static mapping match
@@ -1151,9 +1239,9 @@ class TestNAT44ED(VppTestCase):
host0 = self.pg0.remote_hosts[0]
self.pg0.remote_hosts[0] = self.pg0.remote_hosts[1]
try:
- pkts = self.create_stream_out(self.pg1,
- dst_ip=self.pg0.remote_ip4,
- use_inside_ports=True)
+ pkts = self.create_stream_out(
+ self.pg1, dst_ip=self.pg0.remote_ip4, use_inside_ports=True
+ )
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1165,24 +1253,27 @@ class TestNAT44ED(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4,
- same_port=True)
+ self.verify_capture_out(
+ capture, nat_ip=self.pg0.remote_ip4, same_port=True
+ )
finally:
self.pg0.remote_hosts[0] = host0
user = self.pg0.remote_hosts[1]
sessions = self.vapi.nat44_user_session_dump(user.ip4, 0)
self.assertEqual(len(sessions), 3)
- self.assertTrue(sessions[0].flags &
- self.config_flags.NAT_IS_EXT_HOST_VALID)
+ self.assertTrue(sessions[0].flags & self.config_flags.NAT_IS_EXT_HOST_VALID)
self.vapi.nat44_del_session(
address=sessions[0].inside_ip_address,
port=sessions[0].inside_port,
protocol=sessions[0].protocol,
- flags=(self.config_flags.NAT_IS_INSIDE |
- self.config_flags.NAT_IS_EXT_HOST_VALID),
+ flags=(
+ self.config_flags.NAT_IS_INSIDE
+ | self.config_flags.NAT_IS_EXT_HOST_VALID
+ ),
ext_host_address=sessions[0].ext_host_address,
- ext_host_port=sessions[0].ext_host_port)
+ ext_host_port=sessions[0].ext_host_port,
+ )
sessions = self.vapi.nat44_user_session_dump(user.ip4, 0)
self.assertEqual(len(sessions), 2)
@@ -1194,16 +1285,17 @@ class TestNAT44ED(VppTestCase):
local_ip_address=real_ip,
external_ip_address=alias_ip,
external_sw_if_index=0xFFFFFFFF,
- flags=flags)
+ flags=flags,
+ )
def test_output_feature_and_service2(self):
- """ NAT44ED interface output feature and service host direct access """
+ """NAT44ED interface output feature and service host direct access"""
self.vapi.nat44_forwarding_enable_disable(enable=1)
self.nat_add_address(self.nat_addr)
self.vapi.nat44_ed_add_del_output_interface(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# session initiated from service host - translate
pkts = self.create_stream_in(self.pg0, self.pg1)
@@ -1230,9 +1322,9 @@ class TestNAT44ED(VppTestCase):
self.icmp_id_in = 60305
try:
- pkts = self.create_stream_out(self.pg1,
- self.pg0.remote_ip4,
- use_inside_ports=True)
+ pkts = self.create_stream_out(
+ self.pg1, self.pg0.remote_ip4, use_inside_ports=True
+ )
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1244,40 +1336,37 @@ class TestNAT44ED(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4,
- same_port=True)
+ self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4, same_port=True)
finally:
self.tcp_port_in = tcp_port_in
self.udp_port_in = udp_port_in
self.icmp_id_in = icmp_id_in
def test_twice_nat(self):
- """ NAT44ED Twice NAT """
+ """NAT44ED Twice NAT"""
self.twice_nat_common()
def test_self_twice_nat_positive(self):
- """ NAT44ED Self Twice NAT (positive test) """
+ """NAT44ED Self Twice NAT (positive test)"""
self.twice_nat_common(self_twice_nat=True, same_pg=True)
def test_self_twice_nat_lb_positive(self):
- """ NAT44ED Self Twice NAT local service load balancing (positive test)
- """
- self.twice_nat_common(lb=True, self_twice_nat=True, same_pg=True,
- client_id=1)
+ """NAT44ED Self Twice NAT local service load balancing (positive test)"""
+ self.twice_nat_common(lb=True, self_twice_nat=True, same_pg=True, client_id=1)
def test_twice_nat_lb(self):
- """ NAT44ED Twice NAT local service load balancing """
+ """NAT44ED Twice NAT local service load balancing"""
self.twice_nat_common(lb=True)
def test_output_feature(self):
- """ NAT44ED interface output feature (in2out postrouting) """
+ """NAT44ED interface output feature (in2out postrouting)"""
self.vapi.nat44_forwarding_enable_disable(enable=1)
self.nat_add_address(self.nat_addr)
self.nat_add_outside_interface(self.pg0)
self.vapi.nat44_ed_add_del_output_interface(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# in2out
pkts = self.create_stream_in(self.pg0, self.pg1)
@@ -1323,24 +1412,31 @@ class TestNAT44ED(VppTestCase):
self.assertEqual(p[ICMP].type, 11) # 11 == time-exceeded
def test_static_with_port_out2(self):
- """ NAT44ED 1:1 NAPT asymmetrical rule """
+ """NAT44ED 1:1 NAPT asymmetrical rule"""
external_port = 80
local_port = 8080
self.vapi.nat44_forwarding_enable_disable(enable=1)
flags = self.config_flags.NAT_IS_OUT2IN_ONLY
- self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- local_port, external_port,
- proto=IP_PROTOS.tcp, flags=flags)
+ self.nat_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ local_port,
+ external_port,
+ proto=IP_PROTOS.tcp,
+ flags=flags,
+ )
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
# from client to service
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=12345, dport=external_port))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=12345, dport=external_port)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1357,9 +1453,12 @@ class TestNAT44ED(VppTestCase):
raise
# ICMP error
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- ICMP(type=11) / capture[0][IP])
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / ICMP(type=11)
+ / capture[0][IP]
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1375,9 +1474,11 @@ class TestNAT44ED(VppTestCase):
raise
# from service back to client
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=local_port, dport=12345))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=local_port, dport=12345)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1394,9 +1495,12 @@ class TestNAT44ED(VppTestCase):
raise
# ICMP error
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- ICMP(type=11) / capture[0][IP])
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / ICMP(type=11)
+ / capture[0][IP]
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1412,9 +1516,11 @@ class TestNAT44ED(VppTestCase):
raise
# from client to server (no translation)
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) /
- TCP(sport=12346, dport=local_port))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4)
+ / TCP(sport=12346, dport=local_port)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1431,9 +1537,11 @@ class TestNAT44ED(VppTestCase):
raise
# from service back to client (no translation)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=local_port, dport=12346))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=local_port, dport=12346)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1450,21 +1558,17 @@ class TestNAT44ED(VppTestCase):
raise
def test_static_lb(self):
- """ NAT44ED local service load balancing """
+ """NAT44ED local service load balancing"""
external_addr_n = self.nat_addr
external_port = 80
local_port = 8080
server1 = self.pg0.remote_hosts[0]
server2 = self.pg0.remote_hosts[1]
- locals = [{'addr': server1.ip4,
- 'port': local_port,
- 'probability': 70,
- 'vrf_id': 0},
- {'addr': server2.ip4,
- 'port': local_port,
- 'probability': 30,
- 'vrf_id': 0}]
+ locals = [
+ {"addr": server1.ip4, "port": local_port, "probability": 70, "vrf_id": 0},
+ {"addr": server2.ip4, "port": local_port, "probability": 30, "vrf_id": 0},
+ ]
self.nat_add_address(self.nat_addr)
self.vapi.nat44_add_del_lb_static_mapping(
@@ -1473,19 +1577,22 @@ class TestNAT44ED(VppTestCase):
external_port=external_port,
protocol=IP_PROTOS.tcp,
local_num=len(locals),
- locals=locals)
+ locals=locals,
+ )
flags = self.config_flags.NAT_IS_INSIDE
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# from client to service
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=12345, dport=external_port))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=12345, dport=external_port)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1507,9 +1614,11 @@ class TestNAT44ED(VppTestCase):
raise
# from service back to client
- p = (Ether(src=server.mac, dst=self.pg0.local_mac) /
- IP(src=server.ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=local_port, dport=12345))
+ p = (
+ Ether(src=server.mac, dst=self.pg0.local_mac)
+ / IP(src=server.ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=local_port, dport=12345)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1527,56 +1636,59 @@ class TestNAT44ED(VppTestCase):
sessions = self.vapi.nat44_user_session_dump(server.ip4, 0)
self.assertEqual(len(sessions), 1)
- self.assertTrue(sessions[0].flags &
- self.config_flags.NAT_IS_EXT_HOST_VALID)
+ self.assertTrue(sessions[0].flags & self.config_flags.NAT_IS_EXT_HOST_VALID)
self.vapi.nat44_del_session(
address=sessions[0].inside_ip_address,
port=sessions[0].inside_port,
protocol=sessions[0].protocol,
- flags=(self.config_flags.NAT_IS_INSIDE |
- self.config_flags.NAT_IS_EXT_HOST_VALID),
+ flags=(
+ self.config_flags.NAT_IS_INSIDE
+ | self.config_flags.NAT_IS_EXT_HOST_VALID
+ ),
ext_host_address=sessions[0].ext_host_address,
- ext_host_port=sessions[0].ext_host_port)
+ ext_host_port=sessions[0].ext_host_port,
+ )
sessions = self.vapi.nat44_user_session_dump(server.ip4, 0)
self.assertEqual(len(sessions), 0)
def test_static_lb_2(self):
- """ NAT44ED local service load balancing (asymmetrical rule) """
+ """NAT44ED local service load balancing (asymmetrical rule)"""
external_addr = self.nat_addr
external_port = 80
local_port = 8080
server1 = self.pg0.remote_hosts[0]
server2 = self.pg0.remote_hosts[1]
- locals = [{'addr': server1.ip4,
- 'port': local_port,
- 'probability': 70,
- 'vrf_id': 0},
- {'addr': server2.ip4,
- 'port': local_port,
- 'probability': 30,
- 'vrf_id': 0}]
+ locals = [
+ {"addr": server1.ip4, "port": local_port, "probability": 70, "vrf_id": 0},
+ {"addr": server2.ip4, "port": local_port, "probability": 30, "vrf_id": 0},
+ ]
self.vapi.nat44_forwarding_enable_disable(enable=1)
flags = self.config_flags.NAT_IS_OUT2IN_ONLY
- self.vapi.nat44_add_del_lb_static_mapping(is_add=1, flags=flags,
- external_addr=external_addr,
- external_port=external_port,
- protocol=IP_PROTOS.tcp,
- local_num=len(locals),
- locals=locals)
+ self.vapi.nat44_add_del_lb_static_mapping(
+ is_add=1,
+ flags=flags,
+ external_addr=external_addr,
+ external_port=external_port,
+ protocol=IP_PROTOS.tcp,
+ local_num=len(locals),
+ locals=locals,
+ )
flags = self.config_flags.NAT_IS_INSIDE
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# from client to service
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=12345, dport=external_port))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=12345, dport=external_port)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1598,9 +1710,11 @@ class TestNAT44ED(VppTestCase):
raise
# from service back to client
- p = (Ether(src=server.mac, dst=self.pg0.local_mac) /
- IP(src=server.ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=local_port, dport=12345))
+ p = (
+ Ether(src=server.mac, dst=self.pg0.local_mac)
+ / IP(src=server.ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=local_port, dport=12345)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1617,9 +1731,11 @@ class TestNAT44ED(VppTestCase):
raise
# from client to server (no translation)
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=server1.ip4) /
- TCP(sport=12346, dport=local_port))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=server1.ip4)
+ / TCP(sport=12346, dport=local_port)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1637,9 +1753,11 @@ class TestNAT44ED(VppTestCase):
raise
# from service back to client (no translation)
- p = (Ether(src=server1.mac, dst=self.pg0.local_mac) /
- IP(src=server1.ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=local_port, dport=12346))
+ p = (
+ Ether(src=server1.mac, dst=self.pg0.local_mac)
+ / IP(src=server1.ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=local_port, dport=12346)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1656,41 +1774,41 @@ class TestNAT44ED(VppTestCase):
raise
def test_lb_affinity(self):
- """ NAT44ED local service load balancing affinity """
+ """NAT44ED local service load balancing affinity"""
external_addr = self.nat_addr
external_port = 80
local_port = 8080
server1 = self.pg0.remote_hosts[0]
server2 = self.pg0.remote_hosts[1]
- locals = [{'addr': server1.ip4,
- 'port': local_port,
- 'probability': 50,
- 'vrf_id': 0},
- {'addr': server2.ip4,
- 'port': local_port,
- 'probability': 50,
- 'vrf_id': 0}]
+ locals = [
+ {"addr": server1.ip4, "port": local_port, "probability": 50, "vrf_id": 0},
+ {"addr": server2.ip4, "port": local_port, "probability": 50, "vrf_id": 0},
+ ]
self.nat_add_address(self.nat_addr)
- self.vapi.nat44_add_del_lb_static_mapping(is_add=1,
- external_addr=external_addr,
- external_port=external_port,
- protocol=IP_PROTOS.tcp,
- affinity=10800,
- local_num=len(locals),
- locals=locals)
+ self.vapi.nat44_add_del_lb_static_mapping(
+ is_add=1,
+ external_addr=external_addr,
+ external_port=external_port,
+ protocol=IP_PROTOS.tcp,
+ affinity=10800,
+ local_num=len(locals),
+ locals=locals,
+ )
flags = self.config_flags.NAT_IS_INSIDE
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=1025, dport=external_port))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=1025, dport=external_port)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1699,22 +1817,26 @@ class TestNAT44ED(VppTestCase):
sessions = self.vapi.nat44_user_session_dump(backend, 0)
self.assertEqual(len(sessions), 1)
- self.assertTrue(sessions[0].flags &
- self.config_flags.NAT_IS_EXT_HOST_VALID)
+ self.assertTrue(sessions[0].flags & self.config_flags.NAT_IS_EXT_HOST_VALID)
self.vapi.nat44_del_session(
address=sessions[0].inside_ip_address,
port=sessions[0].inside_port,
protocol=sessions[0].protocol,
- flags=(self.config_flags.NAT_IS_INSIDE |
- self.config_flags.NAT_IS_EXT_HOST_VALID),
+ flags=(
+ self.config_flags.NAT_IS_INSIDE
+ | self.config_flags.NAT_IS_EXT_HOST_VALID
+ ),
ext_host_address=sessions[0].ext_host_address,
- ext_host_port=sessions[0].ext_host_port)
+ ext_host_port=sessions[0].ext_host_port,
+ )
pkts = []
for port in range(1030, 1100):
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=port, dport=external_port))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=port, dport=external_port)
+ )
pkts.append(p)
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -1724,31 +1846,39 @@ class TestNAT44ED(VppTestCase):
self.assertEqual(p[IP].dst, backend)
def test_multiple_vrf_1(self):
- """ Multiple VRF - both client & service in VRF1 """
+ """Multiple VRF - both client & service in VRF1"""
- external_addr = '1.2.3.4'
+ external_addr = "1.2.3.4"
external_port = 80
local_port = 8080
port = 0
flags = self.config_flags.NAT_IS_INSIDE
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg5.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg5.sw_if_index, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg5.sw_if_index,
- is_add=1, flags=flags)
+ sw_if_index=self.pg5.sw_if_index, is_add=1, flags=flags
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg6.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg6.sw_if_index, is_add=1
+ )
flags = self.config_flags.NAT_IS_OUT2IN_ONLY
- self.nat_add_static_mapping(self.pg5.remote_ip4, external_addr,
- local_port, external_port, vrf_id=1,
- proto=IP_PROTOS.tcp, flags=flags)
+ self.nat_add_static_mapping(
+ self.pg5.remote_ip4,
+ external_addr,
+ local_port,
+ external_port,
+ vrf_id=1,
+ proto=IP_PROTOS.tcp,
+ flags=flags,
+ )
- p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) /
- IP(src=self.pg6.remote_ip4, dst=external_addr) /
- TCP(sport=12345, dport=external_port))
+ p = (
+ Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac)
+ / IP(src=self.pg6.remote_ip4, dst=external_addr)
+ / TCP(sport=12345, dport=external_port)
+ )
self.pg6.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1764,9 +1894,11 @@ class TestNAT44ED(VppTestCase):
self.logger.error(ppp("Unexpected or invalid packet:", p))
raise
- p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) /
- IP(src=self.pg5.remote_ip4, dst=self.pg6.remote_ip4) /
- TCP(sport=local_port, dport=12345))
+ p = (
+ Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac)
+ / IP(src=self.pg5.remote_ip4, dst=self.pg6.remote_ip4)
+ / TCP(sport=local_port, dport=12345)
+ )
self.pg5.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1783,9 +1915,9 @@ class TestNAT44ED(VppTestCase):
raise
def test_multiple_vrf_2(self):
- """ Multiple VRF - dynamic NAT from VRF1 to VRF0 (output-feature) """
+ """Multiple VRF - dynamic NAT from VRF1 to VRF0 (output-feature)"""
- external_addr = '1.2.3.4'
+ external_addr = "1.2.3.4"
external_port = 80
local_port = 8080
port = 0
@@ -1793,22 +1925,30 @@ class TestNAT44ED(VppTestCase):
self.nat_add_address(self.nat_addr)
flags = self.config_flags.NAT_IS_INSIDE
self.vapi.nat44_ed_add_del_output_interface(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg5.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg5.sw_if_index, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg5.sw_if_index,
- is_add=1, flags=flags)
+ sw_if_index=self.pg5.sw_if_index, is_add=1, flags=flags
+ )
flags = self.config_flags.NAT_IS_OUT2IN_ONLY
- self.nat_add_static_mapping(self.pg5.remote_ip4, external_addr,
- local_port, external_port, vrf_id=1,
- proto=IP_PROTOS.tcp, flags=flags)
+ self.nat_add_static_mapping(
+ self.pg5.remote_ip4,
+ external_addr,
+ local_port,
+ external_port,
+ vrf_id=1,
+ proto=IP_PROTOS.tcp,
+ flags=flags,
+ )
- p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) /
- IP(src=self.pg5.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=2345, dport=22))
+ p = (
+ Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac)
+ / IP(src=self.pg5.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=2345, dport=22)
+ )
self.pg5.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1824,9 +1964,11 @@ class TestNAT44ED(VppTestCase):
self.logger.error(ppp("Unexpected or invalid packet:", p))
raise
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=22, dport=port))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=22, dport=port)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1843,23 +1985,23 @@ class TestNAT44ED(VppTestCase):
raise
def test_multiple_vrf_3(self):
- """ Multiple VRF - client in VRF1, service in VRF0 """
+ """Multiple VRF - client in VRF1, service in VRF0"""
- external_addr = '1.2.3.4'
+ external_addr = "1.2.3.4"
external_port = 80
local_port = 8080
port = 0
flags = self.config_flags.NAT_IS_INSIDE
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1, flags=flags)
+ sw_if_index=self.pg0.sw_if_index, is_add=1, flags=flags
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg6.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg6.sw_if_index, is_add=1
+ )
flags = self.config_flags.NAT_IS_OUT2IN_ONLY
self.nat_add_static_mapping(
self.pg0.remote_ip4,
@@ -1868,13 +2010,15 @@ class TestNAT44ED(VppTestCase):
vrf_id=0,
external_port=external_port,
proto=IP_PROTOS.tcp,
- flags=flags
+ flags=flags,
)
# from client VRF1 to service VRF0
- p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) /
- IP(src=self.pg6.remote_ip4, dst=self.pg0.local_ip4) /
- TCP(sport=12346, dport=external_port))
+ p = (
+ Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac)
+ / IP(src=self.pg6.remote_ip4, dst=self.pg0.local_ip4)
+ / TCP(sport=12346, dport=external_port)
+ )
self.pg6.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1891,9 +2035,11 @@ class TestNAT44ED(VppTestCase):
raise
# from service VRF0 back to client VRF1
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) /
- TCP(sport=local_port, dport=12346))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4)
+ / TCP(sport=local_port, dport=12346)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1910,35 +2056,43 @@ class TestNAT44ED(VppTestCase):
raise
def test_multiple_vrf_4(self):
- """ Multiple VRF - client in VRF0, service in VRF1 """
+ """Multiple VRF - client in VRF0, service in VRF1"""
- external_addr = '1.2.3.4'
+ external_addr = "1.2.3.4"
external_port = 80
local_port = 8080
port = 0
flags = self.config_flags.NAT_IS_INSIDE
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1, flags=flags)
+ sw_if_index=self.pg0.sw_if_index, is_add=1, flags=flags
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg5.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg5.sw_if_index, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg5.sw_if_index,
- is_add=1, flags=flags)
+ sw_if_index=self.pg5.sw_if_index, is_add=1, flags=flags
+ )
flags = self.config_flags.NAT_IS_OUT2IN_ONLY
- self.nat_add_static_mapping(self.pg5.remote_ip4, external_addr,
- local_port, external_port, vrf_id=1,
- proto=IP_PROTOS.tcp, flags=flags)
+ self.nat_add_static_mapping(
+ self.pg5.remote_ip4,
+ external_addr,
+ local_port,
+ external_port,
+ vrf_id=1,
+ proto=IP_PROTOS.tcp,
+ flags=flags,
+ )
# from client VRF0 to service VRF1
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=external_addr) /
- TCP(sport=12347, dport=external_port))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=external_addr)
+ / TCP(sport=12347, dport=external_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1955,9 +2109,11 @@ class TestNAT44ED(VppTestCase):
raise
# from service VRF1 back to client VRF0
- p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) /
- IP(src=self.pg5.remote_ip4, dst=self.pg0.remote_ip4) /
- TCP(sport=local_port, dport=12347))
+ p = (
+ Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac)
+ / IP(src=self.pg5.remote_ip4, dst=self.pg0.remote_ip4)
+ / TCP(sport=local_port, dport=12347)
+ )
self.pg5.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1974,9 +2130,9 @@ class TestNAT44ED(VppTestCase):
raise
def test_multiple_vrf_5(self):
- """ Multiple VRF - forwarding - no translation """
+ """Multiple VRF - forwarding - no translation"""
- external_addr = '1.2.3.4'
+ external_addr = "1.2.3.4"
external_port = 80
local_port = 8080
port = 0
@@ -1984,24 +2140,30 @@ class TestNAT44ED(VppTestCase):
self.vapi.nat44_forwarding_enable_disable(enable=1)
flags = self.config_flags.NAT_IS_INSIDE
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1, flags=flags)
+ sw_if_index=self.pg0.sw_if_index, is_add=1, flags=flags
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg5.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg5.sw_if_index, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg5.sw_if_index,
- is_add=1, flags=flags)
+ sw_if_index=self.pg5.sw_if_index, is_add=1, flags=flags
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg6.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg6.sw_if_index, is_add=1
+ )
flags = self.config_flags.NAT_IS_OUT2IN_ONLY
- self.nat_add_static_mapping(self.pg5.remote_ip4, external_addr,
- local_port, external_port, vrf_id=1,
- proto=IP_PROTOS.tcp, flags=flags)
+ self.nat_add_static_mapping(
+ self.pg5.remote_ip4,
+ external_addr,
+ local_port,
+ external_port,
+ vrf_id=1,
+ proto=IP_PROTOS.tcp,
+ flags=flags,
+ )
self.nat_add_static_mapping(
self.pg0.remote_ip4,
external_sw_if_index=self.pg0.sw_if_index,
@@ -2009,13 +2171,15 @@ class TestNAT44ED(VppTestCase):
vrf_id=0,
external_port=external_port,
proto=IP_PROTOS.tcp,
- flags=flags
+ flags=flags,
)
# from client to server (both VRF1, no translation)
- p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) /
- IP(src=self.pg6.remote_ip4, dst=self.pg5.remote_ip4) /
- TCP(sport=12348, dport=local_port))
+ p = (
+ Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac)
+ / IP(src=self.pg6.remote_ip4, dst=self.pg5.remote_ip4)
+ / TCP(sport=12348, dport=local_port)
+ )
self.pg6.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2032,9 +2196,11 @@ class TestNAT44ED(VppTestCase):
raise
# from server back to client (both VRF1, no translation)
- p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) /
- IP(src=self.pg5.remote_ip4, dst=self.pg6.remote_ip4) /
- TCP(sport=local_port, dport=12348))
+ p = (
+ Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac)
+ / IP(src=self.pg5.remote_ip4, dst=self.pg6.remote_ip4)
+ / TCP(sport=local_port, dport=12348)
+ )
self.pg5.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2051,9 +2217,11 @@ class TestNAT44ED(VppTestCase):
raise
# from client VRF1 to server VRF0 (no translation)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) /
- TCP(sport=local_port, dport=12349))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4)
+ / TCP(sport=local_port, dport=12349)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2070,9 +2238,11 @@ class TestNAT44ED(VppTestCase):
raise
# from server VRF0 back to client VRF1 (no translation)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4) /
- TCP(sport=local_port, dport=12349))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg6.remote_ip4)
+ / TCP(sport=local_port, dport=12349)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2089,9 +2259,11 @@ class TestNAT44ED(VppTestCase):
raise
# from client VRF0 to server VRF1 (no translation)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg5.remote_ip4) /
- TCP(sport=12344, dport=local_port))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg5.remote_ip4)
+ / TCP(sport=12344, dport=local_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2108,9 +2280,11 @@ class TestNAT44ED(VppTestCase):
raise
# from server VRF1 back to client VRF0 (no translation)
- p = (Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac) /
- IP(src=self.pg5.remote_ip4, dst=self.pg0.remote_ip4) /
- TCP(sport=local_port, dport=12344))
+ p = (
+ Ether(src=self.pg5.remote_mac, dst=self.pg5.local_mac)
+ / IP(src=self.pg5.remote_ip4, dst=self.pg0.remote_ip4)
+ / TCP(sport=local_port, dport=12344)
+ )
self.pg5.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2127,7 +2301,7 @@ class TestNAT44ED(VppTestCase):
raise
def test_outside_address_distribution(self):
- """ Outside address distribution based on source address """
+ """Outside address distribution based on source address"""
x = 100
nat_addresses = []
@@ -2142,7 +2316,10 @@ class TestNAT44ED(VppTestCase):
self.vapi.nat44_add_del_address_range(
first_ip_address=nat_addresses[0],
last_ip_address=nat_addresses[-1],
- vrf_id=0xFFFFFFFF, is_add=1, flags=0)
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ flags=0,
+ )
self.pg0.generate_remote_hosts(x)
@@ -2150,11 +2327,12 @@ class TestNAT44ED(VppTestCase):
for i in range(x):
info = self.create_packet_info(self.pg0, self.pg1)
payload = self.info_to_payload(info)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_hosts[i].ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=7000+i, dport=8000+i) /
- Raw(payload))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_hosts[i].ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=7000 + i, dport=8000 + i)
+ / Raw(payload)
+ )
info.data = p
pkts.append(p)
@@ -2172,20 +2350,23 @@ class TestNAT44ED(VppTestCase):
packed = socket.inet_aton(p_sent[IP].src)
numeric = struct.unpack("!L", packed)[0]
numeric = socket.htonl(numeric)
- a = nat_addresses[(numeric-1) % len(nat_addresses)]
+ a = nat_addresses[(numeric - 1) % len(nat_addresses)]
self.assertEqual(
- a, p_recvd[IP].src,
+ a,
+ p_recvd[IP].src,
"Invalid packet (src IP %s translated to %s, but expected %s)"
- % (p_sent[IP].src, p_recvd[IP].src, a))
+ % (p_sent[IP].src, p_recvd[IP].src, a),
+ )
class TestNAT44EDMW(TestNAT44ED):
- """ NAT44ED MW Test Case """
+ """NAT44ED MW Test Case"""
+
vpp_worker_count = 4
max_sessions = 5000
def test_dynamic(self):
- """ NAT44ED dynamic translation test """
+ """NAT44ED dynamic translation test"""
pkt_count = 1500
tcp_port_offset = 20
udp_port_offset = 20
@@ -2196,27 +2377,33 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_outside_interface(self.pg1)
# in2out
- tc1 = self.statistics['/nat44-ed/in2out/slowpath/tcp']
- uc1 = self.statistics['/nat44-ed/in2out/slowpath/udp']
- ic1 = self.statistics['/nat44-ed/in2out/slowpath/icmp']
- dc1 = self.statistics['/nat44-ed/in2out/slowpath/drops']
+ tc1 = self.statistics["/nat44-ed/in2out/slowpath/tcp"]
+ uc1 = self.statistics["/nat44-ed/in2out/slowpath/udp"]
+ ic1 = self.statistics["/nat44-ed/in2out/slowpath/icmp"]
+ dc1 = self.statistics["/nat44-ed/in2out/slowpath/drops"]
i2o_pkts = [[] for x in range(0, self.vpp_worker_count)]
for i in range(pkt_count):
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=tcp_port_offset + i, dport=20))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=tcp_port_offset + i, dport=20)
+ )
i2o_pkts[p[TCP].sport % self.vpp_worker_count].append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP(sport=udp_port_offset + i, dport=20))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=udp_port_offset + i, dport=20)
+ )
i2o_pkts[p[UDP].sport % self.vpp_worker_count].append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- ICMP(id=icmp_id_offset + i, type='echo-request'))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / ICMP(id=icmp_id_offset + i, type="echo-request")
+ )
i2o_pkts[p[ICMP].id % self.vpp_worker_count].append(p)
for i in range(0, self.vpp_worker_count):
@@ -2228,26 +2415,23 @@ class TestNAT44EDMW(TestNAT44ED):
capture = self.pg1.get_capture(pkt_count * 3, timeout=5)
if_idx = self.pg0.sw_if_index
- tc2 = self.statistics['/nat44-ed/in2out/slowpath/tcp']
- uc2 = self.statistics['/nat44-ed/in2out/slowpath/udp']
- ic2 = self.statistics['/nat44-ed/in2out/slowpath/icmp']
- dc2 = self.statistics['/nat44-ed/in2out/slowpath/drops']
-
- self.assertEqual(
- tc2[:, if_idx].sum() - tc1[:, if_idx].sum(), pkt_count)
- self.assertEqual(
- uc2[:, if_idx].sum() - uc1[:, if_idx].sum(), pkt_count)
- self.assertEqual(
- ic2[:, if_idx].sum() - ic1[:, if_idx].sum(), pkt_count)
+ tc2 = self.statistics["/nat44-ed/in2out/slowpath/tcp"]
+ uc2 = self.statistics["/nat44-ed/in2out/slowpath/udp"]
+ ic2 = self.statistics["/nat44-ed/in2out/slowpath/icmp"]
+ dc2 = self.statistics["/nat44-ed/in2out/slowpath/drops"]
+
+ self.assertEqual(tc2[:, if_idx].sum() - tc1[:, if_idx].sum(), pkt_count)
+ self.assertEqual(uc2[:, if_idx].sum() - uc1[:, if_idx].sum(), pkt_count)
+ self.assertEqual(ic2[:, if_idx].sum() - ic1[:, if_idx].sum(), pkt_count)
self.assertEqual(dc2[:, if_idx].sum() - dc1[:, if_idx].sum(), 0)
self.logger.info(self.vapi.cli("show trace"))
# out2in
- tc1 = self.statistics['/nat44-ed/out2in/fastpath/tcp']
- uc1 = self.statistics['/nat44-ed/out2in/fastpath/udp']
- ic1 = self.statistics['/nat44-ed/out2in/fastpath/icmp']
- dc1 = self.statistics['/nat44-ed/out2in/fastpath/drops']
+ tc1 = self.statistics["/nat44-ed/out2in/fastpath/tcp"]
+ uc1 = self.statistics["/nat44-ed/out2in/fastpath/udp"]
+ ic1 = self.statistics["/nat44-ed/out2in/fastpath/icmp"]
+ dc1 = self.statistics["/nat44-ed/out2in/fastpath/drops"]
recvd_tcp_ports = set()
recvd_udp_ports = set()
@@ -2267,19 +2451,25 @@ class TestNAT44EDMW(TestNAT44ED):
o2i_pkts = [[] for x in range(0, self.vpp_worker_count)]
for i in range(pkt_count):
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(dport=choice(recvd_tcp_ports), sport=20))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(dport=choice(recvd_tcp_ports), sport=20)
+ )
o2i_pkts[p[TCP].dport % self.vpp_worker_count].append(p)
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- UDP(dport=choice(recvd_udp_ports), sport=20))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / UDP(dport=choice(recvd_udp_ports), sport=20)
+ )
o2i_pkts[p[UDP].dport % self.vpp_worker_count].append(p)
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- ICMP(id=choice(recvd_icmp_ids), type='echo-reply'))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / ICMP(id=choice(recvd_icmp_ids), type="echo-reply")
+ )
o2i_pkts[p[ICMP].id % self.vpp_worker_count].append(p)
for i in range(0, self.vpp_worker_count):
@@ -2295,41 +2485,50 @@ class TestNAT44EDMW(TestNAT44ED):
self.assertEqual(packet[IP].dst, self.pg0.remote_ip4)
if packet.haslayer(TCP):
self.assert_in_range(
- packet[TCP].dport, tcp_port_offset,
- tcp_port_offset + pkt_count, "dst TCP port")
+ packet[TCP].dport,
+ tcp_port_offset,
+ tcp_port_offset + pkt_count,
+ "dst TCP port",
+ )
elif packet.haslayer(UDP):
self.assert_in_range(
- packet[UDP].dport, udp_port_offset,
- udp_port_offset + pkt_count, "dst UDP port")
+ packet[UDP].dport,
+ udp_port_offset,
+ udp_port_offset + pkt_count,
+ "dst UDP port",
+ )
else:
self.assert_in_range(
- packet[ICMP].id, icmp_id_offset,
- icmp_id_offset + pkt_count, "ICMP id")
+ packet[ICMP].id,
+ icmp_id_offset,
+ icmp_id_offset + pkt_count,
+ "ICMP id",
+ )
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(inside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (inside network):", packet)
+ )
raise
if_idx = self.pg1.sw_if_index
- tc2 = self.statistics['/nat44-ed/out2in/fastpath/tcp']
- uc2 = self.statistics['/nat44-ed/out2in/fastpath/udp']
- ic2 = self.statistics['/nat44-ed/out2in/fastpath/icmp']
- dc2 = self.statistics['/nat44-ed/out2in/fastpath/drops']
-
- self.assertEqual(
- tc2[:, if_idx].sum() - tc1[:, if_idx].sum(), pkt_count)
- self.assertEqual(
- uc2[:, if_idx].sum() - uc1[:, if_idx].sum(), pkt_count)
- self.assertEqual(
- ic2[:, if_idx].sum() - ic1[:, if_idx].sum(), pkt_count)
+ tc2 = self.statistics["/nat44-ed/out2in/fastpath/tcp"]
+ uc2 = self.statistics["/nat44-ed/out2in/fastpath/udp"]
+ ic2 = self.statistics["/nat44-ed/out2in/fastpath/icmp"]
+ dc2 = self.statistics["/nat44-ed/out2in/fastpath/drops"]
+
+ self.assertEqual(tc2[:, if_idx].sum() - tc1[:, if_idx].sum(), pkt_count)
+ self.assertEqual(uc2[:, if_idx].sum() - uc1[:, if_idx].sum(), pkt_count)
+ self.assertEqual(ic2[:, if_idx].sum() - ic1[:, if_idx].sum(), pkt_count)
self.assertEqual(dc2[:, if_idx].sum() - dc1[:, if_idx].sum(), 0)
- sc = self.statistics['/nat44-ed/total-sessions']
- self.assertEqual(sc[:, 0].sum(), len(recvd_tcp_ports) +
- len(recvd_udp_ports) + len(recvd_icmp_ids))
+ sc = self.statistics["/nat44-ed/total-sessions"]
+ self.assertEqual(
+ sc[:, 0].sum(),
+ len(recvd_tcp_ports) + len(recvd_udp_ports) + len(recvd_icmp_ids),
+ )
def test_frag_in_order(self):
- """ NAT44ED translate fragments arriving in order """
+ """NAT44ED translate fragments arriving in order"""
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
@@ -2340,7 +2539,7 @@ class TestNAT44EDMW(TestNAT44ED):
self.frag_in_order(proto=IP_PROTOS.icmp, ignore_port=True)
def test_frag_in_order_do_not_translate(self):
- """ NAT44ED don't translate fragments arriving in order """
+ """NAT44ED don't translate fragments arriving in order"""
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
@@ -2350,7 +2549,7 @@ class TestNAT44EDMW(TestNAT44ED):
self.frag_in_order(proto=IP_PROTOS.tcp, dont_translate=True)
def test_frag_out_of_order(self):
- """ NAT44ED translate fragments arriving out of order """
+ """NAT44ED translate fragments arriving out of order"""
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
@@ -2361,7 +2560,7 @@ class TestNAT44EDMW(TestNAT44ED):
self.frag_out_of_order(proto=IP_PROTOS.icmp, ignore_port=True)
def test_frag_in_order_in_plus_out(self):
- """ NAT44ED in+out interface fragments in order """
+ """NAT44ED in+out interface fragments in order"""
in_port = self.random_port()
out_port = self.random_port()
@@ -2373,39 +2572,29 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_outside_interface(self.pg1)
# add static mappings for server
- self.nat_add_static_mapping(self.server_addr,
- self.nat_addr,
- in_port,
- out_port,
- proto=IP_PROTOS.tcp)
- self.nat_add_static_mapping(self.server_addr,
- self.nat_addr,
- in_port,
- out_port,
- proto=IP_PROTOS.udp)
- self.nat_add_static_mapping(self.server_addr,
- self.nat_addr,
- proto=IP_PROTOS.icmp)
+ self.nat_add_static_mapping(
+ self.server_addr, self.nat_addr, in_port, out_port, proto=IP_PROTOS.tcp
+ )
+ self.nat_add_static_mapping(
+ self.server_addr, self.nat_addr, in_port, out_port, proto=IP_PROTOS.udp
+ )
+ self.nat_add_static_mapping(
+ self.server_addr, self.nat_addr, proto=IP_PROTOS.icmp
+ )
# run tests for each protocol
- self.frag_in_order_in_plus_out(self.server_addr,
- self.nat_addr,
- in_port,
- out_port,
- IP_PROTOS.tcp)
- self.frag_in_order_in_plus_out(self.server_addr,
- self.nat_addr,
- in_port,
- out_port,
- IP_PROTOS.udp)
- self.frag_in_order_in_plus_out(self.server_addr,
- self.nat_addr,
- in_port,
- out_port,
- IP_PROTOS.icmp)
+ self.frag_in_order_in_plus_out(
+ self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.tcp
+ )
+ self.frag_in_order_in_plus_out(
+ self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.udp
+ )
+ self.frag_in_order_in_plus_out(
+ self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.icmp
+ )
def test_frag_out_of_order_in_plus_out(self):
- """ NAT44ED in+out interface fragments out of order """
+ """NAT44ED in+out interface fragments out of order"""
in_port = self.random_port()
out_port = self.random_port()
@@ -2417,39 +2606,29 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_outside_interface(self.pg1)
# add static mappings for server
- self.nat_add_static_mapping(self.server_addr,
- self.nat_addr,
- in_port,
- out_port,
- proto=IP_PROTOS.tcp)
- self.nat_add_static_mapping(self.server_addr,
- self.nat_addr,
- in_port,
- out_port,
- proto=IP_PROTOS.udp)
- self.nat_add_static_mapping(self.server_addr,
- self.nat_addr,
- proto=IP_PROTOS.icmp)
+ self.nat_add_static_mapping(
+ self.server_addr, self.nat_addr, in_port, out_port, proto=IP_PROTOS.tcp
+ )
+ self.nat_add_static_mapping(
+ self.server_addr, self.nat_addr, in_port, out_port, proto=IP_PROTOS.udp
+ )
+ self.nat_add_static_mapping(
+ self.server_addr, self.nat_addr, proto=IP_PROTOS.icmp
+ )
# run tests for each protocol
- self.frag_out_of_order_in_plus_out(self.server_addr,
- self.nat_addr,
- in_port,
- out_port,
- IP_PROTOS.tcp)
- self.frag_out_of_order_in_plus_out(self.server_addr,
- self.nat_addr,
- in_port,
- out_port,
- IP_PROTOS.udp)
- self.frag_out_of_order_in_plus_out(self.server_addr,
- self.nat_addr,
- in_port,
- out_port,
- IP_PROTOS.icmp)
+ self.frag_out_of_order_in_plus_out(
+ self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.tcp
+ )
+ self.frag_out_of_order_in_plus_out(
+ self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.udp
+ )
+ self.frag_out_of_order_in_plus_out(
+ self.server_addr, self.nat_addr, in_port, out_port, IP_PROTOS.icmp
+ )
def test_reass_hairpinning(self):
- """ NAT44ED fragments hairpinning """
+ """NAT44ED fragments hairpinning"""
server_addr = self.pg0.remote_hosts[1].ip4
@@ -2462,26 +2641,49 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_outside_interface(self.pg1)
# add static mapping for server
- self.nat_add_static_mapping(server_addr, self.nat_addr,
- server_in_port, server_out_port,
- proto=IP_PROTOS.tcp)
- self.nat_add_static_mapping(server_addr, self.nat_addr,
- server_in_port, server_out_port,
- proto=IP_PROTOS.udp)
+ self.nat_add_static_mapping(
+ server_addr,
+ self.nat_addr,
+ server_in_port,
+ server_out_port,
+ proto=IP_PROTOS.tcp,
+ )
+ self.nat_add_static_mapping(
+ server_addr,
+ self.nat_addr,
+ server_in_port,
+ server_out_port,
+ proto=IP_PROTOS.udp,
+ )
self.nat_add_static_mapping(server_addr, self.nat_addr)
- self.reass_hairpinning(server_addr, server_in_port, server_out_port,
- host_in_port, proto=IP_PROTOS.tcp,
- ignore_port=True)
- self.reass_hairpinning(server_addr, server_in_port, server_out_port,
- host_in_port, proto=IP_PROTOS.udp,
- ignore_port=True)
- self.reass_hairpinning(server_addr, server_in_port, server_out_port,
- host_in_port, proto=IP_PROTOS.icmp,
- ignore_port=True)
+ self.reass_hairpinning(
+ server_addr,
+ server_in_port,
+ server_out_port,
+ host_in_port,
+ proto=IP_PROTOS.tcp,
+ ignore_port=True,
+ )
+ self.reass_hairpinning(
+ server_addr,
+ server_in_port,
+ server_out_port,
+ host_in_port,
+ proto=IP_PROTOS.udp,
+ ignore_port=True,
+ )
+ self.reass_hairpinning(
+ server_addr,
+ server_in_port,
+ server_out_port,
+ host_in_port,
+ proto=IP_PROTOS.icmp,
+ ignore_port=True,
+ )
def test_session_limit_per_vrf(self):
- """ NAT44ED per vrf session limit """
+ """NAT44ED per vrf session limit"""
inside = self.pg0
inside_vrf10 = self.pg2
@@ -2520,27 +2722,29 @@ class TestNAT44EDMW(TestNAT44ED):
capture = outside.get_capture(len(stream))
def test_show_max_translations(self):
- """ NAT44ED API test - max translations per thread """
+ """NAT44ED API test - max translations per thread"""
config = self.vapi.nat44_show_running_config()
- self.assertEqual(self.max_sessions,
- config.sessions)
+ self.assertEqual(self.max_sessions, config.sessions)
def test_lru_cleanup(self):
- """ NAT44ED LRU cleanup algorithm """
+ """NAT44ED LRU cleanup algorithm"""
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
self.vapi.nat_set_timeouts(
- udp=1, tcp_established=7440, tcp_transitory=30, icmp=1)
+ udp=1, tcp_established=7440, tcp_transitory=30, icmp=1
+ )
tcp_port_out = self.init_tcp_session(self.pg0, self.pg1, 2000, 80)
pkts = []
for i in range(0, self.max_sessions - 1):
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64) /
- UDP(sport=7000+i, dport=80))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64)
+ / UDP(sport=7000 + i, dport=80)
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
@@ -2551,9 +2755,11 @@ class TestNAT44EDMW(TestNAT44ED):
pkts = []
for i in range(0, self.max_sessions - 1):
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64) /
- ICMP(id=8000+i, type='echo-request'))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64)
+ / ICMP(id=8000 + i, type="echo-request")
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
@@ -2562,79 +2768,89 @@ class TestNAT44EDMW(TestNAT44ED):
self.pg1.get_capture(len(pkts))
def test_session_rst_timeout(self):
- """ NAT44ED session RST timeouts """
+ """NAT44ED session RST timeouts"""
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
- self.vapi.nat_set_timeouts(udp=300, tcp_established=7440,
- tcp_transitory=5, icmp=60)
+ self.vapi.nat_set_timeouts(
+ udp=300, tcp_established=7440, tcp_transitory=5, icmp=60
+ )
- self.init_tcp_session(self.pg0, self.pg1, self.tcp_port_in,
- self.tcp_external_port)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="R"))
+ self.init_tcp_session(
+ self.pg0, self.pg1, self.tcp_port_in, self.tcp_external_port
+ )
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="R")
+ )
self.send_and_expect(self.pg0, p, self.pg1)
self.virtual_sleep(6)
# The session is already closed
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="P"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="P")
+ )
self.send_and_assert_no_replies(self.pg0, p, self.pg1)
# The session can be re-opened
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="S"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="S")
+ )
self.send_and_expect(self.pg0, p, self.pg1)
def test_session_rst_established_timeout(self):
- """ NAT44ED session RST timeouts """
+ """NAT44ED session RST timeouts"""
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
- self.vapi.nat_set_timeouts(udp=300, tcp_established=7440,
- tcp_transitory=5, icmp=60)
+ self.vapi.nat_set_timeouts(
+ udp=300, tcp_established=7440, tcp_transitory=5, icmp=60
+ )
- self.init_tcp_session(self.pg0, self.pg1, self.tcp_port_in,
- self.tcp_external_port)
+ self.init_tcp_session(
+ self.pg0, self.pg1, self.tcp_port_in, self.tcp_external_port
+ )
# Wait at least the transitory time, the session is in established
# state anyway. RST followed by a data packet should move it to
# transitory state.
self.virtual_sleep(6)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="R"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="R")
+ )
self.send_and_expect(self.pg0, p, self.pg1)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="P"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="P")
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# State is transitory, session should be closed after 6 seconds
self.virtual_sleep(6)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="P"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="P")
+ )
self.send_and_assert_no_replies(self.pg0, p, self.pg1)
def test_dynamic_out_of_ports(self):
- """ NAT44ED dynamic translation test: out of ports """
+ """NAT44ED dynamic translation test: out of ports"""
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
@@ -2643,60 +2859,71 @@ class TestNAT44EDMW(TestNAT44ED):
pkts = self.create_stream_in(self.pg0, self.pg1)
self.send_and_assert_no_replies(
- self.pg0, pkts, msg="i2o pkts",
- stats_diff=self.no_diff | {
+ self.pg0,
+ pkts,
+ msg="i2o pkts",
+ stats_diff=self.no_diff
+ | {
"err": {
- '/err/nat44-ed-in2out-slowpath/out of ports': len(pkts),
+ "/err/nat44-ed-in2out-slowpath/out of ports": len(pkts),
},
self.pg0.sw_if_index: {
- '/nat44-ed/in2out/slowpath/drops': len(pkts),
+ "/nat44-ed/in2out/slowpath/drops": len(pkts),
},
- }
+ },
)
# in2out after NAT addresses added
self.nat_add_address(self.nat_addr)
- tcpn, udpn, icmpn = (sum(x) for x in
- zip(*((TCP in p, UDP in p, ICMP in p)
- for p in pkts)))
+ tcpn, udpn, icmpn = (
+ sum(x) for x in zip(*((TCP in p, UDP in p, ICMP in p) for p in pkts))
+ )
self.send_and_expect(
- self.pg0, pkts, self.pg1, msg="i2o pkts",
- stats_diff=self.no_diff | {
+ self.pg0,
+ pkts,
+ self.pg1,
+ msg="i2o pkts",
+ stats_diff=self.no_diff
+ | {
"err": {
- '/err/nat44-ed-in2out-slowpath/out of ports': 0,
+ "/err/nat44-ed-in2out-slowpath/out of ports": 0,
},
self.pg0.sw_if_index: {
- '/nat44-ed/in2out/slowpath/drops': 0,
- '/nat44-ed/in2out/slowpath/tcp': tcpn,
- '/nat44-ed/in2out/slowpath/udp': udpn,
- '/nat44-ed/in2out/slowpath/icmp': icmpn,
+ "/nat44-ed/in2out/slowpath/drops": 0,
+ "/nat44-ed/in2out/slowpath/tcp": tcpn,
+ "/nat44-ed/in2out/slowpath/udp": udpn,
+ "/nat44-ed/in2out/slowpath/icmp": icmpn,
},
- }
+ },
)
def test_unknown_proto(self):
- """ NAT44ED translate packet with unknown protocol """
+ """NAT44ED translate packet with unknown protocol"""
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
# in2out
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=20))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=20)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
p = self.pg1.get_capture(1)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- GRE() /
- IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / GRE()
+ / IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2712,11 +2939,13 @@ class TestNAT44EDMW(TestNAT44ED):
raise
# out2in
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- GRE() /
- IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / GRE()
+ / IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2732,7 +2961,7 @@ class TestNAT44EDMW(TestNAT44ED):
raise
def test_hairpinning_unknown_proto(self):
- """ NAT44ED translate packet with unknown protocol - hairpinning """
+ """NAT44ED translate packet with unknown protocol - hairpinning"""
host = self.pg0.remote_hosts[0]
server = self.pg0.remote_hosts[1]
host_in_port = 1234
@@ -2747,19 +2976,23 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_static_mapping(server.ip4, server_nat_ip)
# host to server
- p = (Ether(src=host.mac, dst=self.pg0.local_mac) /
- IP(src=host.ip4, dst=server_nat_ip) /
- TCP(sport=host_in_port, dport=server_out_port))
+ p = (
+ Ether(src=host.mac, dst=self.pg0.local_mac)
+ / IP(src=host.ip4, dst=server_nat_ip)
+ / TCP(sport=host_in_port, dport=server_out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
self.pg0.get_capture(1)
- p = (Ether(dst=self.pg0.local_mac, src=host.mac) /
- IP(src=host.ip4, dst=server_nat_ip) /
- GRE() /
- IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=host.mac)
+ / IP(src=host.ip4, dst=server_nat_ip)
+ / GRE()
+ / IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2775,11 +3008,13 @@ class TestNAT44EDMW(TestNAT44ED):
raise
# server to host
- p = (Ether(dst=self.pg0.local_mac, src=server.mac) /
- IP(src=server.ip4, dst=self.nat_addr) /
- GRE() /
- IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=server.mac)
+ / IP(src=server.ip4, dst=self.nat_addr)
+ / GRE()
+ / IP(src=self.pg2.remote_ip4, dst=self.pg2.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2795,8 +3030,8 @@ class TestNAT44EDMW(TestNAT44ED):
raise
def test_output_feature_and_service(self):
- """ NAT44ED interface output feature and services """
- external_addr = '1.2.3.4'
+ """NAT44ED interface output feature and services"""
+ external_addr = "1.2.3.4"
external_port = 80
local_port = 8080
@@ -2804,22 +3039,33 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_address(self.nat_addr)
flags = self.config_flags.NAT_IS_ADDR_ONLY
self.vapi.nat44_add_del_identity_mapping(
- ip_address=self.pg1.remote_ip4, sw_if_index=0xFFFFFFFF,
- flags=flags, is_add=1)
+ ip_address=self.pg1.remote_ip4,
+ sw_if_index=0xFFFFFFFF,
+ flags=flags,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_OUT2IN_ONLY
- self.nat_add_static_mapping(self.pg0.remote_ip4, external_addr,
- local_port, external_port,
- proto=IP_PROTOS.tcp, flags=flags)
+ self.nat_add_static_mapping(
+ self.pg0.remote_ip4,
+ external_addr,
+ local_port,
+ external_port,
+ proto=IP_PROTOS.tcp,
+ flags=flags,
+ )
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg0)
self.vapi.nat44_ed_add_del_output_interface(
- sw_if_index=self.pg1.sw_if_index, is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# from client to service
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=external_addr) /
- TCP(sport=12345, dport=external_port))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=external_addr)
+ / TCP(sport=12345, dport=external_port)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2836,9 +3082,11 @@ class TestNAT44EDMW(TestNAT44ED):
raise
# from service back to client
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=local_port, dport=12345))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=local_port, dport=12345)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2877,26 +3125,34 @@ class TestNAT44EDMW(TestNAT44ED):
self.verify_capture_in(capture, self.pg0)
def test_output_feature_and_service3(self):
- """ NAT44ED interface output feature and DST NAT """
- external_addr = '1.2.3.4'
+ """NAT44ED interface output feature and DST NAT"""
+ external_addr = "1.2.3.4"
external_port = 80
local_port = 8080
self.vapi.nat44_forwarding_enable_disable(enable=1)
self.nat_add_address(self.nat_addr)
flags = self.config_flags.NAT_IS_OUT2IN_ONLY
- self.nat_add_static_mapping(self.pg1.remote_ip4, external_addr,
- local_port, external_port,
- proto=IP_PROTOS.tcp, flags=flags)
+ self.nat_add_static_mapping(
+ self.pg1.remote_ip4,
+ external_addr,
+ local_port,
+ external_port,
+ proto=IP_PROTOS.tcp,
+ flags=flags,
+ )
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg0)
self.vapi.nat44_ed_add_del_output_interface(
- sw_if_index=self.pg1.sw_if_index, is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=external_addr) /
- TCP(sport=12345, dport=external_port))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=external_addr)
+ / TCP(sport=12345, dport=external_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2914,9 +3170,11 @@ class TestNAT44EDMW(TestNAT44ED):
self.logger.error(ppp("Unexpected or invalid packet:", p))
raise
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) /
- TCP(sport=local_port, dport=12345))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4)
+ / TCP(sport=local_port, dport=12345)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2935,17 +3193,15 @@ class TestNAT44EDMW(TestNAT44ED):
raise
def test_self_twice_nat_lb_negative(self):
- """ NAT44ED Self Twice NAT local service load balancing (negative test)
- """
- self.twice_nat_common(lb=True, self_twice_nat=True, same_pg=True,
- client_id=2)
+ """NAT44ED Self Twice NAT local service load balancing (negative test)"""
+ self.twice_nat_common(lb=True, self_twice_nat=True, same_pg=True, client_id=2)
def test_self_twice_nat_negative(self):
- """ NAT44ED Self Twice NAT (negative test) """
+ """NAT44ED Self Twice NAT (negative test)"""
self.twice_nat_common(self_twice_nat=True)
def test_static_lb_multi_clients(self):
- """ NAT44ED local service load balancing - multiple clients"""
+ """NAT44ED local service load balancing - multiple clients"""
external_addr = self.nat_addr
external_port = 80
@@ -2954,39 +3210,39 @@ class TestNAT44EDMW(TestNAT44ED):
server2 = self.pg0.remote_hosts[1]
server3 = self.pg0.remote_hosts[2]
- locals = [{'addr': server1.ip4,
- 'port': local_port,
- 'probability': 90,
- 'vrf_id': 0},
- {'addr': server2.ip4,
- 'port': local_port,
- 'probability': 10,
- 'vrf_id': 0}]
+ locals = [
+ {"addr": server1.ip4, "port": local_port, "probability": 90, "vrf_id": 0},
+ {"addr": server2.ip4, "port": local_port, "probability": 10, "vrf_id": 0},
+ ]
flags = self.config_flags.NAT_IS_INSIDE
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
self.nat_add_address(self.nat_addr)
- self.vapi.nat44_add_del_lb_static_mapping(is_add=1,
- external_addr=external_addr,
- external_port=external_port,
- protocol=IP_PROTOS.tcp,
- local_num=len(locals),
- locals=locals)
+ self.vapi.nat44_add_del_lb_static_mapping(
+ is_add=1,
+ external_addr=external_addr,
+ external_port=external_port,
+ protocol=IP_PROTOS.tcp,
+ local_num=len(locals),
+ locals=locals,
+ )
server1_n = 0
server2_n = 0
clients = ip4_range(self.pg1.remote_ip4, 10, 50)
pkts = []
for client in clients:
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=client, dst=self.nat_addr) /
- TCP(sport=12345, dport=external_port))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=client, dst=self.nat_addr)
+ / TCP(sport=12345, dport=external_port)
+ )
pkts.append(p)
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -3000,10 +3256,10 @@ class TestNAT44EDMW(TestNAT44ED):
self.assertGreaterEqual(server1_n, server2_n)
local = {
- 'addr': server3.ip4,
- 'port': local_port,
- 'probability': 20,
- 'vrf_id': 0
+ "addr": server3.ip4,
+ "port": local_port,
+ "probability": 20,
+ "vrf_id": 0,
}
# add new back-end
@@ -3012,16 +3268,19 @@ class TestNAT44EDMW(TestNAT44ED):
external_addr=external_addr,
external_port=external_port,
local=local,
- protocol=IP_PROTOS.tcp)
+ protocol=IP_PROTOS.tcp,
+ )
server1_n = 0
server2_n = 0
server3_n = 0
clients = ip4_range(self.pg1.remote_ip4, 60, 110)
pkts = []
for client in clients:
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=client, dst=self.nat_addr) /
- TCP(sport=12346, dport=external_port))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=client, dst=self.nat_addr)
+ / TCP(sport=12346, dport=external_port)
+ )
pkts.append(p)
self.assertGreater(len(pkts), 0)
self.pg1.add_stream(pkts)
@@ -3040,10 +3299,10 @@ class TestNAT44EDMW(TestNAT44ED):
self.assertGreater(server3_n, 0)
local = {
- 'addr': server2.ip4,
- 'port': local_port,
- 'probability': 10,
- 'vrf_id': 0
+ "addr": server2.ip4,
+ "port": local_port,
+ "probability": 10,
+ "vrf_id": 0,
}
# remove one back-end
@@ -3052,7 +3311,8 @@ class TestNAT44EDMW(TestNAT44ED):
external_addr=external_addr,
external_port=external_port,
local=local,
- protocol=IP_PROTOS.tcp)
+ protocol=IP_PROTOS.tcp,
+ )
server1_n = 0
server2_n = 0
server3_n = 0
@@ -3075,39 +3335,39 @@ class TestNAT44EDMW(TestNAT44ED):
# setting syslog sender cannot be undone and if it is set, it messes
# with self.send_and_assert_no_replies functionality
def test_zzz_syslog_sess(self):
- """ NAT44ED Test syslog session creation and deletion """
- self.vapi.syslog_set_filter(
- self.syslog_severity.SYSLOG_API_SEVERITY_INFO)
+ """NAT44ED Test syslog session creation and deletion"""
+ self.vapi.syslog_set_filter(self.syslog_severity.SYSLOG_API_SEVERITY_INFO)
self.vapi.syslog_set_sender(self.pg3.local_ip4, self.pg3.remote_ip4)
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(1)
self.tcp_port_out = capture[0][TCP].sport
capture = self.pg3.get_capture(1)
- self.verify_syslog_sess(capture[0][Raw].load, 'SADD')
+ self.verify_syslog_sess(capture[0][Raw].load, "SADD")
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
self.nat_add_address(self.nat_addr, is_add=0)
capture = self.pg3.get_capture(1)
- self.verify_syslog_sess(capture[0][Raw].load, 'SDEL')
+ self.verify_syslog_sess(capture[0][Raw].load, "SDEL")
# put zzz in front of syslog test name so that it runs as a last test
# setting syslog sender cannot be undone and if it is set, it messes
# with self.send_and_assert_no_replies functionality
def test_zzz_syslog_sess_reopen(self):
- """ Syslog events for session reopen """
- self.vapi.syslog_set_filter(
- self.syslog_severity.SYSLOG_API_SEVERITY_INFO)
+ """Syslog events for session reopen"""
+ self.vapi.syslog_set_filter(self.syslog_severity.SYSLOG_API_SEVERITY_INFO)
self.vapi.syslog_set_sender(self.pg3.local_ip4, self.pg3.remote_ip4)
self.nat_add_address(self.nat_addr)
@@ -3115,55 +3375,62 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_outside_interface(self.pg1)
# SYN in2out
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port)
+ )
capture = self.send_and_expect(self.pg0, p, self.pg1)[0]
self.tcp_port_out = capture[0][TCP].sport
capture = self.pg3.get_capture(1)
- self.verify_syslog_sess(capture[0][Raw].load, 'SADD')
+ self.verify_syslog_sess(capture[0][Raw].load, "SADD")
# SYN out2in
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
- flags='SA'))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="SA")
+ )
self.send_and_expect(self.pg1, p, self.pg0)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="A"))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="A")
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# FIN in2out
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="F"))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port, flags="F")
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# FIN out2in
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=self.tcp_external_port, dport=self.tcp_port_out,
- flags="F"))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out, flags="F")
+ )
self.send_and_expect(self.pg1, p, self.pg0)
- self.init_tcp_session(self.pg0, self.pg1, self.tcp_port_in,
- self.tcp_external_port)
+ self.init_tcp_session(
+ self.pg0, self.pg1, self.tcp_port_in, self.tcp_external_port
+ )
# 2 records should be produced - first one del & add
capture = self.pg3.get_capture(2)
- self.verify_syslog_sess(capture[0][Raw].load, 'SDEL')
- self.verify_syslog_sess(capture[1][Raw].load, 'SADD')
+ self.verify_syslog_sess(capture[0][Raw].load, "SDEL")
+ self.verify_syslog_sess(capture[1][Raw].load, "SADD")
def test_twice_nat_interface_addr(self):
- """ NAT44ED Acquire twice NAT addresses from interface """
+ """NAT44ED Acquire twice NAT addresses from interface"""
flags = self.config_flags.NAT_IS_TWICE_NAT
self.vapi.nat44_add_del_interface_addr(
- sw_if_index=self.pg11.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg11.sw_if_index, flags=flags, is_add=1
+ )
# no address in NAT pool
adresses = self.vapi.nat44_address_dump()
@@ -3173,8 +3440,7 @@ class TestNAT44EDMW(TestNAT44ED):
self.pg11.config_ip4()
adresses = self.vapi.nat44_address_dump()
self.assertEqual(1, len(adresses))
- self.assertEqual(str(adresses[0].ip_address),
- self.pg11.local_ip4)
+ self.assertEqual(str(adresses[0].ip_address), self.pg11.local_ip4)
self.assertEqual(adresses[0].flags, flags)
# remove interface address and check NAT address pool
@@ -3183,11 +3449,12 @@ class TestNAT44EDMW(TestNAT44ED):
self.assertEqual(0, len(adresses))
def test_output_feature_stateful_acl(self):
- """ NAT44ED output feature works with stateful ACL """
+ """NAT44ED output feature works with stateful ACL"""
self.nat_add_address(self.nat_addr)
self.vapi.nat44_ed_add_del_output_interface(
- sw_if_index=self.pg1.sw_if_index, is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# First ensure that the NAT is working sans ACL
@@ -3197,14 +3464,16 @@ class TestNAT44EDMW(TestNAT44ED):
# send packets into inside intf, ensure received via outside intf
pkts_in2out = self.create_stream_in(self.pg0, self.pg1)
- capture = self.send_and_expect(self.pg0, pkts_in2out, self.pg1,
- len(pkts_in2out))
+ capture = self.send_and_expect(
+ self.pg0, pkts_in2out, self.pg1, len(pkts_in2out)
+ )
self.verify_capture_out(capture, ignore_port=True)
# send out2in again, with sessions created it should work now
pkts_out2in = self.create_stream_out(self.pg1)
- capture = self.send_and_expect(self.pg1, pkts_out2in, self.pg0,
- len(pkts_out2in))
+ capture = self.send_and_expect(
+ self.pg1, pkts_out2in, self.pg0, len(pkts_out2in)
+ )
self.verify_capture_in(capture, self.pg0)
# Create an ACL blocking everything
@@ -3218,8 +3487,9 @@ class TestNAT44EDMW(TestNAT44ED):
in2out_acl.add_vpp_config()
# apply as input acl on interface and confirm it blocks everything
- acl_if = VppAclInterface(self, sw_if_index=self.pg1.sw_if_index,
- n_input=1, acls=[out2in_acl])
+ acl_if = VppAclInterface(
+ self, sw_if_index=self.pg1.sw_if_index, n_input=1, acls=[out2in_acl]
+ )
acl_if.add_vpp_config()
self.send_and_assert_no_replies(self.pg1, pkts_out2in)
@@ -3227,8 +3497,9 @@ class TestNAT44EDMW(TestNAT44ED):
acl_if.acls = [out2in_acl, in2out_acl]
acl_if.add_vpp_config()
# send in2out to generate ACL state (NAT state was created earlier)
- capture = self.send_and_expect(self.pg0, pkts_in2out, self.pg1,
- len(pkts_in2out))
+ capture = self.send_and_expect(
+ self.pg0, pkts_in2out, self.pg1, len(pkts_in2out)
+ )
self.verify_capture_out(capture, ignore_port=True)
# send out2in again. ACL state exists so it should work now.
@@ -3236,13 +3507,14 @@ class TestNAT44EDMW(TestNAT44ED):
for p in pkts_out2in:
if p.haslayer(TCP) and p[TCP].flags & 0x02:
p[TCP].flags |= 0x10
- capture = self.send_and_expect(self.pg1, pkts_out2in, self.pg0,
- len(pkts_out2in))
+ capture = self.send_and_expect(
+ self.pg1, pkts_out2in, self.pg0, len(pkts_out2in)
+ )
self.verify_capture_in(capture, self.pg0)
self.logger.info(self.vapi.cli("show trace"))
def test_tcp_close(self):
- """ NAT44ED Close TCP session from inside network - output feature """
+ """NAT44ED Close TCP session from inside network - output feature"""
config = self.vapi.nat44_show_running_config()
old_timeouts = config.timeouts
new_transitory = 2
@@ -3250,77 +3522,92 @@ class TestNAT44EDMW(TestNAT44ED):
udp=old_timeouts.udp,
tcp_established=old_timeouts.tcp_established,
icmp=old_timeouts.icmp,
- tcp_transitory=new_transitory)
+ tcp_transitory=new_transitory,
+ )
self.vapi.nat44_forwarding_enable_disable(enable=1)
self.nat_add_address(self.pg1.local_ip4)
- twice_nat_addr = '10.0.1.3'
- service_ip = '192.168.16.150'
+ twice_nat_addr = "10.0.1.3"
+ service_ip = "192.168.16.150"
self.nat_add_address(twice_nat_addr, twice_nat=1)
flags = self.config_flags.NAT_IS_INSIDE
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ed_add_del_output_interface(
- is_add=1,
- sw_if_index=self.pg1.sw_if_index)
-
- flags = (self.config_flags.NAT_IS_OUT2IN_ONLY |
- self.config_flags.NAT_IS_TWICE_NAT)
- self.nat_add_static_mapping(self.pg0.remote_ip4,
- service_ip, 80, 80,
- proto=IP_PROTOS.tcp,
- flags=flags)
+ is_add=1, sw_if_index=self.pg1.sw_if_index
+ )
+
+ flags = (
+ self.config_flags.NAT_IS_OUT2IN_ONLY | self.config_flags.NAT_IS_TWICE_NAT
+ )
+ self.nat_add_static_mapping(
+ self.pg0.remote_ip4, service_ip, 80, 80, proto=IP_PROTOS.tcp, flags=flags
+ )
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
start_sessnum = len(sessions)
# SYN packet out->in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=service_ip) /
- TCP(sport=33898, dport=80, flags="S"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=service_ip)
+ / TCP(sport=33898, dport=80, flags="S")
+ )
capture = self.send_and_expect(self.pg1, p, self.pg0, n_rx=1)
p = capture[0]
tcp_port = p[TCP].sport
# SYN + ACK packet in->out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) /
- TCP(sport=80, dport=tcp_port, flags="SA"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=twice_nat_addr)
+ / TCP(sport=80, dport=tcp_port, flags="SA")
+ )
self.send_and_expect(self.pg0, p, self.pg1, n_rx=1)
# ACK packet out->in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=service_ip) /
- TCP(sport=33898, dport=80, flags="A"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=service_ip)
+ / TCP(sport=33898, dport=80, flags="A")
+ )
self.send_and_expect(self.pg1, p, self.pg0, n_rx=1)
# FIN packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) /
- TCP(sport=80, dport=tcp_port, flags="FA", seq=100, ack=300))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=twice_nat_addr)
+ / TCP(sport=80, dport=tcp_port, flags="FA", seq=100, ack=300)
+ )
self.send_and_expect(self.pg0, p, self.pg1, n_rx=1)
# FIN+ACK packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=service_ip) /
- TCP(sport=33898, dport=80, flags="FA", seq=300, ack=101))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=service_ip)
+ / TCP(sport=33898, dport=80, flags="FA", seq=300, ack=101)
+ )
self.send_and_expect(self.pg1, p, self.pg0, n_rx=1)
# ACK packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=twice_nat_addr) /
- TCP(sport=80, dport=tcp_port, flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=twice_nat_addr)
+ / TCP(sport=80, dport=tcp_port, flags="A", seq=101, ack=301)
+ )
self.send_and_expect(self.pg0, p, self.pg1, n_rx=1)
# session now in transitory timeout, but traffic still flows
# try FIN packet out->in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=service_ip) /
- TCP(sport=33898, dport=80, flags="F"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=service_ip)
+ / TCP(sport=33898, dport=80, flags="F")
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3334,15 +3621,17 @@ class TestNAT44EDMW(TestNAT44ED):
# send FIN+ACK packet out -> in - will cause session to be wiped
# but won't create a new session
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=service_ip) /
- TCP(sport=33898, dport=80, flags="FA", seq=300, ack=101))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=service_ip)
+ / TCP(sport=33898, dport=80, flags="FA", seq=300, ack=101)
+ )
self.send_and_assert_no_replies(self.pg1, p)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - start_sessnum, 0)
def test_tcp_session_close_in(self):
- """ NAT44ED Close TCP session from inside network """
+ """NAT44ED Close TCP session from inside network"""
in_port = self.tcp_port_in
out_port = 10505
@@ -3351,79 +3640,92 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
- self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- in_port, out_port, proto=IP_PROTOS.tcp,
- flags=self.config_flags.NAT_IS_TWICE_NAT)
+ self.nat_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ in_port,
+ out_port,
+ proto=IP_PROTOS.tcp,
+ flags=self.config_flags.NAT_IS_TWICE_NAT,
+ )
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
session_n = len(sessions)
- self.vapi.nat_set_timeouts(udp=300, tcp_established=7440,
- tcp_transitory=2, icmp=5)
+ self.vapi.nat_set_timeouts(
+ udp=300, tcp_established=7440, tcp_transitory=2, icmp=5
+ )
self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port)
# FIN packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="FA", seq=100, ack=300))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="FA", seq=100, ack=300)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
pkts = []
# ACK packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="A", seq=300, ack=101))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="A", seq=300, ack=101)
+ )
pkts.append(p)
# FIN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="FA", seq=300, ack=101))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=101)
+ )
pkts.append(p)
self.send_and_expect(self.pg1, pkts, self.pg0)
# ACK packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - session_n, 1)
# retransmit FIN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="FA", seq=300, ack=101))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=101)
+ )
self.send_and_expect(self.pg1, p, self.pg0)
# retransmit ACK packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
self.virtual_sleep(3)
# retransmit ACK packet in -> out - this will cause session to be wiped
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301)
+ )
self.send_and_assert_no_replies(self.pg0, p)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - session_n, 0)
def test_tcp_session_close_out(self):
- """ NAT44ED Close TCP session from outside network """
+ """NAT44ED Close TCP session from outside network"""
in_port = self.tcp_port_in
out_port = 10505
@@ -3432,33 +3734,41 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
- self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- in_port, out_port, proto=IP_PROTOS.tcp,
- flags=self.config_flags.NAT_IS_TWICE_NAT)
+ self.nat_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ in_port,
+ out_port,
+ proto=IP_PROTOS.tcp,
+ flags=self.config_flags.NAT_IS_TWICE_NAT,
+ )
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
session_n = len(sessions)
- self.vapi.nat_set_timeouts(udp=300, tcp_established=7440,
- tcp_transitory=2, icmp=5)
+ self.vapi.nat_set_timeouts(
+ udp=300, tcp_established=7440, tcp_transitory=2, icmp=5
+ )
_ = self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port)
# FIN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="FA", seq=100, ack=300))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="FA", seq=100, ack=300)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
self.pg0.get_capture(1)
# FIN+ACK packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="FA", seq=300, ack=101))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="FA", seq=300, ack=101)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
@@ -3466,10 +3776,11 @@ class TestNAT44EDMW(TestNAT44ED):
self.pg1.get_capture(1)
# ACK packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="A", seq=101, ack=301)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3479,31 +3790,34 @@ class TestNAT44EDMW(TestNAT44ED):
self.assertEqual(len(sessions) - session_n, 1)
# retransmit FIN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="FA", seq=300, ack=101))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=101)
+ )
self.send_and_expect(self.pg1, p, self.pg0)
# retransmit ACK packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
self.virtual_sleep(3)
# retransmit ACK packet in -> out - this will cause session to be wiped
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301)
+ )
self.send_and_assert_no_replies(self.pg0, p)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - session_n, 0)
def test_tcp_session_close_simultaneous(self):
- """ Simultaneous TCP close from both sides """
+ """Simultaneous TCP close from both sides"""
in_port = self.tcp_port_in
ext_port = 10505
@@ -3511,252 +3825,297 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
- self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- in_port, ext_port, proto=IP_PROTOS.tcp,
- flags=self.config_flags.NAT_IS_TWICE_NAT)
+ self.nat_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ in_port,
+ ext_port,
+ proto=IP_PROTOS.tcp,
+ flags=self.config_flags.NAT_IS_TWICE_NAT,
+ )
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
session_n = len(sessions)
- self.vapi.nat_set_timeouts(udp=300, tcp_established=7440,
- tcp_transitory=2, icmp=5)
+ self.vapi.nat_set_timeouts(
+ udp=300, tcp_established=7440, tcp_transitory=2, icmp=5
+ )
out_port = self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port)
# FIN packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="FA", seq=100, ack=300))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="FA", seq=100, ack=300)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# FIN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="FA", seq=300, ack=100))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=100)
+ )
self.send_and_expect(self.pg1, p, self.pg0)
# ACK packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# ACK packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="A", seq=301, ack=101))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="A", seq=301, ack=101)
+ )
self.send_and_expect(self.pg1, p, self.pg0)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - session_n, 1)
# retransmit FIN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="FA", seq=300, ack=101))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=101)
+ )
self.send_and_expect(self.pg1, p, self.pg0)
# retransmit ACK packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
self.virtual_sleep(3)
# retransmit ACK packet in -> out - this will cause session to be wiped
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301)
+ )
self.pg_send(self.pg0, p)
self.send_and_assert_no_replies(self.pg0, p)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - session_n, 0)
def test_tcp_session_half_reopen_inside(self):
- """ TCP session in FIN/FIN state not reopened by in2out SYN only """
+ """TCP session in FIN/FIN state not reopened by in2out SYN only"""
in_port = self.tcp_port_in
ext_port = 10505
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
- self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- in_port, ext_port, proto=IP_PROTOS.tcp,
- flags=self.config_flags.NAT_IS_TWICE_NAT)
+ self.nat_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ in_port,
+ ext_port,
+ proto=IP_PROTOS.tcp,
+ flags=self.config_flags.NAT_IS_TWICE_NAT,
+ )
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
session_n = len(sessions)
- self.vapi.nat_set_timeouts(udp=300, tcp_established=7440,
- tcp_transitory=2, icmp=5)
+ self.vapi.nat_set_timeouts(
+ udp=300, tcp_established=7440, tcp_transitory=2, icmp=5
+ )
out_port = self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port)
# FIN packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="FA", seq=100, ack=300))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="FA", seq=100, ack=300)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# FIN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="FA", seq=300, ack=100))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=100)
+ )
self.send_and_expect(self.pg1, p, self.pg0)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - session_n, 1)
# send SYN packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="S", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="S", seq=101, ack=301)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
self.virtual_sleep(3)
# send ACK packet in -> out - session should be wiped
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301)
+ )
self.send_and_assert_no_replies(self.pg0, p, self.pg1)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - session_n, 0)
def test_tcp_session_half_reopen_outside(self):
- """ TCP session in FIN/FIN state not reopened by out2in SYN only """
+ """TCP session in FIN/FIN state not reopened by out2in SYN only"""
in_port = self.tcp_port_in
ext_port = 10505
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
- self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- in_port, ext_port, proto=IP_PROTOS.tcp,
- flags=self.config_flags.NAT_IS_TWICE_NAT)
+ self.nat_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ in_port,
+ ext_port,
+ proto=IP_PROTOS.tcp,
+ flags=self.config_flags.NAT_IS_TWICE_NAT,
+ )
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
session_n = len(sessions)
- self.vapi.nat_set_timeouts(udp=300, tcp_established=7440,
- tcp_transitory=2, icmp=5)
+ self.vapi.nat_set_timeouts(
+ udp=300, tcp_established=7440, tcp_transitory=2, icmp=5
+ )
out_port = self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port)
# FIN packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="FA", seq=100, ack=300))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="FA", seq=100, ack=300)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# FIN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="FA", seq=300, ack=100))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=100)
+ )
self.send_and_expect(self.pg1, p, self.pg0)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - session_n, 1)
# send SYN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="S", seq=300, ack=101))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="S", seq=300, ack=101)
+ )
self.send_and_expect(self.pg1, p, self.pg0)
self.virtual_sleep(3)
# send ACK packet in -> out - session should be wiped
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301)
+ )
self.send_and_assert_no_replies(self.pg0, p, self.pg1)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - session_n, 0)
def test_tcp_session_reopen(self):
- """ TCP session in FIN/FIN state reopened by SYN from both sides """
+ """TCP session in FIN/FIN state reopened by SYN from both sides"""
in_port = self.tcp_port_in
ext_port = 10505
self.nat_add_address(self.nat_addr)
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
- self.nat_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- in_port, ext_port, proto=IP_PROTOS.tcp,
- flags=self.config_flags.NAT_IS_TWICE_NAT)
+ self.nat_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ in_port,
+ ext_port,
+ proto=IP_PROTOS.tcp,
+ flags=self.config_flags.NAT_IS_TWICE_NAT,
+ )
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
session_n = len(sessions)
- self.vapi.nat_set_timeouts(udp=300, tcp_established=7440,
- tcp_transitory=2, icmp=5)
+ self.vapi.nat_set_timeouts(
+ udp=300, tcp_established=7440, tcp_transitory=2, icmp=5
+ )
out_port = self.init_tcp_session(self.pg0, self.pg1, in_port, ext_port)
# FIN packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="FA", seq=100, ack=300))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="FA", seq=100, ack=300)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# FIN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="FA", seq=300, ack=100))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="FA", seq=300, ack=100)
+ )
self.send_and_expect(self.pg1, p, self.pg0)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - session_n, 1)
# send SYN packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="S", seq=300, ack=101))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="S", seq=300, ack=101)
+ )
self.send_and_expect(self.pg1, p, self.pg0)
# send SYN packet in -> out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="SA", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="SA", seq=101, ack=301)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# send ACK packet out -> in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port,
- flags="A", seq=300, ack=101))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="A", seq=300, ack=101)
+ )
self.send_and_expect(self.pg1, p, self.pg0)
self.virtual_sleep(3)
# send ACK packet in -> out - should be forwarded and session alive
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port,
- flags="A", seq=101, ack=301))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A", seq=101, ack=301)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
sessions = self.vapi.nat44_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(len(sessions) - session_n, 1)
def test_dynamic_vrf(self):
- """ NAT44ED dynamic translation test: different VRF"""
+ """NAT44ED dynamic translation test: different VRF"""
vrf_id_in = 33
vrf_id_out = 34
@@ -3789,30 +4148,28 @@ class TestNAT44EDMW(TestNAT44ED):
self.pg7.unconfig()
self.pg8.unconfig()
- self.vapi.ip_table_add_del(is_add=0,
- table={'table_id': vrf_id_in})
- self.vapi.ip_table_add_del(is_add=0,
- table={'table_id': vrf_id_out})
+ self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id_in})
+ self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id_out})
def test_dynamic_output_feature_vrf(self):
- """ NAT44ED dynamic translation test: output-feature, VRF"""
+ """NAT44ED dynamic translation test: output-feature, VRF"""
# other then default (0)
new_vrf_id = 22
self.nat_add_address(self.nat_addr)
self.vapi.nat44_ed_add_del_output_interface(
- sw_if_index=self.pg8.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg8.sw_if_index, is_add=1
+ )
try:
self.configure_ip4_interface(self.pg7, table_id=new_vrf_id)
self.configure_ip4_interface(self.pg8, table_id=new_vrf_id)
# in2out
- tcpn = self.statistics['/nat44-ed/in2out/slowpath/tcp']
- udpn = self.statistics['/nat44-ed/in2out/slowpath/udp']
- icmpn = self.statistics['/nat44-ed/in2out/slowpath/icmp']
- drops = self.statistics['/nat44-ed/in2out/slowpath/drops']
+ tcpn = self.statistics["/nat44-ed/in2out/slowpath/tcp"]
+ udpn = self.statistics["/nat44-ed/in2out/slowpath/udp"]
+ icmpn = self.statistics["/nat44-ed/in2out/slowpath/icmp"]
+ drops = self.statistics["/nat44-ed/in2out/slowpath/drops"]
pkts = self.create_stream_in(self.pg7, self.pg8)
self.pg7.add_stream(pkts)
@@ -3822,20 +4179,20 @@ class TestNAT44EDMW(TestNAT44ED):
self.verify_capture_out(capture, ignore_port=True)
if_idx = self.pg8.sw_if_index
- cnt = self.statistics['/nat44-ed/in2out/slowpath/tcp']
+ cnt = self.statistics["/nat44-ed/in2out/slowpath/tcp"]
self.assertEqual(cnt[:, if_idx].sum() - tcpn[:, if_idx].sum(), 2)
- cnt = self.statistics['/nat44-ed/in2out/slowpath/udp']
+ cnt = self.statistics["/nat44-ed/in2out/slowpath/udp"]
self.assertEqual(cnt[:, if_idx].sum() - udpn[:, if_idx].sum(), 1)
- cnt = self.statistics['/nat44-ed/in2out/slowpath/icmp']
+ cnt = self.statistics["/nat44-ed/in2out/slowpath/icmp"]
self.assertEqual(cnt[:, if_idx].sum() - icmpn[:, if_idx].sum(), 1)
- cnt = self.statistics['/nat44-ed/in2out/slowpath/drops']
+ cnt = self.statistics["/nat44-ed/in2out/slowpath/drops"]
self.assertEqual(cnt[:, if_idx].sum() - drops[:, if_idx].sum(), 0)
# out2in
- tcpn = self.statistics['/nat44-ed/out2in/fastpath/tcp']
- udpn = self.statistics['/nat44-ed/out2in/fastpath/udp']
- icmpn = self.statistics['/nat44-ed/out2in/fastpath/icmp']
- drops = self.statistics['/nat44-ed/out2in/fastpath/drops']
+ tcpn = self.statistics["/nat44-ed/out2in/fastpath/tcp"]
+ udpn = self.statistics["/nat44-ed/out2in/fastpath/udp"]
+ icmpn = self.statistics["/nat44-ed/out2in/fastpath/icmp"]
+ drops = self.statistics["/nat44-ed/out2in/fastpath/drops"]
pkts = self.create_stream_out(self.pg8)
self.pg8.add_stream(pkts)
@@ -3845,48 +4202,56 @@ class TestNAT44EDMW(TestNAT44ED):
self.verify_capture_in(capture, self.pg7)
if_idx = self.pg8.sw_if_index
- cnt = self.statistics['/nat44-ed/out2in/fastpath/tcp']
+ cnt = self.statistics["/nat44-ed/out2in/fastpath/tcp"]
self.assertEqual(cnt[:, if_idx].sum() - tcpn[:, if_idx].sum(), 2)
- cnt = self.statistics['/nat44-ed/out2in/fastpath/udp']
+ cnt = self.statistics["/nat44-ed/out2in/fastpath/udp"]
self.assertEqual(cnt[:, if_idx].sum() - udpn[:, if_idx].sum(), 1)
- cnt = self.statistics['/nat44-ed/out2in/fastpath/icmp']
+ cnt = self.statistics["/nat44-ed/out2in/fastpath/icmp"]
self.assertEqual(cnt[:, if_idx].sum() - icmpn[:, if_idx].sum(), 1)
- cnt = self.statistics['/nat44-ed/out2in/fastpath/drops']
+ cnt = self.statistics["/nat44-ed/out2in/fastpath/drops"]
self.assertEqual(cnt[:, if_idx].sum() - drops[:, if_idx].sum(), 0)
- sessions = self.statistics['/nat44-ed/total-sessions']
+ sessions = self.statistics["/nat44-ed/total-sessions"]
self.assertEqual(sessions[:, 0].sum(), 3)
finally:
self.pg7.unconfig()
self.pg8.unconfig()
- self.vapi.ip_table_add_del(is_add=0,
- table={'table_id': new_vrf_id})
+ self.vapi.ip_table_add_del(is_add=0, table={"table_id": new_vrf_id})
def test_next_src_nat(self):
- """ NAT44ED On way back forward packet to nat44-in2out node. """
+ """NAT44ED On way back forward packet to nat44-in2out node."""
- twice_nat_addr = '10.0.1.3'
+ twice_nat_addr = "10.0.1.3"
external_port = 80
local_port = 8080
post_twice_nat_port = 0
self.vapi.nat44_forwarding_enable_disable(enable=1)
self.nat_add_address(twice_nat_addr, twice_nat=1)
- flags = (self.config_flags.NAT_IS_OUT2IN_ONLY |
- self.config_flags.NAT_IS_SELF_TWICE_NAT)
- self.nat_add_static_mapping(self.pg6.remote_ip4, self.pg1.remote_ip4,
- local_port, external_port,
- proto=IP_PROTOS.tcp, vrf_id=1,
- flags=flags)
+ flags = (
+ self.config_flags.NAT_IS_OUT2IN_ONLY
+ | self.config_flags.NAT_IS_SELF_TWICE_NAT
+ )
+ self.nat_add_static_mapping(
+ self.pg6.remote_ip4,
+ self.pg1.remote_ip4,
+ local_port,
+ external_port,
+ proto=IP_PROTOS.tcp,
+ vrf_id=1,
+ flags=flags,
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg6.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg6.sw_if_index, is_add=1
+ )
- p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) /
- IP(src=self.pg6.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=12345, dport=external_port))
+ p = (
+ Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac)
+ / IP(src=self.pg6.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=12345, dport=external_port)
+ )
self.pg6.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3905,9 +4270,11 @@ class TestNAT44EDMW(TestNAT44ED):
self.logger.error(ppp("Unexpected or invalid packet:", p))
raise
- p = (Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac) /
- IP(src=self.pg6.remote_ip4, dst=twice_nat_addr) /
- TCP(sport=local_port, dport=post_twice_nat_port))
+ p = (
+ Ether(src=self.pg6.remote_mac, dst=self.pg6.local_mac)
+ / IP(src=self.pg6.remote_ip4, dst=twice_nat_addr)
+ / TCP(sport=local_port, dport=post_twice_nat_port)
+ )
self.pg6.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3926,7 +4293,7 @@ class TestNAT44EDMW(TestNAT44ED):
raise
def test_one_armed_nat44_static(self):
- """ NAT44ED One armed NAT and 1:1 NAPT asymmetrical rule """
+ """NAT44ED One armed NAT and 1:1 NAPT asymmetrical rule"""
remote_host = self.pg4.remote_hosts[0]
local_host = self.pg4.remote_hosts[1]
@@ -3936,23 +4303,31 @@ class TestNAT44EDMW(TestNAT44ED):
self.vapi.nat44_forwarding_enable_disable(enable=1)
self.nat_add_address(self.nat_addr, twice_nat=1)
- flags = (self.config_flags.NAT_IS_OUT2IN_ONLY |
- self.config_flags.NAT_IS_TWICE_NAT)
- self.nat_add_static_mapping(local_host.ip4, self.nat_addr,
- local_port, external_port,
- proto=IP_PROTOS.tcp, flags=flags)
+ flags = (
+ self.config_flags.NAT_IS_OUT2IN_ONLY | self.config_flags.NAT_IS_TWICE_NAT
+ )
+ self.nat_add_static_mapping(
+ local_host.ip4,
+ self.nat_addr,
+ local_port,
+ external_port,
+ proto=IP_PROTOS.tcp,
+ flags=flags,
+ )
flags = self.config_flags.NAT_IS_INSIDE
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg4.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg4.sw_if_index, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg4.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg4.sw_if_index, flags=flags, is_add=1
+ )
# from client to service
- p = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) /
- IP(src=remote_host.ip4, dst=self.nat_addr) /
- TCP(sport=12345, dport=external_port))
+ p = (
+ Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac)
+ / IP(src=remote_host.ip4, dst=self.nat_addr)
+ / TCP(sport=12345, dport=external_port)
+ )
self.pg4.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3972,9 +4347,11 @@ class TestNAT44EDMW(TestNAT44ED):
raise
# from service back to client
- p = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) /
- IP(src=local_host.ip4, dst=self.nat_addr) /
- TCP(sport=local_port, dport=eh_port_in))
+ p = (
+ Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac)
+ / IP(src=local_host.ip4, dst=self.nat_addr)
+ / TCP(sport=local_port, dport=eh_port_in)
+ )
self.pg4.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3993,7 +4370,7 @@ class TestNAT44EDMW(TestNAT44ED):
raise
def test_icmp_error_fwd_outbound(self):
- """ NAT44ED ICMP error outbound with forwarding enabled """
+ """NAT44ED ICMP error outbound with forwarding enabled"""
# Ensure that an outbound ICMP error message is properly associated
# with the inbound forward bypass session it is related to.
@@ -4005,9 +4382,12 @@ class TestNAT44EDMW(TestNAT44ED):
# enable forwarding and initiate connection out2in
self.vapi.nat44_forwarding_enable_disable(enable=1)
- p1 = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) /
- UDP(sport=21, dport=20) / payload)
+ p1 = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4)
+ / UDP(sport=21, dport=20)
+ / payload
+ )
self.pg1.add_stream(p1)
self.pg_enable_capture(self.pg_interfaces)
@@ -4021,10 +4401,12 @@ class TestNAT44EDMW(TestNAT44ED):
# session dumps for a user will only look on the worker that the
# user is supposed to be mapped to in2out. The forward bypass session
# is not necessarily created on that worker.
- p2 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- ICMP(type='dest-unreach', code='port-unreachable') /
- capture[IP:])
+ p2 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / ICMP(type="dest-unreach", code="port-unreachable")
+ / capture[IP:]
+ )
self.pg0.add_stream(p2)
self.pg_enable_capture(self.pg_interfaces)
@@ -4038,11 +4420,11 @@ class TestNAT44EDMW(TestNAT44ED):
self.logger.info(ppp("capture packet:", capture))
def test_tcp_session_open_retransmit1(self):
- """ NAT44ED Open TCP session with SYN,ACK retransmit 1
+ """NAT44ED Open TCP session with SYN,ACK retransmit 1
- The client does not receive the [SYN,ACK] or the
- ACK from the client is lost. Therefore, the [SYN, ACK]
- is retransmitted by the server.
+ The client does not receive the [SYN,ACK] or the
+ ACK from the client is lost. Therefore, the [SYN, ACK]
+ is retransmitted by the server.
"""
in_port = self.tcp_port_in
@@ -4053,50 +4435,61 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
- self.vapi.nat_set_timeouts(udp=300, tcp_established=7440,
- tcp_transitory=5, icmp=60)
+ self.vapi.nat_set_timeouts(
+ udp=300, tcp_established=7440, tcp_transitory=5, icmp=60
+ )
# SYN packet in->out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port, flags="S"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="S")
+ )
p = self.send_and_expect(self.pg0, p, self.pg1)[0]
out_port = p[TCP].sport
# SYN + ACK packet out->in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port, flags="SA"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="SA")
+ )
self.send_and_expect(self.pg1, p, self.pg0)
# ACK in->out does not arrive
# resent SYN + ACK packet out->in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port, flags="SA"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="SA")
+ )
self.send_and_expect(self.pg1, p, self.pg0)
# ACK packet in->out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port, flags="A"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A")
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# Verify that the data can be transmitted after the transitory time
self.virtual_sleep(6)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port, flags="PA") /
- Raw(payload))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="PA")
+ / Raw(payload)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
def test_tcp_session_open_retransmit2(self):
- """ NAT44ED Open TCP session with SYN,ACK retransmit 2
+ """NAT44ED Open TCP session with SYN,ACK retransmit 2
- The ACK is lost to the server after the TCP session is opened.
- Data is sent by the client, then the [SYN,ACK] is
- retransmitted by the server.
+ The ACK is lost to the server after the TCP session is opened.
+ Data is sent by the client, then the [SYN,ACK] is
+ retransmitted by the server.
"""
in_port = self.tcp_port_in
@@ -4107,68 +4500,87 @@ class TestNAT44EDMW(TestNAT44ED):
self.nat_add_inside_interface(self.pg0)
self.nat_add_outside_interface(self.pg1)
- self.vapi.nat_set_timeouts(udp=300, tcp_established=7440,
- tcp_transitory=5, icmp=60)
+ self.vapi.nat_set_timeouts(
+ udp=300, tcp_established=7440, tcp_transitory=5, icmp=60
+ )
# SYN packet in->out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port, flags="S"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="S")
+ )
p = self.send_and_expect(self.pg0, p, self.pg1)[0]
out_port = p[TCP].sport
# SYN + ACK packet out->in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port, flags="SA"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="SA")
+ )
self.send_and_expect(self.pg1, p, self.pg0)
# ACK packet in->out -- not received by the server
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port, flags="A"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A")
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# PUSH + ACK packet in->out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port, flags="PA") /
- Raw(payload))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="PA")
+ / Raw(payload)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# resent SYN + ACK packet out->in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port, flags="SA"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="SA")
+ )
self.send_and_expect(self.pg1, p, self.pg0)
# resent ACK packet in->out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port, flags="A"))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="A")
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# resent PUSH + ACK packet in->out
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port, flags="PA") /
- Raw(payload))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="PA")
+ / Raw(payload)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
# ACK packet out->in
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=ext_port, dport=out_port, flags="A"))
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=ext_port, dport=out_port, flags="A")
+ )
self.send_and_expect(self.pg1, p, self.pg0)
# Verify that the data can be transmitted after the transitory time
self.virtual_sleep(6)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=in_port, dport=ext_port, flags="PA") /
- Raw(payload))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=in_port, dport=ext_port, flags="PA")
+ / Raw(payload)
+ )
self.send_and_expect(self.pg0, p, self.pg1)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_nat44_ed_output.py b/test/test_nat44_ed_output.py
index 4ea8a5b5eda..4d75241c321 100644
--- a/test/test_nat44_ed_output.py
+++ b/test/test_nat44_ed_output.py
@@ -21,7 +21,8 @@ def get_nat44_ed_in2out_worker_index(ip, vpp_worker_count):
class TestNAT44EDOutput(VppTestCase):
- """ NAT44 ED output feature Test Case """
+ """NAT44 ED output feature Test Case"""
+
max_sessions = 1024
@classmethod
@@ -40,8 +41,7 @@ class TestNAT44EDOutput(VppTestCase):
i.admin_up()
i.config_ip4()
i.resolve_arp()
- self.vapi.nat44_ed_plugin_enable_disable(sessions=self.max_sessions,
- enable=1)
+ self.vapi.nat44_ed_plugin_enable_disable(sessions=self.max_sessions, enable=1)
def tearDown(self):
if not self.vpp_dead:
@@ -54,7 +54,7 @@ class TestNAT44EDOutput(VppTestCase):
self.vapi.nat44_ed_plugin_enable_disable(enable=0)
def test_static_dynamic(self):
- """ Create static mapping which matches existing dynamic mapping """
+ """Create static mapping which matches existing dynamic mapping"""
config = self.vapi.nat44_show_running_config()
old_timeouts = config.timeouts
@@ -63,31 +63,37 @@ class TestNAT44EDOutput(VppTestCase):
udp=old_timeouts.udp,
tcp_established=old_timeouts.tcp_established,
icmp=old_timeouts.icmp,
- tcp_transitory=new_transitory)
+ tcp_transitory=new_transitory,
+ )
local_host = self.pg0.remote_ip4
remote_host = self.pg1.remote_ip4
nat_intf = self.pg1
outside_addr = nat_intf.local_ip4
- self.vapi.nat44_add_del_address_range(first_ip_address=outside_addr,
- last_ip_address=outside_addr,
- vrf_id=0xffffffff,
- is_add=1,
- flags=0)
+ self.vapi.nat44_add_del_address_range(
+ first_ip_address=outside_addr,
+ last_ip_address=outside_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ flags=0,
+ )
self.vapi.nat44_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1
+ )
self.vapi.nat44_interface_add_del_feature(
sw_if_index=self.pg0.sw_if_index,
- flags=VppEnum.vl_api_nat_config_flags_t.NAT_IS_INSIDE, is_add=1)
+ flags=VppEnum.vl_api_nat_config_flags_t.NAT_IS_INSIDE,
+ is_add=1,
+ )
self.vapi.nat44_ed_add_del_output_interface(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
thread_index = get_nat44_ed_in2out_worker_index(
- local_host, self.vpp_worker_count)
- port_per_thread = int((0xffff-1024) / max(1, self.vpp_worker_count))
+ local_host, self.vpp_worker_count
+ )
+ port_per_thread = int((0xFFFF - 1024) / max(1, self.vpp_worker_count))
local_sport = 1024 + random.randint(1, port_per_thread)
if self.vpp_worker_count > 0:
local_sport += port_per_thread * (thread_index - 1)
@@ -100,9 +106,11 @@ class TestNAT44EDOutput(VppTestCase):
# first setup a dynamic TCP session
# SYN packet in->out
- p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) /
- IP(src=local_host, dst=remote_host) /
- TCP(sport=local_sport, dport=remote_dport, flags="S"))
+ p = (
+ Ether(src=pg0.remote_mac, dst=pg0.local_mac)
+ / IP(src=local_host, dst=remote_host)
+ / TCP(sport=local_sport, dport=remote_dport, flags="S")
+ )
p = self.send_and_expect(pg0, [p], pg1)[0]
self.assertEqual(p[IP].src, outside_addr)
@@ -110,15 +118,19 @@ class TestNAT44EDOutput(VppTestCase):
outside_port = p[TCP].sport
# SYN+ACK packet out->in
- p = (Ether(src=pg1.remote_mac, dst=pg1.local_mac) /
- IP(src=remote_host, dst=outside_addr) /
- TCP(sport=remote_dport, dport=outside_port, flags="SA"))
+ p = (
+ Ether(src=pg1.remote_mac, dst=pg1.local_mac)
+ / IP(src=remote_host, dst=outside_addr)
+ / TCP(sport=remote_dport, dport=outside_port, flags="SA")
+ )
self.send_and_expect(pg1, [p], pg0)
# ACK packet in->out
- p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) /
- IP(src=local_host, dst=remote_host) /
- TCP(sport=local_sport, dport=remote_dport, flags="A"))
+ p = (
+ Ether(src=pg0.remote_mac, dst=pg0.local_mac)
+ / IP(src=local_host, dst=remote_host)
+ / TCP(sport=local_sport, dport=remote_dport, flags="A")
+ )
self.send_and_expect(pg0, [p], pg1)
# now we have a session up, create a conflicting static mapping
@@ -126,11 +138,12 @@ class TestNAT44EDOutput(VppTestCase):
is_add=1,
local_ip_address=local_host,
external_ip_address=outside_addr,
- external_sw_if_index=0xffffffff,
+ external_sw_if_index=0xFFFFFFFF,
local_port=local_sport,
external_port=outside_port,
protocol=IP_PROTOS.tcp,
- flags=VppEnum.vl_api_nat_config_flags_t.NAT_IS_OUT2IN_ONLY)
+ flags=VppEnum.vl_api_nat_config_flags_t.NAT_IS_OUT2IN_ONLY,
+ )
sessions = self.vapi.nat44_user_session_dump(local_host, 0)
self.assertEqual(1, len(sessions))
@@ -138,47 +151,56 @@ class TestNAT44EDOutput(VppTestCase):
# now send some more data over existing session - it should pass
# in->out
- p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) /
- IP(src=local_host, dst=remote_host) /
- TCP(sport=local_sport, dport=remote_dport) /
- Raw("zippity zap"))
+ p = (
+ Ether(src=pg0.remote_mac, dst=pg0.local_mac)
+ / IP(src=local_host, dst=remote_host)
+ / TCP(sport=local_sport, dport=remote_dport)
+ / Raw("zippity zap")
+ )
self.send_and_expect(pg0, [p], pg1)
# out->in
- p = (Ether(src=pg1.remote_mac, dst=pg1.local_mac) /
- IP(src=remote_host, dst=outside_addr) /
- TCP(sport=remote_dport, dport=outside_port) /
- Raw("flippity flop"))
+ p = (
+ Ether(src=pg1.remote_mac, dst=pg1.local_mac)
+ / IP(src=remote_host, dst=outside_addr)
+ / TCP(sport=remote_dport, dport=outside_port)
+ / Raw("flippity flop")
+ )
self.send_and_expect(pg1, [p], pg0)
# now close the session
# FIN packet in -> out
- p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) /
- IP(src=local_host, dst=remote_host) /
- TCP(sport=local_sport, dport=remote_dport, flags="FA", seq=100,
- ack=300))
+ p = (
+ Ether(src=pg0.remote_mac, dst=pg0.local_mac)
+ / IP(src=local_host, dst=remote_host)
+ / TCP(sport=local_sport, dport=remote_dport, flags="FA", seq=100, ack=300)
+ )
self.send_and_expect(pg0, [p], pg1)
# FIN+ACK packet out -> in
- p = (Ether(src=pg1.remote_mac, dst=pg1.local_mac) /
- IP(src=remote_host, dst=outside_addr) /
- TCP(sport=remote_dport, dport=outside_port, flags="FA", seq=300,
- ack=101))
+ p = (
+ Ether(src=pg1.remote_mac, dst=pg1.local_mac)
+ / IP(src=remote_host, dst=outside_addr)
+ / TCP(sport=remote_dport, dport=outside_port, flags="FA", seq=300, ack=101)
+ )
self.send_and_expect(pg1, [p], pg0)
# ACK packet in -> out
- p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) /
- IP(src=local_host, dst=remote_host) /
- TCP(sport=local_sport, dport=remote_dport, flags="A", seq=101,
- ack=301))
+ p = (
+ Ether(src=pg0.remote_mac, dst=pg0.local_mac)
+ / IP(src=local_host, dst=remote_host)
+ / TCP(sport=local_sport, dport=remote_dport, flags="A", seq=101, ack=301)
+ )
self.send_and_expect(pg0, [p], pg1)
# session now in transitory timeout
# try SYN packet in->out - should be dropped
- p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) /
- IP(src=local_host, dst=remote_host) /
- TCP(sport=local_sport, dport=remote_dport, flags="S"))
+ p = (
+ Ether(src=pg0.remote_mac, dst=pg0.local_mac)
+ / IP(src=local_host, dst=remote_host)
+ / TCP(sport=local_sport, dport=remote_dport, flags="S")
+ )
pg0.add_stream(p)
self.pg_enable_capture()
self.pg_start()
@@ -192,10 +214,11 @@ class TestNAT44EDOutput(VppTestCase):
# send FIN+ACK packet in->out - will cause session to be wiped
# but won't create a new session
- p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) /
- IP(src=local_host, dst=remote_host) /
- TCP(sport=local_sport, dport=remote_dport, flags="FA", seq=300,
- ack=101))
+ p = (
+ Ether(src=pg0.remote_mac, dst=pg0.local_mac)
+ / IP(src=local_host, dst=remote_host)
+ / TCP(sport=local_sport, dport=remote_dport, flags="FA", seq=300, ack=101)
+ )
pg1.add_stream(p)
self.pg_enable_capture()
self.pg_start()
@@ -207,9 +230,11 @@ class TestNAT44EDOutput(VppTestCase):
# create a new session and make sure the outside port is remapped
# SYN packet in->out
- p = (Ether(src=pg0.remote_mac, dst=pg0.local_mac) /
- IP(src=local_host, dst=remote_host) /
- TCP(sport=local_sport, dport=remote_dport, flags="S"))
+ p = (
+ Ether(src=pg0.remote_mac, dst=pg0.local_mac)
+ / IP(src=local_host, dst=remote_host)
+ / TCP(sport=local_sport, dport=remote_dport, flags="S")
+ )
p = self.send_and_expect(pg0, [p], pg1)[0]
self.assertEqual(p[IP].src, outside_addr)
@@ -217,14 +242,16 @@ class TestNAT44EDOutput(VppTestCase):
# make sure static mapping works and creates a new session
# SYN packet out->in
- p = (Ether(src=pg1.remote_mac, dst=pg1.local_mac) /
- IP(src=remote_host, dst=outside_addr) /
- TCP(sport=remote_dport, dport=outside_port, flags="S"))
+ p = (
+ Ether(src=pg1.remote_mac, dst=pg1.local_mac)
+ / IP(src=remote_host, dst=outside_addr)
+ / TCP(sport=remote_dport, dport=outside_port, flags="S")
+ )
self.send_and_expect(pg1, [p], pg0)
sessions = self.vapi.nat44_user_session_dump(pg0.remote_ip4, 0)
self.assertEqual(2, len(sessions))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_nat44_ei.py b/test/test_nat44_ei.py
index aafd345f43f..9eb127aaf0b 100644
--- a/test/test_nat44_ei.py
+++ b/test/test_nat44_ei.py
@@ -10,9 +10,19 @@ from io import BytesIO
import scapy.compat
from framework import VppTestCase, VppTestRunner
from ipfix import IPFIX, Set, Template, Data, IPFIXDecoder
-from scapy.all import bind_layers, Packet, ByteEnumField, ShortField, \
- IPField, IntField, LongField, XByteField, FlagsField, FieldLenField, \
- PacketListField
+from scapy.all import (
+ bind_layers,
+ Packet,
+ ByteEnumField,
+ ShortField,
+ IPField,
+ IntField,
+ LongField,
+ XByteField,
+ FlagsField,
+ FieldLenField,
+ PacketListField,
+)
from scapy.data import IP_PROTOS
from scapy.layers.inet import IP, TCP, UDP, ICMP
from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror
@@ -30,22 +40,22 @@ from vpp_papi import VppEnum
# NAT HA protocol event data
class Event(Packet):
name = "Event"
- fields_desc = [ByteEnumField("event_type", None,
- {1: "add", 2: "del", 3: "refresh"}),
- ByteEnumField("protocol", None,
- {0: "other", 1: "udp", 2: "tcp", 3: "icmp"}),
- ShortField("flags", 0),
- IPField("in_addr", None),
- IPField("out_addr", None),
- ShortField("in_port", None),
- ShortField("out_port", None),
- IPField("eh_addr", None),
- IPField("ehn_addr", None),
- ShortField("eh_port", None),
- ShortField("ehn_port", None),
- IntField("fib_index", None),
- IntField("total_pkts", 0),
- LongField("total_bytes", 0)]
+ fields_desc = [
+ ByteEnumField("event_type", None, {1: "add", 2: "del", 3: "refresh"}),
+ ByteEnumField("protocol", None, {0: "other", 1: "udp", 2: "tcp", 3: "icmp"}),
+ ShortField("flags", 0),
+ IPField("in_addr", None),
+ IPField("out_addr", None),
+ ShortField("in_port", None),
+ ShortField("out_port", None),
+ IPField("eh_addr", None),
+ IPField("ehn_addr", None),
+ ShortField("eh_port", None),
+ ShortField("ehn_port", None),
+ IntField("fib_index", None),
+ IntField("total_pkts", 0),
+ LongField("total_bytes", 0),
+ ]
def extract_padding(self, s):
return "", s
@@ -54,17 +64,18 @@ class Event(Packet):
# NAT HA protocol header
class HANATStateSync(Packet):
name = "HA NAT state sync"
- fields_desc = [XByteField("version", 1),
- FlagsField("flags", 0, 8, ['ACK']),
- FieldLenField("count", None, count_of="events"),
- IntField("sequence_number", 1),
- IntField("thread_index", 0),
- PacketListField("events", [], Event,
- count_from=lambda pkt: pkt.count)]
+ fields_desc = [
+ XByteField("version", 1),
+ FlagsField("flags", 0, 8, ["ACK"]),
+ FieldLenField("count", None, count_of="events"),
+ IntField("sequence_number", 1),
+ IntField("thread_index", 0),
+ PacketListField("events", [], Event, count_from=lambda pkt: pkt.count),
+ ]
class MethodHolder(VppTestCase):
- """ NAT create capture and verify method holder """
+ """NAT create capture and verify method holder"""
@property
def config_flags(self):
@@ -74,10 +85,19 @@ class MethodHolder(VppTestCase):
def SYSLOG_SEVERITY(self):
return VppEnum.vl_api_syslog_severity_t
- def nat44_add_static_mapping(self, local_ip, external_ip='0.0.0.0',
- local_port=0, external_port=0, vrf_id=0,
- is_add=1, external_sw_if_index=0xFFFFFFFF,
- proto=0, tag="", flags=0):
+ def nat44_add_static_mapping(
+ self,
+ local_ip,
+ external_ip="0.0.0.0",
+ local_port=0,
+ external_port=0,
+ vrf_id=0,
+ is_add=1,
+ external_sw_if_index=0xFFFFFFFF,
+ proto=0,
+ tag="",
+ flags=0,
+ ):
"""
Add/delete NAT44EI static mapping
@@ -103,9 +123,11 @@ class MethodHolder(VppTestCase):
external_sw_if_index=external_sw_if_index,
local_port=local_port,
external_port=external_port,
- vrf_id=vrf_id, protocol=proto,
+ vrf_id=vrf_id,
+ protocol=proto,
flags=flags,
- tag=tag)
+ tag=tag,
+ )
def nat44_add_address(self, ip, is_add=1, vrf_id=0xFFFFFFFF):
"""
@@ -114,31 +136,40 @@ class MethodHolder(VppTestCase):
:param ip: IP address
:param is_add: 1 if add, 0 if delete (Default add)
"""
- self.vapi.nat44_ei_add_del_address_range(first_ip_address=ip,
- last_ip_address=ip,
- vrf_id=vrf_id,
- is_add=is_add)
+ self.vapi.nat44_ei_add_del_address_range(
+ first_ip_address=ip, last_ip_address=ip, vrf_id=vrf_id, is_add=is_add
+ )
def create_routes_and_neigbors(self):
- r1 = VppIpRoute(self, self.pg7.remote_ip4, 32,
- [VppRoutePath(self.pg7.remote_ip4,
- self.pg7.sw_if_index)])
- r2 = VppIpRoute(self, self.pg8.remote_ip4, 32,
- [VppRoutePath(self.pg8.remote_ip4,
- self.pg8.sw_if_index)])
+ r1 = VppIpRoute(
+ self,
+ self.pg7.remote_ip4,
+ 32,
+ [VppRoutePath(self.pg7.remote_ip4, self.pg7.sw_if_index)],
+ )
+ r2 = VppIpRoute(
+ self,
+ self.pg8.remote_ip4,
+ 32,
+ [VppRoutePath(self.pg8.remote_ip4, self.pg8.sw_if_index)],
+ )
r1.add_vpp_config()
r2.add_vpp_config()
- n1 = VppNeighbor(self,
- self.pg7.sw_if_index,
- self.pg7.remote_mac,
- self.pg7.remote_ip4,
- is_static=1)
- n2 = VppNeighbor(self,
- self.pg8.sw_if_index,
- self.pg8.remote_mac,
- self.pg8.remote_ip4,
- is_static=1)
+ n1 = VppNeighbor(
+ self,
+ self.pg7.sw_if_index,
+ self.pg7.remote_mac,
+ self.pg7.remote_ip4,
+ is_static=1,
+ )
+ n2 = VppNeighbor(
+ self,
+ self.pg8.sw_if_index,
+ self.pg8.remote_mac,
+ self.pg8.remote_ip4,
+ is_static=1,
+ )
n1.add_vpp_config()
n2.add_vpp_config()
@@ -156,21 +187,27 @@ class MethodHolder(VppTestCase):
pkts = []
# TCP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- TCP(sport=self.tcp_port_in, dport=20))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / TCP(sport=self.tcp_port_in, dport=20)
+ )
pkts.extend([p, p])
# UDP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- UDP(sport=self.udp_port_in, dport=20))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / UDP(sport=self.udp_port_in, dport=20)
+ )
pkts.append(p)
# ICMP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- ICMP(id=self.icmp_id_in, type='echo-request'))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IP(src=in_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / ICMP(id=self.icmp_id_in, type="echo-request")
+ )
pkts.append(p)
return pkts
@@ -216,11 +253,10 @@ class MethodHolder(VppTestCase):
pref_n[13] = ip4_n[1]
pref_n[14] = ip4_n[2]
pref_n[15] = ip4_n[3]
- packed_pref_n = b''.join([scapy.compat.chb(x) for x in pref_n])
+ packed_pref_n = b"".join([scapy.compat.chb(x) for x in pref_n])
return socket.inet_ntop(socket.AF_INET6, packed_pref_n)
- def create_stream_out(self, out_if, dst_ip=None, ttl=64,
- use_inside_ports=False):
+ def create_stream_out(self, out_if, dst_ip=None, ttl=64, use_inside_ports=False):
"""
Create packet stream for outside network
@@ -242,21 +278,27 @@ class MethodHolder(VppTestCase):
icmp_id = self.icmp_id_in
pkts = []
# TCP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- TCP(dport=tcp_port, sport=20))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / TCP(dport=tcp_port, sport=20)
+ )
pkts.extend([p, p])
# UDP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- UDP(dport=udp_port, sport=20))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / UDP(dport=udp_port, sport=20)
+ )
pkts.append(p)
# ICMP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- ICMP(id=icmp_id, type='echo-reply'))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / ICMP(id=icmp_id, type="echo-reply")
+ )
pkts.append(p)
return pkts
@@ -271,27 +313,40 @@ class MethodHolder(VppTestCase):
"""
pkts = []
# TCP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IPv6(src=src_ip, dst=dst_ip, hlim=hl) /
- TCP(dport=self.tcp_port_out, sport=20))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IPv6(src=src_ip, dst=dst_ip, hlim=hl)
+ / TCP(dport=self.tcp_port_out, sport=20)
+ )
pkts.append(p)
# UDP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IPv6(src=src_ip, dst=dst_ip, hlim=hl) /
- UDP(dport=self.udp_port_out, sport=20))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IPv6(src=src_ip, dst=dst_ip, hlim=hl)
+ / UDP(dport=self.udp_port_out, sport=20)
+ )
pkts.append(p)
# ICMP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IPv6(src=src_ip, dst=dst_ip, hlim=hl) /
- ICMPv6EchoReply(id=self.icmp_id_out))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IPv6(src=src_ip, dst=dst_ip, hlim=hl)
+ / ICMPv6EchoReply(id=self.icmp_id_out)
+ )
pkts.append(p)
return pkts
- def verify_capture_out(self, capture, nat_ip=None, same_port=False,
- dst_ip=None, is_ip6=False, ignore_port=False):
+ def verify_capture_out(
+ self,
+ capture,
+ nat_ip=None,
+ same_port=False,
+ dst_ip=None,
+ is_ip6=False,
+ ignore_port=False,
+ ):
"""
Verify captured packets on outside network
@@ -319,39 +374,33 @@ class MethodHolder(VppTestCase):
if packet.haslayer(TCP):
if not ignore_port:
if same_port:
- self.assertEqual(
- packet[TCP].sport, self.tcp_port_in)
+ self.assertEqual(packet[TCP].sport, self.tcp_port_in)
else:
- self.assertNotEqual(
- packet[TCP].sport, self.tcp_port_in)
+ self.assertNotEqual(packet[TCP].sport, self.tcp_port_in)
self.tcp_port_out = packet[TCP].sport
self.assert_packet_checksums_valid(packet)
elif packet.haslayer(UDP):
if not ignore_port:
if same_port:
- self.assertEqual(
- packet[UDP].sport, self.udp_port_in)
+ self.assertEqual(packet[UDP].sport, self.udp_port_in)
else:
- self.assertNotEqual(
- packet[UDP].sport, self.udp_port_in)
+ self.assertNotEqual(packet[UDP].sport, self.udp_port_in)
self.udp_port_out = packet[UDP].sport
else:
if not ignore_port:
if same_port:
- self.assertEqual(
- packet[ICMP46].id, self.icmp_id_in)
+ self.assertEqual(packet[ICMP46].id, self.icmp_id_in)
else:
- self.assertNotEqual(
- packet[ICMP46].id, self.icmp_id_in)
+ self.assertNotEqual(packet[ICMP46].id, self.icmp_id_in)
self.icmp_id_out = packet[ICMP46].id
self.assert_packet_checksums_valid(packet)
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(outside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (outside network):", packet)
+ )
raise
- def verify_capture_out_ip6(self, capture, nat_ip, same_port=False,
- dst_ip=None):
+ def verify_capture_out_ip6(self, capture, nat_ip, same_port=False, dst_ip=None):
"""
Verify captured packets on outside network
@@ -360,8 +409,7 @@ class MethodHolder(VppTestCase):
:param same_port: Source port number is not translated (Default False)
:param dst_ip: Destination IP address (Default do not verify)
"""
- return self.verify_capture_out(capture, nat_ip, same_port, dst_ip,
- True)
+ return self.verify_capture_out(capture, nat_ip, same_port, dst_ip, True)
def verify_capture_in(self, capture, in_if):
"""
@@ -381,8 +429,9 @@ class MethodHolder(VppTestCase):
else:
self.assertEqual(packet[ICMP].id, self.icmp_id_in)
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(inside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (inside network):", packet)
+ )
raise
def verify_capture_no_translation(self, capture, ingress_if, egress_if):
@@ -404,12 +453,12 @@ class MethodHolder(VppTestCase):
else:
self.assertEqual(packet[ICMP].id, self.icmp_id_in)
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(inside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (inside network):", packet)
+ )
raise
- def verify_capture_out_with_icmp_errors(self, capture, src_ip=None,
- icmp_type=11):
+ def verify_capture_out_with_icmp_errors(self, capture, src_ip=None, icmp_type=11):
"""
Verify captured packets with ICMP errors on outside network
@@ -430,16 +479,15 @@ class MethodHolder(VppTestCase):
self.assertTrue(icmp.haslayer(IPerror))
inner_ip = icmp[IPerror]
if inner_ip.haslayer(TCPerror):
- self.assertEqual(inner_ip[TCPerror].dport,
- self.tcp_port_out)
+ self.assertEqual(inner_ip[TCPerror].dport, self.tcp_port_out)
elif inner_ip.haslayer(UDPerror):
- self.assertEqual(inner_ip[UDPerror].dport,
- self.udp_port_out)
+ self.assertEqual(inner_ip[UDPerror].dport, self.udp_port_out)
else:
self.assertEqual(inner_ip[ICMPerror].id, self.icmp_id_out)
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(outside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (outside network):", packet)
+ )
raise
def verify_capture_in_with_icmp_errors(self, capture, in_if, icmp_type=11):
@@ -460,20 +508,20 @@ class MethodHolder(VppTestCase):
self.assertTrue(icmp.haslayer(IPerror))
inner_ip = icmp[IPerror]
if inner_ip.haslayer(TCPerror):
- self.assertEqual(inner_ip[TCPerror].sport,
- self.tcp_port_in)
+ self.assertEqual(inner_ip[TCPerror].sport, self.tcp_port_in)
elif inner_ip.haslayer(UDPerror):
- self.assertEqual(inner_ip[UDPerror].sport,
- self.udp_port_in)
+ self.assertEqual(inner_ip[UDPerror].sport, self.udp_port_in)
else:
self.assertEqual(inner_ip[ICMPerror].id, self.icmp_id_in)
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(inside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (inside network):", packet)
+ )
raise
- def create_stream_frag(self, src_if, dst, sport, dport, data,
- proto=IP_PROTOS.tcp, echo_reply=False):
+ def create_stream_frag(
+ self, src_if, dst, sport, dport, data, proto=IP_PROTOS.tcp, echo_reply=False
+ ):
"""
Create fragmented packet stream
@@ -487,9 +535,11 @@ class MethodHolder(VppTestCase):
:returns: Fragments
"""
if proto == IP_PROTOS.tcp:
- p = (IP(src=src_if.remote_ip4, dst=dst) /
- TCP(sport=sport, dport=dport) /
- Raw(data))
+ p = (
+ IP(src=src_if.remote_ip4, dst=dst)
+ / TCP(sport=sport, dport=dport)
+ / Raw(data)
+ )
p = p.__class__(scapy.compat.raw(p))
chksum = p[TCP].chksum
proto_header = TCP(sport=sport, dport=dport, chksum=chksum)
@@ -497,9 +547,9 @@ class MethodHolder(VppTestCase):
proto_header = UDP(sport=sport, dport=dport)
elif proto == IP_PROTOS.icmp:
if not echo_reply:
- proto_header = ICMP(id=sport, type='echo-request')
+ proto_header = ICMP(id=sport, type="echo-request")
else:
- proto_header = ICMP(id=sport, type='echo-reply')
+ proto_header = ICMP(id=sport, type="echo-reply")
else:
raise Exception("Unsupported protocol")
id = random.randint(0, 65535)
@@ -508,28 +558,32 @@ class MethodHolder(VppTestCase):
raw = Raw(data[0:4])
else:
raw = Raw(data[0:16])
- p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
- IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id) /
- proto_header /
- raw)
+ p = (
+ Ether(src=src_if.remote_mac, dst=src_if.local_mac)
+ / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id)
+ / proto_header
+ / raw
+ )
pkts.append(p)
if proto == IP_PROTOS.tcp:
raw = Raw(data[4:20])
else:
raw = Raw(data[16:32])
- p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
- IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id,
- proto=proto) /
- raw)
+ p = (
+ Ether(src=src_if.remote_mac, dst=src_if.local_mac)
+ / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id, proto=proto)
+ / raw
+ )
pkts.append(p)
if proto == IP_PROTOS.tcp:
raw = Raw(data[20:])
else:
raw = Raw(data[32:])
- p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
- IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto,
- id=id) /
- raw)
+ p = (
+ Ether(src=src_if.remote_mac, dst=src_if.local_mac)
+ / IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto, id=id)
+ / raw
+ )
pkts.append(p)
return pkts
@@ -550,17 +604,15 @@ class MethodHolder(VppTestCase):
self.assert_ip_checksum_valid(p)
buffer.seek(p[IP].frag * 8)
buffer.write(bytes(p[IP].payload))
- ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst,
- proto=frags[0][IP].proto)
+ ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst, proto=frags[0][IP].proto)
if ip.proto == IP_PROTOS.tcp:
- p = (ip / TCP(buffer.getvalue()))
+ p = ip / TCP(buffer.getvalue())
self.logger.debug(ppp("Reassembled:", p))
self.assert_tcp_checksum_valid(p)
elif ip.proto == IP_PROTOS.udp:
- p = (ip / UDP(buffer.getvalue()[:8]) /
- Raw(buffer.getvalue()[8:]))
+ p = ip / UDP(buffer.getvalue()[:8]) / Raw(buffer.getvalue()[8:])
elif ip.proto == IP_PROTOS.icmp:
- p = (ip / ICMP(buffer.getvalue()))
+ p = ip / ICMP(buffer.getvalue())
return p
def verify_ipfix_nat44_ses(self, data):
@@ -580,29 +632,24 @@ class MethodHolder(VppTestCase):
else:
nat44_ses_delete_num += 1
# sourceIPv4Address
- self.assertEqual(self.pg0.remote_ip4,
- str(ipaddress.IPv4Address(record[8])))
+ self.assertEqual(self.pg0.remote_ip4, str(ipaddress.IPv4Address(record[8])))
# postNATSourceIPv4Address
- self.assertEqual(socket.inet_pton(socket.AF_INET, self.nat_addr),
- record[225])
+ self.assertEqual(
+ socket.inet_pton(socket.AF_INET, self.nat_addr), record[225]
+ )
# ingressVRFID
self.assertEqual(struct.pack("!I", 0), record[234])
# protocolIdentifier/sourceTransportPort
# /postNAPTSourceTransportPort
if IP_PROTOS.icmp == scapy.compat.orb(record[4]):
self.assertEqual(struct.pack("!H", self.icmp_id_in), record[7])
- self.assertEqual(struct.pack("!H", self.icmp_id_out),
- record[227])
+ self.assertEqual(struct.pack("!H", self.icmp_id_out), record[227])
elif IP_PROTOS.tcp == scapy.compat.orb(record[4]):
- self.assertEqual(struct.pack("!H", self.tcp_port_in),
- record[7])
- self.assertEqual(struct.pack("!H", self.tcp_port_out),
- record[227])
+ self.assertEqual(struct.pack("!H", self.tcp_port_in), record[7])
+ self.assertEqual(struct.pack("!H", self.tcp_port_out), record[227])
elif IP_PROTOS.udp == scapy.compat.orb(record[4]):
- self.assertEqual(struct.pack("!H", self.udp_port_in),
- record[7])
- self.assertEqual(struct.pack("!H", self.udp_port_out),
- record[227])
+ self.assertEqual(struct.pack("!H", self.udp_port_in), record[7])
+ self.assertEqual(struct.pack("!H", self.udp_port_out), record[227])
else:
self.fail(f"Invalid protocol {scapy.compat.orb(record[4])}")
self.assertEqual(3, nat44_ses_create_num)
@@ -627,16 +674,16 @@ class MethodHolder(VppTestCase):
self.assertEqual(struct.pack("!I", limit), record[471])
def verify_no_nat44_user(self):
- """ Verify that there is no NAT44EI user """
+ """Verify that there is no NAT44EI user"""
users = self.vapi.nat44_ei_user_dump()
self.assertEqual(len(users), 0)
- users = self.statistics['/nat44-ei/total-users']
+ users = self.statistics["/nat44-ei/total-users"]
self.assertEqual(users[0][0], 0)
- sessions = self.statistics['/nat44-ei/total-sessions']
+ sessions = self.statistics["/nat44-ei/total-sessions"]
self.assertEqual(sessions[0][0], 0)
def verify_syslog_apmap(self, data, is_add=True):
- message = data.decode('utf-8')
+ message = data.decode("utf-8")
try:
message = SyslogMessage.parse(message)
except ParseError as e:
@@ -644,26 +691,26 @@ class MethodHolder(VppTestCase):
raise
else:
self.assertEqual(message.severity, SyslogSeverity.info)
- self.assertEqual(message.appname, 'NAT')
- self.assertEqual(message.msgid, 'APMADD' if is_add else 'APMDEL')
- sd_params = message.sd.get('napmap')
+ self.assertEqual(message.appname, "NAT")
+ self.assertEqual(message.msgid, "APMADD" if is_add else "APMDEL")
+ sd_params = message.sd.get("napmap")
self.assertTrue(sd_params is not None)
- self.assertEqual(sd_params.get('IATYP'), 'IPv4')
- self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip4)
- self.assertEqual(sd_params.get('ISPORT'), "%d" % self.tcp_port_in)
- self.assertEqual(sd_params.get('XATYP'), 'IPv4')
- self.assertEqual(sd_params.get('XSADDR'), self.nat_addr)
- self.assertEqual(sd_params.get('XSPORT'), "%d" % self.tcp_port_out)
- self.assertEqual(sd_params.get('PROTO'), "%d" % IP_PROTOS.tcp)
- self.assertTrue(sd_params.get('SSUBIX') is not None)
- self.assertEqual(sd_params.get('SVLAN'), '0')
+ self.assertEqual(sd_params.get("IATYP"), "IPv4")
+ self.assertEqual(sd_params.get("ISADDR"), self.pg0.remote_ip4)
+ self.assertEqual(sd_params.get("ISPORT"), "%d" % self.tcp_port_in)
+ self.assertEqual(sd_params.get("XATYP"), "IPv4")
+ self.assertEqual(sd_params.get("XSADDR"), self.nat_addr)
+ self.assertEqual(sd_params.get("XSPORT"), "%d" % self.tcp_port_out)
+ self.assertEqual(sd_params.get("PROTO"), "%d" % IP_PROTOS.tcp)
+ self.assertTrue(sd_params.get("SSUBIX") is not None)
+ self.assertEqual(sd_params.get("SVLAN"), "0")
def verify_mss_value(self, pkt, mss):
if not pkt.haslayer(IP) or not pkt.haslayer(TCP):
raise TypeError("Not a TCP/IP packet")
for option in pkt[TCP].options:
- if option[0] == 'MSS':
+ if option[0] == "MSS":
self.assertEqual(option[1], mss)
self.assert_tcp_checksum_valid(pkt)
@@ -678,8 +725,9 @@ class MethodHolder(VppTestCase):
else:
raise Exception("Unsupported protocol")
- def frag_in_order(self, proto=IP_PROTOS.tcp, dont_translate=False,
- ignore_port=False):
+ def frag_in_order(
+ self, proto=IP_PROTOS.tcp, dont_translate=False, ignore_port=False
+ ):
layer = self.proto2layer(proto)
if proto == IP_PROTOS.tcp:
@@ -689,20 +737,19 @@ class MethodHolder(VppTestCase):
self.port_in = random.randint(1025, 65535)
# in2out
- pkts = self.create_stream_frag(self.pg0, self.pg1.remote_ip4,
- self.port_in, 20, data, proto)
+ pkts = self.create_stream_frag(
+ self.pg0, self.pg1.remote_ip4, self.port_in, 20, data, proto
+ )
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg1.get_capture(len(pkts))
if not dont_translate:
- p = self.reass_frags_and_verify(frags,
- self.nat_addr,
- self.pg1.remote_ip4)
+ p = self.reass_frags_and_verify(frags, self.nat_addr, self.pg1.remote_ip4)
else:
- p = self.reass_frags_and_verify(frags,
- self.pg0.remote_ip4,
- self.pg1.remote_ip4)
+ p = self.reass_frags_and_verify(
+ frags, self.pg0.remote_ip4, self.pg1.remote_ip4
+ )
if proto != IP_PROTOS.icmp:
if not dont_translate:
self.assertEqual(p[layer].dport, 20)
@@ -729,15 +776,14 @@ class MethodHolder(VppTestCase):
else:
sport = p[layer].id
dport = 0
- pkts = self.create_stream_frag(self.pg1, dst_addr, sport, dport, data,
- proto, echo_reply=True)
+ pkts = self.create_stream_frag(
+ self.pg1, dst_addr, sport, dport, data, proto, echo_reply=True
+ )
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg0.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- self.pg1.remote_ip4,
- self.pg0.remote_ip4)
+ p = self.reass_frags_and_verify(frags, self.pg1.remote_ip4, self.pg0.remote_ip4)
if proto != IP_PROTOS.icmp:
self.assertEqual(p[layer].sport, 20)
self.assertEqual(p[layer].dport, self.port_in)
@@ -745,9 +791,15 @@ class MethodHolder(VppTestCase):
self.assertEqual(p[layer].id, self.port_in)
self.assertEqual(data, p[Raw].load)
- def reass_hairpinning(self, server_addr, server_in_port, server_out_port,
- host_in_port, proto=IP_PROTOS.tcp,
- ignore_port=False):
+ def reass_hairpinning(
+ self,
+ server_addr,
+ server_in_port,
+ server_out_port,
+ host_in_port,
+ proto=IP_PROTOS.tcp,
+ ignore_port=False,
+ ):
layer = self.proto2layer(proto)
@@ -757,19 +809,14 @@ class MethodHolder(VppTestCase):
data = b"A" * 16 + b"B" * 16 + b"C" * 3
# send packet from host to server
- pkts = self.create_stream_frag(self.pg0,
- self.nat_addr,
- host_in_port,
- server_out_port,
- data,
- proto)
+ pkts = self.create_stream_frag(
+ self.pg0, self.nat_addr, host_in_port, server_out_port, data, proto
+ )
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg0.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- self.nat_addr,
- server_addr)
+ p = self.reass_frags_and_verify(frags, self.nat_addr, server_addr)
if proto != IP_PROTOS.icmp:
if not ignore_port:
self.assertNotEqual(p[layer].sport, host_in_port)
@@ -779,8 +826,9 @@ class MethodHolder(VppTestCase):
self.assertNotEqual(p[layer].id, host_in_port)
self.assertEqual(data, p[Raw].load)
- def frag_out_of_order(self, proto=IP_PROTOS.tcp, dont_translate=False,
- ignore_port=False):
+ def frag_out_of_order(
+ self, proto=IP_PROTOS.tcp, dont_translate=False, ignore_port=False
+ ):
layer = self.proto2layer(proto)
if proto == IP_PROTOS.tcp:
@@ -791,21 +839,22 @@ class MethodHolder(VppTestCase):
for i in range(2):
# in2out
- pkts = self.create_stream_frag(self.pg0, self.pg1.remote_ip4,
- self.port_in, 20, data, proto)
+ pkts = self.create_stream_frag(
+ self.pg0, self.pg1.remote_ip4, self.port_in, 20, data, proto
+ )
pkts.reverse()
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg1.get_capture(len(pkts))
if not dont_translate:
- p = self.reass_frags_and_verify(frags,
- self.nat_addr,
- self.pg1.remote_ip4)
+ p = self.reass_frags_and_verify(
+ frags, self.nat_addr, self.pg1.remote_ip4
+ )
else:
- p = self.reass_frags_and_verify(frags,
- self.pg0.remote_ip4,
- self.pg1.remote_ip4)
+ p = self.reass_frags_and_verify(
+ frags, self.pg0.remote_ip4, self.pg1.remote_ip4
+ )
if proto != IP_PROTOS.icmp:
if not dont_translate:
self.assertEqual(p[layer].dport, 20)
@@ -832,16 +881,17 @@ class MethodHolder(VppTestCase):
else:
sport = p[layer].id
dport = 0
- pkts = self.create_stream_frag(self.pg1, dst_addr, sport, dport,
- data, proto, echo_reply=True)
+ pkts = self.create_stream_frag(
+ self.pg1, dst_addr, sport, dport, data, proto, echo_reply=True
+ )
pkts.reverse()
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg0.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- self.pg1.remote_ip4,
- self.pg0.remote_ip4)
+ p = self.reass_frags_and_verify(
+ frags, self.pg1.remote_ip4, self.pg0.remote_ip4
+ )
if proto != IP_PROTOS.icmp:
self.assertEqual(p[layer].sport, 20)
self.assertEqual(p[layer].dport, self.port_in)
@@ -861,7 +911,7 @@ def get_nat44_ei_in2out_worker_index(ip, vpp_worker_count):
class TestNAT44EI(MethodHolder):
- """ NAT44EI Test Cases """
+ """NAT44EI Test Cases"""
max_translations = 10240
max_users = 10240
@@ -877,7 +927,7 @@ class TestNAT44EI(MethodHolder):
cls.udp_port_out = 6304
cls.icmp_id_in = 6305
cls.icmp_id_out = 6305
- cls.nat_addr = '10.0.0.3'
+ cls.nat_addr = "10.0.0.3"
cls.ipfix_src_port = 4739
cls.ipfix_domain_id = 1
cls.tcp_external_port = 80
@@ -898,8 +948,8 @@ class TestNAT44EI(MethodHolder):
cls.pg1.configure_ipv4_neighbors()
cls.overlapping_interfaces = list(list(cls.pg_interfaces[4:7]))
- cls.vapi.ip_table_add_del(is_add=1, table={'table_id': 10})
- cls.vapi.ip_table_add_del(is_add=1, table={'table_id': 20})
+ cls.vapi.ip_table_add_del(is_add=1, table={"table_id": 10})
+ cls.vapi.ip_table_add_del(is_add=1, table={"table_id": 20})
cls.pg4._local_ip4 = "172.16.255.1"
cls.pg4._remote_hosts[0]._ip4 = "172.16.255.2"
@@ -921,8 +971,8 @@ class TestNAT44EI(MethodHolder):
cls.pg9.generate_remote_hosts(2)
cls.pg9.config_ip4()
cls.vapi.sw_interface_add_del_address(
- sw_if_index=cls.pg9.sw_if_index,
- prefix="10.0.0.1/24")
+ sw_if_index=cls.pg9.sw_if_index, prefix="10.0.0.1/24"
+ )
cls.pg9.admin_up()
cls.pg9.resolve_arp()
@@ -932,8 +982,8 @@ class TestNAT44EI(MethodHolder):
def plugin_enable(self):
self.vapi.nat44_ei_plugin_enable_disable(
- sessions=self.max_translations,
- users=self.max_users, enable=1)
+ sessions=self.max_translations, users=self.max_users, enable=1
+ )
def setUp(self):
super(TestNAT44EI, self).setUp()
@@ -943,8 +993,8 @@ class TestNAT44EI(MethodHolder):
super(TestNAT44EI, self).tearDown()
if not self.vpp_dead:
self.vapi.nat44_ei_ipfix_enable_disable(
- domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port,
- enable=0)
+ domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=0
+ )
self.ipfix_src_port = 4739
self.ipfix_domain_id = 1
@@ -952,16 +1002,16 @@ class TestNAT44EI(MethodHolder):
self.vapi.cli("clear logging")
def test_clear_sessions(self):
- """ NAT44EI session clearing test """
+ """NAT44EI session clearing test"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
pkts = self.create_stream_in(self.pg0, self.pg1)
self.pg0.add_stream(pkts)
@@ -970,32 +1020,32 @@ class TestNAT44EI(MethodHolder):
capture = self.pg1.get_capture(len(pkts))
self.verify_capture_out(capture)
- sessions = self.statistics['/nat44-ei/total-sessions']
+ sessions = self.statistics["/nat44-ei/total-sessions"]
self.assertGreater(sessions[:, 0].sum(), 0, "Session count invalid")
self.logger.info("sessions before clearing: %s" % sessions[0][0])
self.vapi.cli("clear nat44 ei sessions")
- sessions = self.statistics['/nat44-ei/total-sessions']
+ sessions = self.statistics["/nat44-ei/total-sessions"]
self.assertEqual(sessions[:, 0].sum(), 0, "Session count invalid")
self.logger.info("sessions after clearing: %s" % sessions[0][0])
def test_dynamic(self):
- """ NAT44EI dynamic translation test """
+ """NAT44EI dynamic translation test"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# in2out
- tcpn = self.statistics['/nat44-ei/in2out/slowpath/tcp']
- udpn = self.statistics['/nat44-ei/in2out/slowpath/udp']
- icmpn = self.statistics['/nat44-ei/in2out/slowpath/icmp']
- drops = self.statistics['/nat44-ei/in2out/slowpath/drops']
+ tcpn = self.statistics["/nat44-ei/in2out/slowpath/tcp"]
+ udpn = self.statistics["/nat44-ei/in2out/slowpath/udp"]
+ icmpn = self.statistics["/nat44-ei/in2out/slowpath/icmp"]
+ drops = self.statistics["/nat44-ei/in2out/slowpath/drops"]
pkts = self.create_stream_in(self.pg0, self.pg1)
self.pg0.add_stream(pkts)
@@ -1005,20 +1055,20 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_out(capture)
if_idx = self.pg0.sw_if_index
- cnt = self.statistics['/nat44-ei/in2out/slowpath/tcp']
+ cnt = self.statistics["/nat44-ei/in2out/slowpath/tcp"]
self.assertEqual(cnt[:, if_idx].sum() - tcpn[:, if_idx].sum(), 2)
- cnt = self.statistics['/nat44-ei/in2out/slowpath/udp']
+ cnt = self.statistics["/nat44-ei/in2out/slowpath/udp"]
self.assertEqual(cnt[:, if_idx].sum() - udpn[:, if_idx].sum(), 1)
- cnt = self.statistics['/nat44-ei/in2out/slowpath/icmp']
+ cnt = self.statistics["/nat44-ei/in2out/slowpath/icmp"]
self.assertEqual(cnt[:, if_idx].sum() - icmpn[:, if_idx].sum(), 1)
- cnt = self.statistics['/nat44-ei/in2out/slowpath/drops']
+ cnt = self.statistics["/nat44-ei/in2out/slowpath/drops"]
self.assertEqual(cnt[:, if_idx].sum() - drops[:, if_idx].sum(), 0)
# out2in
- tcpn = self.statistics['/nat44-ei/out2in/slowpath/tcp']
- udpn = self.statistics['/nat44-ei/out2in/slowpath/udp']
- icmpn = self.statistics['/nat44-ei/out2in/slowpath/icmp']
- drops = self.statistics['/nat44-ei/out2in/slowpath/drops']
+ tcpn = self.statistics["/nat44-ei/out2in/slowpath/tcp"]
+ udpn = self.statistics["/nat44-ei/out2in/slowpath/udp"]
+ icmpn = self.statistics["/nat44-ei/out2in/slowpath/icmp"]
+ drops = self.statistics["/nat44-ei/out2in/slowpath/drops"]
pkts = self.create_stream_out(self.pg1)
self.pg1.add_stream(pkts)
@@ -1028,31 +1078,31 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_in(capture, self.pg0)
if_idx = self.pg1.sw_if_index
- cnt = self.statistics['/nat44-ei/out2in/slowpath/tcp']
+ cnt = self.statistics["/nat44-ei/out2in/slowpath/tcp"]
self.assertEqual(cnt[:, if_idx].sum() - tcpn[:, if_idx].sum(), 2)
- cnt = self.statistics['/nat44-ei/out2in/slowpath/udp']
+ cnt = self.statistics["/nat44-ei/out2in/slowpath/udp"]
self.assertEqual(cnt[:, if_idx].sum() - udpn[:, if_idx].sum(), 1)
- cnt = self.statistics['/nat44-ei/out2in/slowpath/icmp']
+ cnt = self.statistics["/nat44-ei/out2in/slowpath/icmp"]
self.assertEqual(cnt[:, if_idx].sum() - icmpn[:, if_idx].sum(), 1)
- cnt = self.statistics['/nat44-ei/out2in/slowpath/drops']
+ cnt = self.statistics["/nat44-ei/out2in/slowpath/drops"]
self.assertEqual(cnt[:, if_idx].sum() - drops[:, if_idx].sum(), 0)
- users = self.statistics['/nat44-ei/total-users']
+ users = self.statistics["/nat44-ei/total-users"]
self.assertEqual(users[:, 0].sum(), 1)
- sessions = self.statistics['/nat44-ei/total-sessions']
+ sessions = self.statistics["/nat44-ei/total-sessions"]
self.assertEqual(sessions[:, 0].sum(), 3)
def test_dynamic_icmp_errors_in2out_ttl_1(self):
- """ NAT44EI handling of client packets with TTL=1 """
+ """NAT44EI handling of client packets with TTL=1"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# Client side - generate traffic
pkts = self.create_stream_in(self.pg0, self.pg1, ttl=1)
@@ -1062,16 +1112,16 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_in_with_icmp_errors(capture, self.pg0)
def test_dynamic_icmp_errors_out2in_ttl_1(self):
- """ NAT44EI handling of server packets with TTL=1 """
+ """NAT44EI handling of server packets with TTL=1"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# Client side - create sessions
pkts = self.create_stream_in(self.pg0, self.pg1)
@@ -1086,21 +1136,19 @@ class TestNAT44EI(MethodHolder):
capture = self.send_and_expect_some(self.pg1, pkts, self.pg1)
# Server side - verify ICMP type 11 packets
- self.verify_capture_out_with_icmp_errors(capture,
- src_ip=self.pg1.local_ip4)
+ self.verify_capture_out_with_icmp_errors(capture, src_ip=self.pg1.local_ip4)
def test_dynamic_icmp_errors_in2out_ttl_2(self):
- """ NAT44EI handling of error responses to client packets with TTL=2
- """
+ """NAT44EI handling of error responses to client packets with TTL=2"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# Client side - generate traffic
pkts = self.create_stream_in(self.pg0, self.pg1, ttl=2)
@@ -1110,9 +1158,13 @@ class TestNAT44EI(MethodHolder):
# Server side - simulate ICMP type 11 response
capture = self.pg1.get_capture(len(pkts))
- pkts = [Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- ICMP(type=11) / packet[IP] for packet in capture]
+ pkts = [
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / ICMP(type=11)
+ / packet[IP]
+ for packet in capture
+ ]
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1122,17 +1174,16 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_in_with_icmp_errors(capture, self.pg0)
def test_dynamic_icmp_errors_out2in_ttl_2(self):
- """ NAT44EI handling of error responses to server packets with TTL=2
- """
+ """NAT44EI handling of error responses to server packets with TTL=2"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# Client side - create sessions
pkts = self.create_stream_in(self.pg0, self.pg1)
@@ -1150,9 +1201,13 @@ class TestNAT44EI(MethodHolder):
# Client side - simulate ICMP type 11 response
capture = self.pg0.get_capture(len(pkts))
- pkts = [Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- ICMP(type=11) / packet[IP] for packet in capture]
+ pkts = [
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / ICMP(type=11)
+ / packet[IP]
+ for packet in capture
+ ]
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1162,20 +1217,22 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_out_with_icmp_errors(capture)
def test_ping_out_interface_from_outside(self):
- """ NAT44EI ping out interface from outside network """
+ """NAT44EI ping out interface from outside network"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
-
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4) /
- ICMP(id=self.icmp_id_out, type='echo-request'))
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
+
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg1.local_ip4)
+ / ICMP(id=self.icmp_id_out, type="echo-request")
+ )
pkts = [p]
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -1188,26 +1245,29 @@ class TestNAT44EI(MethodHolder):
self.assertEqual(packet[ICMP].id, self.icmp_id_in)
self.assertEqual(packet[ICMP].type, 0) # echo reply
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(outside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (outside network):", packet)
+ )
raise
def test_ping_internal_host_from_outside(self):
- """ NAT44EI ping internal host from outside network """
+ """NAT44EI ping internal host from outside network"""
self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# out2in
- pkt = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr, ttl=64) /
- ICMP(id=self.icmp_id_out, type='echo-request'))
+ pkt = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr, ttl=64)
+ / ICMP(id=self.icmp_id_out, type="echo-request")
+ )
self.pg1.add_stream(pkt)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1216,9 +1276,11 @@ class TestNAT44EI(MethodHolder):
self.assert_equal(capture[0][IP].proto, IP_PROTOS.icmp)
# in2out
- pkt = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64) /
- ICMP(id=self.icmp_id_in, type='echo-reply'))
+ pkt = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, ttl=64)
+ / ICMP(id=self.icmp_id_in, type="echo-reply")
+ )
self.pg0.add_stream(pkt)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1227,25 +1289,27 @@ class TestNAT44EI(MethodHolder):
self.assert_equal(capture[0][IP].proto, IP_PROTOS.icmp)
def test_forwarding(self):
- """ NAT44EI forwarding test """
+ """NAT44EI forwarding test"""
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
self.vapi.nat44_ei_forwarding_enable_disable(enable=1)
real_ip = self.pg0.remote_ip4
alias_ip = self.nat_addr
flags = self.config_flags.NAT44_EI_ADDR_ONLY_MAPPING
self.vapi.nat44_ei_add_del_static_mapping(
- is_add=1, local_ip_address=real_ip,
+ is_add=1,
+ local_ip_address=real_ip,
external_ip_address=alias_ip,
external_sw_if_index=0xFFFFFFFF,
- flags=flags)
+ flags=flags,
+ )
try:
# static mapping match
@@ -1269,9 +1333,9 @@ class TestNAT44EI(MethodHolder):
host0 = self.pg0.remote_hosts[0]
self.pg0.remote_hosts[0] = self.pg0.remote_hosts[1]
try:
- pkts = self.create_stream_out(self.pg1,
- dst_ip=self.pg0.remote_ip4,
- use_inside_ports=True)
+ pkts = self.create_stream_out(
+ self.pg1, dst_ip=self.pg0.remote_ip4, use_inside_ports=True
+ )
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1283,8 +1347,9 @@ class TestNAT44EI(MethodHolder):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out(capture, nat_ip=self.pg0.remote_ip4,
- same_port=True)
+ self.verify_capture_out(
+ capture, nat_ip=self.pg0.remote_ip4, same_port=True
+ )
finally:
self.pg0.remote_hosts[0] = host0
@@ -1296,10 +1361,11 @@ class TestNAT44EI(MethodHolder):
local_ip_address=real_ip,
external_ip_address=alias_ip,
external_sw_if_index=0xFFFFFFFF,
- flags=flags)
+ flags=flags,
+ )
def test_static_in(self):
- """ NAT44EI 1:1 NAT initialized from inside network """
+ """NAT44EI 1:1 NAT initialized from inside network"""
nat_ip = "10.0.0.10"
self.tcp_port_out = 6303
@@ -1309,14 +1375,14 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
sm = self.vapi.nat44_ei_static_mapping_dump()
self.assertEqual(len(sm), 1)
- self.assertEqual(sm[0].tag, '')
+ self.assertEqual(sm[0].tag, "")
self.assertEqual(sm[0].protocol, 0)
self.assertEqual(sm[0].local_port, 0)
self.assertEqual(sm[0].external_port, 0)
@@ -1338,7 +1404,7 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_in(capture, self.pg0)
def test_static_out(self):
- """ NAT44EI 1:1 NAT initialized from outside network """
+ """NAT44EI 1:1 NAT initialized from outside network"""
nat_ip = "10.0.0.20"
self.tcp_port_out = 6303
@@ -1349,11 +1415,11 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip, tag=tag)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
sm = self.vapi.nat44_ei_static_mapping_dump()
self.assertEqual(len(sm), 1)
self.assertEqual(sm[0].tag, tag)
@@ -1375,29 +1441,41 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_out(capture, nat_ip, True)
def test_static_with_port_in(self):
- """ NAT44EI 1:1 NAPT initialized from inside network """
+ """NAT44EI 1:1 NAPT initialized from inside network"""
self.tcp_port_out = 3606
self.udp_port_out = 3607
self.icmp_id_out = 3608
self.nat44_add_address(self.nat_addr)
- self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- self.tcp_port_in, self.tcp_port_out,
- proto=IP_PROTOS.tcp)
- self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- self.udp_port_in, self.udp_port_out,
- proto=IP_PROTOS.udp)
- self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- self.icmp_id_in, self.icmp_id_out,
- proto=IP_PROTOS.icmp)
+ self.nat44_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ self.tcp_port_in,
+ self.tcp_port_out,
+ proto=IP_PROTOS.tcp,
+ )
+ self.nat44_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ self.udp_port_in,
+ self.udp_port_out,
+ proto=IP_PROTOS.udp,
+ )
+ self.nat44_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ self.icmp_id_in,
+ self.icmp_id_out,
+ proto=IP_PROTOS.icmp,
+ )
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# in2out
pkts = self.create_stream_in(self.pg0, self.pg1)
@@ -1416,29 +1494,41 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_in(capture, self.pg0)
def test_static_with_port_out(self):
- """ NAT44EI 1:1 NAPT initialized from outside network """
+ """NAT44EI 1:1 NAPT initialized from outside network"""
self.tcp_port_out = 30606
self.udp_port_out = 30607
self.icmp_id_out = 30608
self.nat44_add_address(self.nat_addr)
- self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- self.tcp_port_in, self.tcp_port_out,
- proto=IP_PROTOS.tcp)
- self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- self.udp_port_in, self.udp_port_out,
- proto=IP_PROTOS.udp)
- self.nat44_add_static_mapping(self.pg0.remote_ip4, self.nat_addr,
- self.icmp_id_in, self.icmp_id_out,
- proto=IP_PROTOS.icmp)
+ self.nat44_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ self.tcp_port_in,
+ self.tcp_port_out,
+ proto=IP_PROTOS.tcp,
+ )
+ self.nat44_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ self.udp_port_in,
+ self.udp_port_out,
+ proto=IP_PROTOS.udp,
+ )
+ self.nat44_add_static_mapping(
+ self.pg0.remote_ip4,
+ self.nat_addr,
+ self.icmp_id_in,
+ self.icmp_id_out,
+ proto=IP_PROTOS.icmp,
+ )
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# out2in
pkts = self.create_stream_out(self.pg1)
@@ -1457,7 +1547,7 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_out(capture)
def test_static_vrf_aware(self):
- """ NAT44EI 1:1 NAT VRF awareness """
+ """NAT44EI 1:1 NAT VRF awareness"""
nat_ip1 = "10.0.0.30"
nat_ip2 = "10.0.0.40"
@@ -1465,20 +1555,18 @@ class TestNAT44EI(MethodHolder):
self.udp_port_out = 6304
self.icmp_id_out = 6305
- self.nat44_add_static_mapping(self.pg4.remote_ip4, nat_ip1,
- vrf_id=10)
- self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip2,
- vrf_id=10)
+ self.nat44_add_static_mapping(self.pg4.remote_ip4, nat_ip1, vrf_id=10)
+ self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip2, vrf_id=10)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg3.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg3.sw_if_index, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg4.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg4.sw_if_index, flags=flags, is_add=1
+ )
# inside interface VRF match NAT44EI static mapping VRF
pkts = self.create_stream_in(self.pg4, self.pg3)
@@ -1497,7 +1585,7 @@ class TestNAT44EI(MethodHolder):
self.pg3.assert_nothing_captured()
def test_dynamic_to_static(self):
- """ NAT44EI Switch from dynamic translation to 1:1NAT """
+ """NAT44EI Switch from dynamic translation to 1:1NAT"""
nat_ip = "10.0.0.10"
self.tcp_port_out = 6303
self.udp_port_out = 6304
@@ -1506,11 +1594,11 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# dynamic
pkts = self.create_stream_in(self.pg0, self.pg1)
@@ -1532,22 +1620,27 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_out(capture, nat_ip, True)
def test_identity_nat(self):
- """ NAT44EI Identity NAT """
+ """NAT44EI Identity NAT"""
flags = self.config_flags.NAT44_EI_ADDR_ONLY_MAPPING
self.vapi.nat44_ei_add_del_identity_mapping(
- ip_address=self.pg0.remote_ip4, sw_if_index=0xFFFFFFFF,
- flags=flags, is_add=1)
+ ip_address=self.pg0.remote_ip4,
+ sw_if_index=0xFFFFFFFF,
+ flags=flags,
+ is_add=1,
+ )
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
-
- p = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) /
- TCP(sport=12345, dport=56789))
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
+
+ p = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4)
+ / TCP(sport=12345, dport=56789)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1569,26 +1662,29 @@ class TestNAT44EI(MethodHolder):
self.assertEqual(len(sessions), 0)
flags = self.config_flags.NAT44_EI_ADDR_ONLY_MAPPING
self.vapi.nat44_ei_add_del_identity_mapping(
- ip_address=self.pg0.remote_ip4, sw_if_index=0xFFFFFFFF,
- flags=flags, vrf_id=1, is_add=1)
+ ip_address=self.pg0.remote_ip4,
+ sw_if_index=0xFFFFFFFF,
+ flags=flags,
+ vrf_id=1,
+ is_add=1,
+ )
identity_mappings = self.vapi.nat44_ei_identity_mapping_dump()
self.assertEqual(len(identity_mappings), 2)
def test_multiple_inside_interfaces(self):
- """ NAT44EI multiple non-overlapping address space inside interfaces
- """
+ """NAT44EI multiple non-overlapping address space inside interfaces"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg1.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg3.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg3.sw_if_index, is_add=1
+ )
# between two NAT44EI inside interfaces (no translation)
pkts = self.create_stream_in(self.pg0, self.pg1)
@@ -1639,26 +1735,24 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_in(capture, self.pg1)
def test_inside_overlapping_interfaces(self):
- """ NAT44EI multiple inside interfaces with overlapping address space
- """
+ """NAT44EI multiple inside interfaces with overlapping address space"""
static_nat_ip = "10.0.0.10"
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg3.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg3.sw_if_index, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg4.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg4.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg5.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg5.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg6.sw_if_index,
- flags=flags, is_add=1)
- self.nat44_add_static_mapping(self.pg6.remote_ip4, static_nat_ip,
- vrf_id=20)
+ sw_if_index=self.pg6.sw_if_index, flags=flags, is_add=1
+ )
+ self.nat44_add_static_mapping(self.pg6.remote_ip4, static_nat_ip, vrf_id=20)
# between NAT44EI inside interfaces with same VRF (no translation)
pkts = self.create_stream_in(self.pg4, self.pg5)
@@ -1669,9 +1763,11 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_no_translation(capture, self.pg4, self.pg5)
# between NAT44EI inside interfaces with different VRF (hairpinning)
- p = (Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac) /
- IP(src=self.pg4.remote_ip4, dst=static_nat_ip) /
- TCP(sport=1234, dport=5678))
+ p = (
+ Ether(src=self.pg4.remote_mac, dst=self.pg4.local_mac)
+ / IP(src=self.pg4.remote_ip4, dst=static_nat_ip)
+ / TCP(sport=1234, dport=5678)
+ )
self.pg4.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1723,16 +1819,12 @@ class TestNAT44EI(MethodHolder):
# pg5 session dump
addresses = self.vapi.nat44_ei_address_dump()
self.assertEqual(len(addresses), 1)
- sessions = self.vapi.nat44_ei_user_session_dump(
- self.pg5.remote_ip4, 10)
+ sessions = self.vapi.nat44_ei_user_session_dump(self.pg5.remote_ip4, 10)
self.assertEqual(len(sessions), 3)
for session in sessions:
- self.assertFalse(session.flags &
- self.config_flags.NAT44_EI_STATIC_MAPPING)
- self.assertEqual(str(session.inside_ip_address),
- self.pg5.remote_ip4)
- self.assertEqual(session.outside_ip_address,
- addresses[0].ip_address)
+ self.assertFalse(session.flags & self.config_flags.NAT44_EI_STATIC_MAPPING)
+ self.assertEqual(str(session.inside_ip_address), self.pg5.remote_ip4)
+ self.assertEqual(session.outside_ip_address, addresses[0].ip_address)
self.assertEqual(sessions[0].protocol, IP_PROTOS.tcp)
self.assertEqual(sessions[1].protocol, IP_PROTOS.udp)
self.assertEqual(sessions[2].protocol, IP_PROTOS.icmp)
@@ -1765,44 +1857,38 @@ class TestNAT44EI(MethodHolder):
addresses = self.vapi.nat44_ei_address_dump()
self.assertEqual(len(addresses), 1)
for user in users:
- sessions = self.vapi.nat44_ei_user_session_dump(user.ip_address,
- user.vrf_id)
+ sessions = self.vapi.nat44_ei_user_session_dump(
+ user.ip_address, user.vrf_id
+ )
for session in sessions:
self.assertEqual(user.ip_address, session.inside_ip_address)
self.assertTrue(session.total_bytes > session.total_pkts > 0)
- self.assertTrue(session.protocol in
- [IP_PROTOS.tcp, IP_PROTOS.udp,
- IP_PROTOS.icmp])
+ self.assertTrue(
+ session.protocol in [IP_PROTOS.tcp, IP_PROTOS.udp, IP_PROTOS.icmp]
+ )
# pg4 session dump
- sessions = self.vapi.nat44_ei_user_session_dump(
- self.pg4.remote_ip4, 10)
+ sessions = self.vapi.nat44_ei_user_session_dump(self.pg4.remote_ip4, 10)
self.assertGreaterEqual(len(sessions), 4)
for session in sessions:
- self.assertFalse(
- session.flags & self.config_flags.NAT44_EI_STATIC_MAPPING)
- self.assertEqual(str(session.inside_ip_address),
- self.pg4.remote_ip4)
- self.assertEqual(session.outside_ip_address,
- addresses[0].ip_address)
+ self.assertFalse(session.flags & self.config_flags.NAT44_EI_STATIC_MAPPING)
+ self.assertEqual(str(session.inside_ip_address), self.pg4.remote_ip4)
+ self.assertEqual(session.outside_ip_address, addresses[0].ip_address)
# pg6 session dump
- sessions = self.vapi.nat44_ei_user_session_dump(
- self.pg6.remote_ip4, 20)
+ sessions = self.vapi.nat44_ei_user_session_dump(self.pg6.remote_ip4, 20)
self.assertGreaterEqual(len(sessions), 3)
for session in sessions:
+ self.assertTrue(session.flags & self.config_flags.NAT44_EI_STATIC_MAPPING)
+ self.assertEqual(str(session.inside_ip_address), self.pg6.remote_ip4)
+ self.assertEqual(str(session.outside_ip_address), static_nat_ip)
self.assertTrue(
- session.flags & self.config_flags.NAT44_EI_STATIC_MAPPING)
- self.assertEqual(str(session.inside_ip_address),
- self.pg6.remote_ip4)
- self.assertEqual(str(session.outside_ip_address),
- static_nat_ip)
- self.assertTrue(session.inside_port in
- [self.tcp_port_in, self.udp_port_in,
- self.icmp_id_in])
+ session.inside_port
+ in [self.tcp_port_in, self.udp_port_in, self.icmp_id_in]
+ )
def test_hairpinning(self):
- """ NAT44EI hairpinning - 1:1 NAPT """
+ """NAT44EI hairpinning - 1:1 NAPT"""
host = self.pg0.remote_hosts[0]
server = self.pg0.remote_hosts[1]
@@ -1814,22 +1900,28 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# add static mapping for server
- self.nat44_add_static_mapping(server.ip4, self.nat_addr,
- server_in_port, server_out_port,
- proto=IP_PROTOS.tcp)
-
- cnt = self.statistics['/nat44-ei/hairpinning']
+ self.nat44_add_static_mapping(
+ server.ip4,
+ self.nat_addr,
+ server_in_port,
+ server_out_port,
+ proto=IP_PROTOS.tcp,
+ )
+
+ cnt = self.statistics["/nat44-ei/hairpinning"]
# send packet from host to server
- p = (Ether(src=host.mac, dst=self.pg0.local_mac) /
- IP(src=host.ip4, dst=self.nat_addr) /
- TCP(sport=host_in_port, dport=server_out_port))
+ p = (
+ Ether(src=host.mac, dst=self.pg0.local_mac)
+ / IP(src=host.ip4, dst=self.nat_addr)
+ / TCP(sport=host_in_port, dport=server_out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1848,14 +1940,16 @@ class TestNAT44EI(MethodHolder):
self.logger.error(ppp("Unexpected or invalid packet:", p))
raise
- after = self.statistics['/nat44-ei/hairpinning']
+ after = self.statistics["/nat44-ei/hairpinning"]
if_idx = self.pg0.sw_if_index
self.assertEqual(after[:, if_idx].sum() - cnt[:, if_idx].sum(), 1)
# send reply from server to host
- p = (Ether(src=server.mac, dst=self.pg0.local_mac) /
- IP(src=server.ip4, dst=self.nat_addr) /
- TCP(sport=server_in_port, dport=host_out_port))
+ p = (
+ Ether(src=server.mac, dst=self.pg0.local_mac)
+ / IP(src=server.ip4, dst=self.nat_addr)
+ / TCP(sport=server_in_port, dport=host_out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1873,13 +1967,15 @@ class TestNAT44EI(MethodHolder):
self.logger.error(ppp("Unexpected or invalid packet:", p))
raise
- after = self.statistics['/nat44-ei/hairpinning']
+ after = self.statistics["/nat44-ei/hairpinning"]
if_idx = self.pg0.sw_if_index
- self.assertEqual(after[:, if_idx].sum() - cnt[:, if_idx].sum(),
- 2+(1 if self.vpp_worker_count > 0 else 0))
+ self.assertEqual(
+ after[:, if_idx].sum() - cnt[:, if_idx].sum(),
+ 2 + (1 if self.vpp_worker_count > 0 else 0),
+ )
def test_hairpinning2(self):
- """ NAT44EI hairpinning - 1:1 NAT"""
+ """NAT44EI hairpinning - 1:1 NAT"""
server1_nat_ip = "10.0.0.10"
server2_nat_ip = "10.0.0.11"
@@ -1892,11 +1988,11 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# add static mapping for servers
self.nat44_add_static_mapping(server1.ip4, server1_nat_ip)
@@ -1904,17 +2000,23 @@ class TestNAT44EI(MethodHolder):
# host to server1
pkts = []
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=host.ip4, dst=server1_nat_ip) /
- TCP(sport=self.tcp_port_in, dport=server_tcp_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=host.ip4, dst=server1_nat_ip)
+ / TCP(sport=self.tcp_port_in, dport=server_tcp_port)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=host.ip4, dst=server1_nat_ip) /
- UDP(sport=self.udp_port_in, dport=server_udp_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=host.ip4, dst=server1_nat_ip)
+ / UDP(sport=self.udp_port_in, dport=server_udp_port)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=host.ip4, dst=server1_nat_ip) /
- ICMP(id=self.icmp_id_in, type='echo-request'))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=host.ip4, dst=server1_nat_ip)
+ / ICMP(id=self.icmp_id_in, type="echo-request")
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -1942,17 +2044,23 @@ class TestNAT44EI(MethodHolder):
# server1 to host
pkts = []
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=self.nat_addr) /
- TCP(sport=server_tcp_port, dport=self.tcp_port_out))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=self.nat_addr)
+ / TCP(sport=server_tcp_port, dport=self.tcp_port_out)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=self.nat_addr) /
- UDP(sport=server_udp_port, dport=self.udp_port_out))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=self.nat_addr)
+ / UDP(sport=server_udp_port, dport=self.udp_port_out)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=self.nat_addr) /
- ICMP(id=self.icmp_id_out, type='echo-reply'))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=self.nat_addr)
+ / ICMP(id=self.icmp_id_out, type="echo-reply")
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -1977,17 +2085,23 @@ class TestNAT44EI(MethodHolder):
# server2 to server1
pkts = []
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server2.ip4, dst=server1_nat_ip) /
- TCP(sport=self.tcp_port_in, dport=server_tcp_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server2.ip4, dst=server1_nat_ip)
+ / TCP(sport=self.tcp_port_in, dport=server_tcp_port)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server2.ip4, dst=server1_nat_ip) /
- UDP(sport=self.udp_port_in, dport=server_udp_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server2.ip4, dst=server1_nat_ip)
+ / UDP(sport=self.udp_port_in, dport=server_udp_port)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server2.ip4, dst=server1_nat_ip) /
- ICMP(id=self.icmp_id_in, type='echo-request'))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server2.ip4, dst=server1_nat_ip)
+ / ICMP(id=self.icmp_id_in, type="echo-request")
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -2015,17 +2129,23 @@ class TestNAT44EI(MethodHolder):
# server1 to server2
pkts = []
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=server2_nat_ip) /
- TCP(sport=server_tcp_port, dport=self.tcp_port_out))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=server2_nat_ip)
+ / TCP(sport=server_tcp_port, dport=self.tcp_port_out)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=server2_nat_ip) /
- UDP(sport=server_udp_port, dport=self.udp_port_out))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=server2_nat_ip)
+ / UDP(sport=server_udp_port, dport=self.udp_port_out)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=server2_nat_ip) /
- ICMP(id=self.icmp_id_out, type='echo-reply'))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=server2_nat_ip)
+ / ICMP(id=self.icmp_id_out, type="echo-reply")
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -2049,7 +2169,7 @@ class TestNAT44EI(MethodHolder):
raise
def test_hairpinning_avoid_inf_loop(self):
- """ NAT44EI hairpinning - 1:1 NAPT avoid infinite loop """
+ """NAT44EI hairpinning - 1:1 NAPT avoid infinite loop"""
host = self.pg0.remote_hosts[0]
server = self.pg0.remote_hosts[1]
@@ -2061,34 +2181,42 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# add static mapping for server
- self.nat44_add_static_mapping(server.ip4, self.nat_addr,
- server_in_port, server_out_port,
- proto=IP_PROTOS.tcp)
+ self.nat44_add_static_mapping(
+ server.ip4,
+ self.nat_addr,
+ server_in_port,
+ server_out_port,
+ proto=IP_PROTOS.tcp,
+ )
# add another static mapping that maps pg0.local_ip4 address to itself
self.nat44_add_static_mapping(self.pg0.local_ip4, self.pg0.local_ip4)
# send packet from host to VPP (the packet should get dropped)
- p = (Ether(src=host.mac, dst=self.pg0.local_mac) /
- IP(src=host.ip4, dst=self.pg0.local_ip4) /
- TCP(sport=host_in_port, dport=server_out_port))
+ p = (
+ Ether(src=host.mac, dst=self.pg0.local_mac)
+ / IP(src=host.ip4, dst=self.pg0.local_ip4)
+ / TCP(sport=host_in_port, dport=server_out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
# Here VPP used to crash due to an infinite loop
- cnt = self.statistics['/nat44-ei/hairpinning']
+ cnt = self.statistics["/nat44-ei/hairpinning"]
# send packet from host to server
- p = (Ether(src=host.mac, dst=self.pg0.local_mac) /
- IP(src=host.ip4, dst=self.nat_addr) /
- TCP(sport=host_in_port, dport=server_out_port))
+ p = (
+ Ether(src=host.mac, dst=self.pg0.local_mac)
+ / IP(src=host.ip4, dst=self.nat_addr)
+ / TCP(sport=host_in_port, dport=server_out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2107,14 +2235,16 @@ class TestNAT44EI(MethodHolder):
self.logger.error(ppp("Unexpected or invalid packet:", p))
raise
- after = self.statistics['/nat44-ei/hairpinning']
+ after = self.statistics["/nat44-ei/hairpinning"]
if_idx = self.pg0.sw_if_index
self.assertEqual(after[:, if_idx].sum() - cnt[:, if_idx].sum(), 1)
# send reply from server to host
- p = (Ether(src=server.mac, dst=self.pg0.local_mac) /
- IP(src=server.ip4, dst=self.nat_addr) /
- TCP(sport=server_in_port, dport=host_out_port))
+ p = (
+ Ether(src=server.mac, dst=self.pg0.local_mac)
+ / IP(src=server.ip4, dst=self.nat_addr)
+ / TCP(sport=server_in_port, dport=host_out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2132,16 +2262,18 @@ class TestNAT44EI(MethodHolder):
self.logger.error(ppp("Unexpected or invalid packet:", p))
raise
- after = self.statistics['/nat44-ei/hairpinning']
+ after = self.statistics["/nat44-ei/hairpinning"]
if_idx = self.pg0.sw_if_index
- self.assertEqual(after[:, if_idx].sum() - cnt[:, if_idx].sum(),
- 2+(1 if self.vpp_worker_count > 0 else 0))
+ self.assertEqual(
+ after[:, if_idx].sum() - cnt[:, if_idx].sum(),
+ 2 + (1 if self.vpp_worker_count > 0 else 0),
+ )
def test_interface_addr(self):
- """ NAT44EI acquire addresses from interface """
+ """NAT44EI acquire addresses from interface"""
self.vapi.nat44_ei_add_del_interface_addr(
- is_add=1,
- sw_if_index=self.pg7.sw_if_index)
+ is_add=1, sw_if_index=self.pg7.sw_if_index
+ )
# no address in NAT pool
addresses = self.vapi.nat44_ei_address_dump()
@@ -2159,22 +2291,20 @@ class TestNAT44EI(MethodHolder):
self.assertEqual(0, len(addresses))
def test_interface_addr_static_mapping(self):
- """ NAT44EI Static mapping with addresses from interface """
+ """NAT44EI Static mapping with addresses from interface"""
tag = "testTAG"
self.vapi.nat44_ei_add_del_interface_addr(
- is_add=1,
- sw_if_index=self.pg7.sw_if_index)
+ is_add=1, sw_if_index=self.pg7.sw_if_index
+ )
self.nat44_add_static_mapping(
- '1.2.3.4',
- external_sw_if_index=self.pg7.sw_if_index,
- tag=tag)
+ "1.2.3.4", external_sw_if_index=self.pg7.sw_if_index, tag=tag
+ )
# static mappings with external interface
static_mappings = self.vapi.nat44_ei_static_mapping_dump()
self.assertEqual(1, len(static_mappings))
- self.assertEqual(self.pg7.sw_if_index,
- static_mappings[0].external_sw_if_index)
+ self.assertEqual(self.pg7.sw_if_index, static_mappings[0].external_sw_if_index)
self.assertEqual(static_mappings[0].tag, tag)
# configure interface address and check static mappings
@@ -2184,8 +2314,7 @@ class TestNAT44EI(MethodHolder):
resolved = False
for sm in static_mappings:
if sm.external_sw_if_index == 0xFFFFFFFF:
- self.assertEqual(str(sm.external_ip_address),
- self.pg7.local_ip4)
+ self.assertEqual(str(sm.external_ip_address), self.pg7.local_ip4)
self.assertEqual(sm.tag, tag)
resolved = True
self.assertTrue(resolved)
@@ -2194,8 +2323,7 @@ class TestNAT44EI(MethodHolder):
self.pg7.unconfig_ip4()
static_mappings = self.vapi.nat44_ei_static_mapping_dump()
self.assertEqual(1, len(static_mappings))
- self.assertEqual(self.pg7.sw_if_index,
- static_mappings[0].external_sw_if_index)
+ self.assertEqual(self.pg7.sw_if_index, static_mappings[0].external_sw_if_index)
self.assertEqual(static_mappings[0].tag, tag)
# configure interface address again and check static mappings
@@ -2205,40 +2333,37 @@ class TestNAT44EI(MethodHolder):
resolved = False
for sm in static_mappings:
if sm.external_sw_if_index == 0xFFFFFFFF:
- self.assertEqual(str(sm.external_ip_address),
- self.pg7.local_ip4)
+ self.assertEqual(str(sm.external_ip_address), self.pg7.local_ip4)
self.assertEqual(sm.tag, tag)
resolved = True
self.assertTrue(resolved)
# remove static mapping
self.nat44_add_static_mapping(
- '1.2.3.4',
- external_sw_if_index=self.pg7.sw_if_index,
- tag=tag,
- is_add=0)
+ "1.2.3.4", external_sw_if_index=self.pg7.sw_if_index, tag=tag, is_add=0
+ )
static_mappings = self.vapi.nat44_ei_static_mapping_dump()
self.assertEqual(0, len(static_mappings))
def test_interface_addr_identity_nat(self):
- """ NAT44EI Identity NAT with addresses from interface """
+ """NAT44EI Identity NAT with addresses from interface"""
port = 53053
self.vapi.nat44_ei_add_del_interface_addr(
- is_add=1,
- sw_if_index=self.pg7.sw_if_index)
+ is_add=1, sw_if_index=self.pg7.sw_if_index
+ )
self.vapi.nat44_ei_add_del_identity_mapping(
- ip_address=b'0',
+ ip_address=b"0",
sw_if_index=self.pg7.sw_if_index,
port=port,
protocol=IP_PROTOS.tcp,
- is_add=1)
+ is_add=1,
+ )
# identity mappings with external interface
identity_mappings = self.vapi.nat44_ei_identity_mapping_dump()
self.assertEqual(1, len(identity_mappings))
- self.assertEqual(self.pg7.sw_if_index,
- identity_mappings[0].sw_if_index)
+ self.assertEqual(self.pg7.sw_if_index, identity_mappings[0].sw_if_index)
# configure interface address and check identity mappings
self.pg7.config_ip4()
@@ -2247,8 +2372,9 @@ class TestNAT44EI(MethodHolder):
self.assertEqual(2, len(identity_mappings))
for sm in identity_mappings:
if sm.sw_if_index == 0xFFFFFFFF:
- self.assertEqual(str(identity_mappings[0].ip_address),
- self.pg7.local_ip4)
+ self.assertEqual(
+ str(identity_mappings[0].ip_address), self.pg7.local_ip4
+ )
self.assertEqual(port, identity_mappings[0].port)
self.assertEqual(IP_PROTOS.tcp, identity_mappings[0].protocol)
resolved = True
@@ -2258,11 +2384,10 @@ class TestNAT44EI(MethodHolder):
self.pg7.unconfig_ip4()
identity_mappings = self.vapi.nat44_ei_identity_mapping_dump()
self.assertEqual(1, len(identity_mappings))
- self.assertEqual(self.pg7.sw_if_index,
- identity_mappings[0].sw_if_index)
+ self.assertEqual(self.pg7.sw_if_index, identity_mappings[0].sw_if_index)
def test_ipfix_nat44_sess(self):
- """ NAT44EI IPFIX logging NAT44EI session created/deleted """
+ """NAT44EI IPFIX logging NAT44EI session created/deleted"""
self.ipfix_domain_id = 10
self.ipfix_src_port = 20202
collector_port = 30303
@@ -2270,19 +2395,21 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
- self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4,
- src_address=self.pg3.local_ip4,
- path_mtu=512,
- template_interval=10,
- collector_port=collector_port)
- self.vapi.nat44_ei_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
- src_port=self.ipfix_src_port,
- enable=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
+ self.vapi.set_ipfix_exporter(
+ collector_address=self.pg3.remote_ip4,
+ src_address=self.pg3.local_ip4,
+ path_mtu=512,
+ template_interval=10,
+ collector_port=collector_port,
+ )
+ self.vapi.nat44_ei_ipfix_enable_disable(
+ domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=1
+ )
pkts = self.create_stream_in(self.pg0, self.pg1)
self.pg0.add_stream(pkts)
@@ -2301,8 +2428,7 @@ class TestNAT44EI(MethodHolder):
self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
self.assertEqual(p[UDP].sport, self.ipfix_src_port)
self.assertEqual(p[UDP].dport, collector_port)
- self.assertEqual(p[IPFIX].observationDomainID,
- self.ipfix_domain_id)
+ self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id)
if p.haslayer(Template):
ipfix.add_template(p.getlayer(Template))
# verify events in data set
@@ -2312,25 +2438,29 @@ class TestNAT44EI(MethodHolder):
self.verify_ipfix_nat44_ses(data)
def test_ipfix_addr_exhausted(self):
- """ NAT44EI IPFIX logging NAT addresses exhausted """
+ """NAT44EI IPFIX logging NAT addresses exhausted"""
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
- self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4,
- src_address=self.pg3.local_ip4,
- path_mtu=512,
- template_interval=10)
- self.vapi.nat44_ei_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
- src_port=self.ipfix_src_port,
- enable=1)
-
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=3025))
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
+ self.vapi.set_ipfix_exporter(
+ collector_address=self.pg3.remote_ip4,
+ src_address=self.pg3.local_ip4,
+ path_mtu=512,
+ template_interval=10,
+ )
+ self.vapi.nat44_ei_ipfix_enable_disable(
+ domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=1
+ )
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=3025)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2345,8 +2475,7 @@ class TestNAT44EI(MethodHolder):
self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
self.assertEqual(p[UDP].sport, self.ipfix_src_port)
self.assertEqual(p[UDP].dport, 4739)
- self.assertEqual(p[IPFIX].observationDomainID,
- self.ipfix_domain_id)
+ self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id)
if p.haslayer(Template):
ipfix.add_template(p.getlayer(Template))
# verify events in data set
@@ -2356,15 +2485,15 @@ class TestNAT44EI(MethodHolder):
self.verify_ipfix_addr_exhausted(data)
def test_ipfix_max_sessions(self):
- """ NAT44EI IPFIX logging maximum session entries exceeded """
+ """NAT44EI IPFIX logging maximum session entries exceeded"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
max_sessions_per_thread = self.max_translations
max_sessions = max(1, self.vpp_worker_count) * max_sessions_per_thread
@@ -2372,26 +2501,32 @@ class TestNAT44EI(MethodHolder):
pkts = []
for i in range(0, max_sessions):
src = "10.10.%u.%u" % ((i & 0xFF00) >> 8, i & 0xFF)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=src, dst=self.pg1.remote_ip4) /
- TCP(sport=1025))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=src, dst=self.pg1.remote_ip4)
+ / TCP(sport=1025)
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
self.pg1.get_capture(max_sessions)
- self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4,
- src_address=self.pg3.local_ip4,
- path_mtu=512,
- template_interval=10)
- self.vapi.nat44_ei_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
- src_port=self.ipfix_src_port,
- enable=1)
-
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=1025))
+ self.vapi.set_ipfix_exporter(
+ collector_address=self.pg3.remote_ip4,
+ src_address=self.pg3.local_ip4,
+ path_mtu=512,
+ template_interval=10,
+ )
+ self.vapi.nat44_ei_ipfix_enable_disable(
+ domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=1
+ )
+
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=1025)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2406,8 +2541,7 @@ class TestNAT44EI(MethodHolder):
self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
self.assertEqual(p[UDP].sport, self.ipfix_src_port)
self.assertEqual(p[UDP].dport, 4739)
- self.assertEqual(p[IPFIX].observationDomainID,
- self.ipfix_domain_id)
+ self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id)
if p.haslayer(Template):
ipfix.add_template(p.getlayer(Template))
# verify events in data set
@@ -2417,22 +2551,23 @@ class TestNAT44EI(MethodHolder):
self.verify_ipfix_max_sessions(data, max_sessions_per_thread)
def test_syslog_apmap(self):
- """ NAT44EI syslog address and port mapping creation and deletion """
- self.vapi.syslog_set_filter(
- self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_INFO)
+ """NAT44EI syslog address and port mapping creation and deletion"""
+ self.vapi.syslog_set_filter(self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_INFO)
self.vapi.syslog_set_sender(self.pg3.local_ip4, self.pg3.remote_ip4)
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
-
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=20))
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
+
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=self.tcp_port_in, dport=20)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2448,22 +2583,25 @@ class TestNAT44EI(MethodHolder):
self.verify_syslog_apmap(capture[0][Raw].load, False)
def test_pool_addr_fib(self):
- """ NAT44EI add pool addresses to FIB """
- static_addr = '10.0.0.10'
+ """NAT44EI add pool addresses to FIB"""
+ static_addr = "10.0.0.10"
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
self.nat44_add_static_mapping(self.pg0.remote_ip4, static_addr)
# NAT44EI address
- p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') /
- ARP(op=ARP.who_has, pdst=self.nat_addr,
- psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac))
+ p = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op=ARP.who_has,
+ pdst=self.nat_addr,
+ psrc=self.pg1.remote_ip4,
+ hwsrc=self.pg1.remote_mac,
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2472,9 +2610,12 @@ class TestNAT44EI(MethodHolder):
self.assertTrue(capture[0][ARP].op, ARP.is_at)
# 1:1 NAT address
- p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') /
- ARP(op=ARP.who_has, pdst=static_addr,
- psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac))
+ p = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op=ARP.who_has,
+ pdst=static_addr,
+ psrc=self.pg1.remote_ip4,
+ hwsrc=self.pg1.remote_mac,
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2483,9 +2624,12 @@ class TestNAT44EI(MethodHolder):
self.assertTrue(capture[0][ARP].op, ARP.is_at)
# send ARP to non-NAT44EI interface
- p = (Ether(src=self.pg2.remote_mac, dst='ff:ff:ff:ff:ff:ff') /
- ARP(op=ARP.who_has, pdst=self.nat_addr,
- psrc=self.pg2.remote_ip4, hwsrc=self.pg2.remote_mac))
+ p = Ether(src=self.pg2.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op=ARP.who_has,
+ pdst=self.nat_addr,
+ psrc=self.pg2.remote_ip4,
+ hwsrc=self.pg2.remote_mac,
+ )
self.pg2.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2493,27 +2637,32 @@ class TestNAT44EI(MethodHolder):
# remove addresses and verify
self.nat44_add_address(self.nat_addr, is_add=0)
- self.nat44_add_static_mapping(self.pg0.remote_ip4, static_addr,
- is_add=0)
-
- p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') /
- ARP(op=ARP.who_has, pdst=self.nat_addr,
- psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac))
+ self.nat44_add_static_mapping(self.pg0.remote_ip4, static_addr, is_add=0)
+
+ p = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op=ARP.who_has,
+ pdst=self.nat_addr,
+ psrc=self.pg1.remote_ip4,
+ hwsrc=self.pg1.remote_mac,
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
self.pg1.assert_nothing_captured()
- p = (Ether(src=self.pg1.remote_mac, dst='ff:ff:ff:ff:ff:ff') /
- ARP(op=ARP.who_has, pdst=static_addr,
- psrc=self.pg1.remote_ip4, hwsrc=self.pg1.remote_mac))
+ p = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op=ARP.who_has,
+ pdst=static_addr,
+ psrc=self.pg1.remote_ip4,
+ hwsrc=self.pg1.remote_mac,
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
self.pg1.assert_nothing_captured()
def test_vrf_mode(self):
- """ NAT44EI tenant VRF aware address pool mode """
+ """NAT44EI tenant VRF aware address pool mode"""
vrf_id1 = 1
vrf_id2 = 2
@@ -2522,8 +2671,8 @@ class TestNAT44EI(MethodHolder):
self.pg0.unconfig_ip4()
self.pg1.unconfig_ip4()
- self.vapi.ip_table_add_del(is_add=1, table={'table_id': vrf_id1})
- self.vapi.ip_table_add_del(is_add=1, table={'table_id': vrf_id2})
+ self.vapi.ip_table_add_del(is_add=1, table={"table_id": vrf_id1})
+ self.vapi.ip_table_add_del(is_add=1, table={"table_id": vrf_id2})
self.pg0.set_table_ip4(vrf_id1)
self.pg1.set_table_ip4(vrf_id2)
self.pg0.config_ip4()
@@ -2535,14 +2684,14 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_address(nat_ip2, vrf_id=vrf_id2)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg1.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg2.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg2.sw_if_index, is_add=1
+ )
try:
# first VRF
@@ -2570,11 +2719,11 @@ class TestNAT44EI(MethodHolder):
self.pg1.config_ip4()
self.pg0.resolve_arp()
self.pg1.resolve_arp()
- self.vapi.ip_table_add_del(is_add=0, table={'table_id': vrf_id1})
- self.vapi.ip_table_add_del(is_add=0, table={'table_id': vrf_id2})
+ self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id1})
+ self.vapi.ip_table_add_del(is_add=0, table={"table_id": vrf_id2})
def test_vrf_feature_independent(self):
- """ NAT44EI tenant VRF independent address pool mode """
+ """NAT44EI tenant VRF independent address pool mode"""
nat_ip1 = "10.0.0.10"
nat_ip2 = "10.0.0.11"
@@ -2583,14 +2732,14 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_address(nat_ip2, vrf_id=99)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg1.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg2.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg2.sw_if_index, is_add=1
+ )
# first VRF
pkts = self.create_stream_in(self.pg0, self.pg2)
@@ -2609,16 +2758,16 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_out(capture, nat_ip1)
def test_dynamic_ipless_interfaces(self):
- """ NAT44EI interfaces without configured IP address """
+ """NAT44EI interfaces without configured IP address"""
self.create_routes_and_neigbors()
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg7.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg7.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg8.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg8.sw_if_index, is_add=1
+ )
# in2out
pkts = self.create_stream_in(self.pg7, self.pg8)
@@ -2637,17 +2786,17 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_in(capture, self.pg7)
def test_static_ipless_interfaces(self):
- """ NAT44EI interfaces without configured IP address - 1:1 NAT """
+ """NAT44EI interfaces without configured IP address - 1:1 NAT"""
self.create_routes_and_neigbors()
self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg7.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg7.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg8.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg8.sw_if_index, is_add=1
+ )
# out2in
pkts = self.create_stream_out(self.pg8)
@@ -2666,7 +2815,7 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_out(capture, self.nat_addr, True)
def test_static_with_port_ipless_interfaces(self):
- """ NAT44EI interfaces without configured IP address - 1:1 NAPT """
+ """NAT44EI interfaces without configured IP address - 1:1 NAPT"""
self.tcp_port_out = 30606
self.udp_port_out = 30607
@@ -2674,22 +2823,34 @@ class TestNAT44EI(MethodHolder):
self.create_routes_and_neigbors()
self.nat44_add_address(self.nat_addr)
- self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr,
- self.tcp_port_in, self.tcp_port_out,
- proto=IP_PROTOS.tcp)
- self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr,
- self.udp_port_in, self.udp_port_out,
- proto=IP_PROTOS.udp)
- self.nat44_add_static_mapping(self.pg7.remote_ip4, self.nat_addr,
- self.icmp_id_in, self.icmp_id_out,
- proto=IP_PROTOS.icmp)
+ self.nat44_add_static_mapping(
+ self.pg7.remote_ip4,
+ self.nat_addr,
+ self.tcp_port_in,
+ self.tcp_port_out,
+ proto=IP_PROTOS.tcp,
+ )
+ self.nat44_add_static_mapping(
+ self.pg7.remote_ip4,
+ self.nat_addr,
+ self.udp_port_in,
+ self.udp_port_out,
+ proto=IP_PROTOS.udp,
+ )
+ self.nat44_add_static_mapping(
+ self.pg7.remote_ip4,
+ self.nat_addr,
+ self.icmp_id_in,
+ self.icmp_id_out,
+ proto=IP_PROTOS.icmp,
+ )
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg7.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg7.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg8.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg8.sw_if_index, is_add=1
+ )
# out2in
pkts = self.create_stream_out(self.pg8)
@@ -2708,23 +2869,25 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_out(capture)
def test_static_unknown_proto(self):
- """ NAT44EI 1:1 translate packet with unknown protocol """
+ """NAT44EI 1:1 translate packet with unknown protocol"""
nat_ip = "10.0.0.10"
self.nat44_add_static_mapping(self.pg0.remote_ip4, nat_ip)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# in2out
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- GRE() /
- IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / GRE()
+ / IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2740,11 +2903,13 @@ class TestNAT44EI(MethodHolder):
raise
# out2in
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=nat_ip) /
- GRE() /
- IP(src=self.pg3.remote_ip4, dst=self.pg2.remote_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=nat_ip)
+ / GRE()
+ / IP(src=self.pg3.remote_ip4, dst=self.pg2.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2760,8 +2925,7 @@ class TestNAT44EI(MethodHolder):
raise
def test_hairpinning_static_unknown_proto(self):
- """ NAT44EI 1:1 translate packet with unknown protocol - hairpinning
- """
+ """NAT44EI 1:1 translate packet with unknown protocol - hairpinning"""
host = self.pg0.remote_hosts[0]
server = self.pg0.remote_hosts[1]
@@ -2773,18 +2937,20 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_static_mapping(server.ip4, server_nat_ip)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# host to server
- p = (Ether(dst=self.pg0.local_mac, src=host.mac) /
- IP(src=host.ip4, dst=server_nat_ip) /
- GRE() /
- IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=host.mac)
+ / IP(src=host.ip4, dst=server_nat_ip)
+ / GRE()
+ / IP(src=self.pg2.remote_ip4, dst=self.pg3.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2800,11 +2966,13 @@ class TestNAT44EI(MethodHolder):
raise
# server to host
- p = (Ether(dst=self.pg0.local_mac, src=server.mac) /
- IP(src=server.ip4, dst=host_nat_ip) /
- GRE() /
- IP(src=self.pg3.remote_ip4, dst=self.pg2.remote_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=server.mac)
+ / IP(src=server.ip4, dst=host_nat_ip)
+ / GRE()
+ / IP(src=self.pg3.remote_ip4, dst=self.pg2.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2820,10 +2988,11 @@ class TestNAT44EI(MethodHolder):
raise
def test_output_feature(self):
- """ NAT44EI output feature (in2out postrouting) """
+ """NAT44EI output feature (in2out postrouting)"""
self.nat44_add_address(self.nat_addr)
self.vapi.nat44_ei_add_del_output_interface(
- sw_if_index=self.pg3.sw_if_index, is_add=1)
+ sw_if_index=self.pg3.sw_if_index, is_add=1
+ )
# in2out
pkts = self.create_stream_in(self.pg0, self.pg3)
@@ -2850,25 +3019,32 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_no_translation(capture, self.pg2, self.pg0)
def test_output_feature_vrf_aware(self):
- """ NAT44EI output feature VRF aware (in2out postrouting) """
+ """NAT44EI output feature VRF aware (in2out postrouting)"""
nat_ip_vrf10 = "10.0.0.10"
nat_ip_vrf20 = "10.0.0.20"
- r1 = VppIpRoute(self, self.pg3.remote_ip4, 32,
- [VppRoutePath(self.pg3.remote_ip4,
- self.pg3.sw_if_index)],
- table_id=10)
- r2 = VppIpRoute(self, self.pg3.remote_ip4, 32,
- [VppRoutePath(self.pg3.remote_ip4,
- self.pg3.sw_if_index)],
- table_id=20)
+ r1 = VppIpRoute(
+ self,
+ self.pg3.remote_ip4,
+ 32,
+ [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)],
+ table_id=10,
+ )
+ r2 = VppIpRoute(
+ self,
+ self.pg3.remote_ip4,
+ 32,
+ [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)],
+ table_id=20,
+ )
r1.add_vpp_config()
r2.add_vpp_config()
self.nat44_add_address(nat_ip_vrf10, vrf_id=10)
self.nat44_add_address(nat_ip_vrf20, vrf_id=20)
self.vapi.nat44_ei_add_del_output_interface(
- sw_if_index=self.pg3.sw_if_index, is_add=1)
+ sw_if_index=self.pg3.sw_if_index, is_add=1
+ )
# in2out VRF 10
pkts = self.create_stream_in(self.pg4, self.pg3)
@@ -2903,7 +3079,7 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_in(capture, self.pg6)
def test_output_feature_hairpinning(self):
- """ NAT44EI output feature hairpinning (in2out postrouting) """
+ """NAT44EI output feature hairpinning (in2out postrouting)"""
host = self.pg0.remote_hosts[0]
server = self.pg0.remote_hosts[1]
host_in_port = 1234
@@ -2913,19 +3089,27 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_address(self.nat_addr)
self.vapi.nat44_ei_add_del_output_interface(
- sw_if_index=self.pg0.sw_if_index, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, is_add=1
+ )
self.vapi.nat44_ei_add_del_output_interface(
- sw_if_index=self.pg1.sw_if_index, is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# add static mapping for server
- self.nat44_add_static_mapping(server.ip4, self.nat_addr,
- server_in_port, server_out_port,
- proto=IP_PROTOS.tcp)
+ self.nat44_add_static_mapping(
+ server.ip4,
+ self.nat_addr,
+ server_in_port,
+ server_out_port,
+ proto=IP_PROTOS.tcp,
+ )
# send packet from host to server
- p = (Ether(src=host.mac, dst=self.pg0.local_mac) /
- IP(src=host.ip4, dst=self.nat_addr) /
- TCP(sport=host_in_port, dport=server_out_port))
+ p = (
+ Ether(src=host.mac, dst=self.pg0.local_mac)
+ / IP(src=host.ip4, dst=self.nat_addr)
+ / TCP(sport=host_in_port, dport=server_out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2945,9 +3129,11 @@ class TestNAT44EI(MethodHolder):
raise
# send reply from server to host
- p = (Ether(src=server.mac, dst=self.pg0.local_mac) /
- IP(src=server.ip4, dst=self.nat_addr) /
- TCP(sport=server_in_port, dport=host_out_port))
+ p = (
+ Ether(src=server.mac, dst=self.pg0.local_mac)
+ / IP(src=server.ip4, dst=self.nat_addr)
+ / TCP(sport=server_in_port, dport=host_out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -2966,7 +3152,7 @@ class TestNAT44EI(MethodHolder):
raise
def test_one_armed_nat44(self):
- """ NAT44EI One armed NAT """
+ """NAT44EI One armed NAT"""
remote_host = self.pg9.remote_hosts[0]
local_host = self.pg9.remote_hosts[1]
external_port = 0
@@ -2974,16 +3160,18 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg9.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg9.sw_if_index, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg9.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg9.sw_if_index, flags=flags, is_add=1
+ )
# in2out
- p = (Ether(src=self.pg9.remote_mac, dst=self.pg9.local_mac) /
- IP(src=local_host.ip4, dst=remote_host.ip4) /
- TCP(sport=12345, dport=80))
+ p = (
+ Ether(src=self.pg9.remote_mac, dst=self.pg9.local_mac)
+ / IP(src=local_host.ip4, dst=remote_host.ip4)
+ / TCP(sport=12345, dport=80)
+ )
self.pg9.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3003,9 +3191,11 @@ class TestNAT44EI(MethodHolder):
raise
# out2in
- p = (Ether(src=self.pg9.remote_mac, dst=self.pg9.local_mac) /
- IP(src=remote_host.ip4, dst=self.nat_addr) /
- TCP(sport=80, dport=external_port))
+ p = (
+ Ether(src=self.pg9.remote_mac, dst=self.pg9.local_mac)
+ / IP(src=remote_host.ip4, dst=self.nat_addr)
+ / TCP(sport=80, dport=external_port)
+ )
self.pg9.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3028,21 +3218,21 @@ class TestNAT44EI(MethodHolder):
else:
node = "nat44-ei-classify"
- err = self.statistics.get_err_counter('/err/%s/next in2out' % node)
+ err = self.statistics.get_err_counter("/err/%s/next in2out" % node)
self.assertEqual(err, 1)
- err = self.statistics.get_err_counter('/err/%s/next out2in' % node)
+ err = self.statistics.get_err_counter("/err/%s/next out2in" % node)
self.assertEqual(err, 1)
def test_del_session(self):
- """ NAT44EI delete session """
+ """NAT44EI delete session"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
pkts = self.create_stream_in(self.pg0, self.pg1)
self.pg0.add_stream(pkts)
@@ -3057,12 +3247,14 @@ class TestNAT44EI(MethodHolder):
address=sessions[0].inside_ip_address,
port=sessions[0].inside_port,
protocol=sessions[0].protocol,
- flags=self.config_flags.NAT44_EI_IF_INSIDE)
+ flags=self.config_flags.NAT44_EI_IF_INSIDE,
+ )
self.vapi.nat44_ei_del_session(
address=sessions[1].outside_ip_address,
port=sessions[1].outside_port,
- protocol=sessions[1].protocol)
+ protocol=sessions[1].protocol,
+ )
sessions = self.vapi.nat44_ei_user_session_dump(self.pg0.remote_ip4, 0)
self.assertEqual(nsessions - len(sessions), 2)
@@ -3071,60 +3263,56 @@ class TestNAT44EI(MethodHolder):
address=sessions[0].inside_ip_address,
port=sessions[0].inside_port,
protocol=sessions[0].protocol,
- flags=self.config_flags.NAT44_EI_IF_INSIDE)
+ flags=self.config_flags.NAT44_EI_IF_INSIDE,
+ )
self.verify_no_nat44_user()
def test_frag_in_order(self):
- """ NAT44EI translate fragments arriving in order """
+ """NAT44EI translate fragments arriving in order"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
self.frag_in_order(proto=IP_PROTOS.tcp)
self.frag_in_order(proto=IP_PROTOS.udp)
self.frag_in_order(proto=IP_PROTOS.icmp)
def test_frag_forwarding(self):
- """ NAT44EI forwarding fragment test """
+ """NAT44EI forwarding fragment test"""
self.vapi.nat44_ei_add_del_interface_addr(
- is_add=1,
- sw_if_index=self.pg1.sw_if_index)
+ is_add=1, sw_if_index=self.pg1.sw_if_index
+ )
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
self.vapi.nat44_ei_forwarding_enable_disable(enable=1)
data = b"A" * 16 + b"B" * 16 + b"C" * 3
- pkts = self.create_stream_frag(self.pg1,
- self.pg0.remote_ip4,
- 4789,
- 4789,
- data,
- proto=IP_PROTOS.udp)
+ pkts = self.create_stream_frag(
+ self.pg1, self.pg0.remote_ip4, 4789, 4789, data, proto=IP_PROTOS.udp
+ )
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg0.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- self.pg1.remote_ip4,
- self.pg0.remote_ip4)
+ p = self.reass_frags_and_verify(frags, self.pg1.remote_ip4, self.pg0.remote_ip4)
self.assertEqual(p[UDP].sport, 4789)
self.assertEqual(p[UDP].dport, 4789)
self.assertEqual(data, p[Raw].load)
def test_reass_hairpinning(self):
- """ NAT44EI fragments hairpinning """
+ """NAT44EI fragments hairpinning"""
server_addr = self.pg0.remote_hosts[1].ip4
host_in_port = random.randint(1025, 65535)
@@ -3134,63 +3322,85 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# add static mapping for server
- self.nat44_add_static_mapping(server_addr, self.nat_addr,
- server_in_port,
- server_out_port,
- proto=IP_PROTOS.tcp)
- self.nat44_add_static_mapping(server_addr, self.nat_addr,
- server_in_port,
- server_out_port,
- proto=IP_PROTOS.udp)
+ self.nat44_add_static_mapping(
+ server_addr,
+ self.nat_addr,
+ server_in_port,
+ server_out_port,
+ proto=IP_PROTOS.tcp,
+ )
+ self.nat44_add_static_mapping(
+ server_addr,
+ self.nat_addr,
+ server_in_port,
+ server_out_port,
+ proto=IP_PROTOS.udp,
+ )
self.nat44_add_static_mapping(server_addr, self.nat_addr)
- self.reass_hairpinning(server_addr, server_in_port, server_out_port,
- host_in_port, proto=IP_PROTOS.tcp)
- self.reass_hairpinning(server_addr, server_in_port, server_out_port,
- host_in_port, proto=IP_PROTOS.udp)
- self.reass_hairpinning(server_addr, server_in_port, server_out_port,
- host_in_port, proto=IP_PROTOS.icmp)
+ self.reass_hairpinning(
+ server_addr,
+ server_in_port,
+ server_out_port,
+ host_in_port,
+ proto=IP_PROTOS.tcp,
+ )
+ self.reass_hairpinning(
+ server_addr,
+ server_in_port,
+ server_out_port,
+ host_in_port,
+ proto=IP_PROTOS.udp,
+ )
+ self.reass_hairpinning(
+ server_addr,
+ server_in_port,
+ server_out_port,
+ host_in_port,
+ proto=IP_PROTOS.icmp,
+ )
def test_frag_out_of_order(self):
- """ NAT44EI translate fragments arriving out of order """
+ """NAT44EI translate fragments arriving out of order"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
self.frag_out_of_order(proto=IP_PROTOS.tcp)
self.frag_out_of_order(proto=IP_PROTOS.udp)
self.frag_out_of_order(proto=IP_PROTOS.icmp)
def test_port_restricted(self):
- """ NAT44EI Port restricted NAT44EI (MAP-E CE) """
+ """NAT44EI Port restricted NAT44EI (MAP-E CE)"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
- self.vapi.nat44_ei_set_addr_and_port_alloc_alg(alg=1,
- psid_offset=6,
- psid_length=6,
- psid=10)
-
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=4567, dport=22))
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
+ self.vapi.nat44_ei_set_addr_and_port_alloc_alg(
+ alg=1, psid_offset=6, psid_length=6, psid=10
+ )
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=4567, dport=22)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3210,24 +3420,26 @@ class TestNAT44EI(MethodHolder):
raise
def test_port_range(self):
- """ NAT44EI External address port range """
+ """NAT44EI External address port range"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
- self.vapi.nat44_ei_set_addr_and_port_alloc_alg(alg=2,
- start_port=1025,
- end_port=1027)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
+ self.vapi.nat44_ei_set_addr_and_port_alloc_alg(
+ alg=2, start_port=1025, end_port=1027
+ )
pkts = []
for port in range(0, 5):
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=1125 + port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(sport=1125 + port)
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -3239,14 +3451,14 @@ class TestNAT44EI(MethodHolder):
self.assertLessEqual(tcp.sport, 1027)
def test_multiple_outside_vrf(self):
- """ NAT44EI Multiple outside VRF """
+ """NAT44EI Multiple outside VRF"""
vrf_id1 = 1
vrf_id2 = 2
self.pg1.unconfig_ip4()
self.pg2.unconfig_ip4()
- self.vapi.ip_table_add_del(is_add=1, table={'table_id': vrf_id1})
- self.vapi.ip_table_add_del(is_add=1, table={'table_id': vrf_id2})
+ self.vapi.ip_table_add_del(is_add=1, table={"table_id": vrf_id1})
+ self.vapi.ip_table_add_del(is_add=1, table={"table_id": vrf_id2})
self.pg1.set_table_ip4(vrf_id1)
self.pg2.set_table_ip4(vrf_id2)
self.pg1.config_ip4()
@@ -3257,14 +3469,14 @@ class TestNAT44EI(MethodHolder):
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg2.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg2.sw_if_index, is_add=1
+ )
try:
# first VRF
@@ -3313,20 +3525,26 @@ class TestNAT44EI(MethodHolder):
self.pg2.resolve_arp()
def test_mss_clamping(self):
- """ NAT44EI TCP MSS clamping """
+ """NAT44EI TCP MSS clamping"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
-
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port,
- flags="S", options=[('MSS', 1400)]))
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / TCP(
+ sport=self.tcp_port_in,
+ dport=self.tcp_external_port,
+ flags="S",
+ options=[("MSS", 1400)],
+ )
+ )
self.vapi.nat44_ei_set_mss_clamping(enable=1, mss_value=1000)
self.pg0.add_stream(p)
@@ -3353,21 +3571,22 @@ class TestNAT44EI(MethodHolder):
self.verify_mss_value(capture[0], 1400)
def test_ha_send(self):
- """ NAT44EI Send HA session synchronization events (active) """
+ """NAT44EI Send HA session synchronization events (active)"""
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
self.nat44_add_address(self.nat_addr)
self.vapi.nat44_ei_ha_set_listener(
- ip_address=self.pg3.local_ip4, port=12345, path_mtu=512)
+ ip_address=self.pg3.local_ip4, port=12345, path_mtu=512
+ )
self.vapi.nat44_ei_ha_set_failover(
- ip_address=self.pg3.remote_ip4, port=12346,
- session_refresh_interval=10)
+ ip_address=self.pg3.remote_ip4, port=12346, session_refresh_interval=10
+ )
bind_layers(UDP, HANATStateSync, sport=12345)
# create sessions
@@ -3379,7 +3598,7 @@ class TestNAT44EI(MethodHolder):
self.verify_capture_out(capture)
# active send HA events
self.vapi.nat44_ei_ha_flush()
- stats = self.statistics['/nat44-ei/ha/add-event-send']
+ stats = self.statistics["/nat44-ei/ha/add-event-send"]
self.assertEqual(stats[:, 0].sum(), 3)
capture = self.pg3.get_capture(1)
p = capture[0]
@@ -3407,23 +3626,29 @@ class TestNAT44EI(MethodHolder):
self.assertEqual(event.fib_index, 0)
# ACK received events
- ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
- UDP(sport=12346, dport=12345) /
- HANATStateSync(sequence_number=seq, flags='ACK',
- thread_index=hanat.thread_index))
+ ack = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4)
+ / UDP(sport=12346, dport=12345)
+ / HANATStateSync(
+ sequence_number=seq, flags="ACK", thread_index=hanat.thread_index
+ )
+ )
self.pg3.add_stream(ack)
self.pg_start()
- stats = self.statistics['/nat44-ei/ha/ack-recv']
+ stats = self.statistics["/nat44-ei/ha/ack-recv"]
self.assertEqual(stats[:, 0].sum(), 1)
# delete one session
self.pg_enable_capture(self.pg_interfaces)
self.vapi.nat44_ei_del_session(
- address=self.pg0.remote_ip4, port=self.tcp_port_in,
- protocol=IP_PROTOS.tcp, flags=self.config_flags.NAT44_EI_IF_INSIDE)
+ address=self.pg0.remote_ip4,
+ port=self.tcp_port_in,
+ protocol=IP_PROTOS.tcp,
+ flags=self.config_flags.NAT44_EI_IF_INSIDE,
+ )
self.vapi.nat44_ei_ha_flush()
- stats = self.statistics['/nat44-ei/ha/del-event-send']
+ stats = self.statistics["/nat44-ei/ha/del-event-send"]
self.assertEqual(stats[:, 0].sum(), 1)
capture = self.pg3.get_capture(1)
p = capture[0]
@@ -3438,9 +3663,9 @@ class TestNAT44EI(MethodHolder):
# do not send ACK, active retry send HA event again
self.pg_enable_capture(self.pg_interfaces)
self.virtual_sleep(12)
- stats = self.statistics['/nat44-ei/ha/retry-count']
+ stats = self.statistics["/nat44-ei/ha/retry-count"]
self.assertEqual(stats[:, 0].sum(), 3)
- stats = self.statistics['/nat44-ei/ha/missed-count']
+ stats = self.statistics["/nat44-ei/ha/missed-count"]
self.assertEqual(stats[:, 0].sum(), 1)
capture = self.pg3.get_capture(3)
for packet in capture:
@@ -3453,7 +3678,7 @@ class TestNAT44EI(MethodHolder):
self.pg_start()
self.pg0.get_capture(2)
self.vapi.nat44_ei_ha_flush()
- stats = self.statistics['/nat44-ei/ha/refresh-event-send']
+ stats = self.statistics["/nat44-ei/ha/refresh-event-send"]
self.assertEqual(stats[:, 0].sum(), 2)
capture = self.pg3.get_capture(1)
p = capture[0]
@@ -3480,29 +3705,33 @@ class TestNAT44EI(MethodHolder):
self.assertEqual(event.total_pkts, 2)
self.assertGreater(event.total_bytes, 0)
- stats = self.statistics['/nat44-ei/ha/ack-recv']
- ack = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
- UDP(sport=12346, dport=12345) /
- HANATStateSync(sequence_number=seq, flags='ACK',
- thread_index=hanat.thread_index))
+ stats = self.statistics["/nat44-ei/ha/ack-recv"]
+ ack = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4)
+ / UDP(sport=12346, dport=12345)
+ / HANATStateSync(
+ sequence_number=seq, flags="ACK", thread_index=hanat.thread_index
+ )
+ )
self.pg3.add_stream(ack)
self.pg_start()
- stats = self.statistics['/nat44-ei/ha/ack-recv']
+ stats = self.statistics["/nat44-ei/ha/ack-recv"]
self.assertEqual(stats[:, 0].sum(), 2)
def test_ha_recv(self):
- """ NAT44EI Receive HA session synchronization events (passive) """
+ """NAT44EI Receive HA session synchronization events (passive)"""
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
- self.vapi.nat44_ei_ha_set_listener(ip_address=self.pg3.local_ip4,
- port=12345, path_mtu=512)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
+ self.vapi.nat44_ei_ha_set_listener(
+ ip_address=self.pg3.local_ip4, port=12345, path_mtu=512
+ )
bind_layers(UDP, HANATStateSync, sport=12345)
# this is a bit tricky - HA dictates thread index due to how it's
@@ -3512,11 +3741,12 @@ class TestNAT44EI(MethodHolder):
# IP address) and out2in (based on outside port)
# first choose a thread index which is correct for IP
- thread_index = get_nat44_ei_in2out_worker_index(self.pg0.remote_ip4,
- self.vpp_worker_count)
+ thread_index = get_nat44_ei_in2out_worker_index(
+ self.pg0.remote_ip4, self.vpp_worker_count
+ )
# now pick a port which is correct for given thread
- port_per_thread = int((0xffff-1024) / max(1, self.vpp_worker_count))
+ port_per_thread = int((0xFFFF - 1024) / max(1, self.vpp_worker_count))
self.tcp_port_out = 1024 + random.randint(1, port_per_thread)
self.udp_port_out = 1024 + random.randint(1, port_per_thread)
if self.vpp_worker_count > 0:
@@ -3524,25 +3754,43 @@ class TestNAT44EI(MethodHolder):
self.udp_port_out += port_per_thread * (thread_index - 1)
# send HA session add events to failover/passive
- p = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
- UDP(sport=12346, dport=12345) /
- HANATStateSync(sequence_number=1, events=[
- Event(event_type='add', protocol='tcp',
- in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr,
- in_port=self.tcp_port_in, out_port=self.tcp_port_out,
- eh_addr=self.pg1.remote_ip4,
- ehn_addr=self.pg1.remote_ip4,
- eh_port=self.tcp_external_port,
- ehn_port=self.tcp_external_port, fib_index=0),
- Event(event_type='add', protocol='udp',
- in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr,
- in_port=self.udp_port_in, out_port=self.udp_port_out,
- eh_addr=self.pg1.remote_ip4,
- ehn_addr=self.pg1.remote_ip4,
- eh_port=self.udp_external_port,
- ehn_port=self.udp_external_port, fib_index=0)],
- thread_index=thread_index))
+ p = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4)
+ / UDP(sport=12346, dport=12345)
+ / HANATStateSync(
+ sequence_number=1,
+ events=[
+ Event(
+ event_type="add",
+ protocol="tcp",
+ in_addr=self.pg0.remote_ip4,
+ out_addr=self.nat_addr,
+ in_port=self.tcp_port_in,
+ out_port=self.tcp_port_out,
+ eh_addr=self.pg1.remote_ip4,
+ ehn_addr=self.pg1.remote_ip4,
+ eh_port=self.tcp_external_port,
+ ehn_port=self.tcp_external_port,
+ fib_index=0,
+ ),
+ Event(
+ event_type="add",
+ protocol="udp",
+ in_addr=self.pg0.remote_ip4,
+ out_addr=self.nat_addr,
+ in_port=self.udp_port_in,
+ out_port=self.udp_port_out,
+ eh_addr=self.pg1.remote_ip4,
+ ehn_addr=self.pg1.remote_ip4,
+ eh_port=self.udp_external_port,
+ ehn_port=self.udp_external_port,
+ fib_index=0,
+ ),
+ ],
+ thread_index=thread_index,
+ )
+ )
self.pg3.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
@@ -3557,49 +3805,57 @@ class TestNAT44EI(MethodHolder):
raise
else:
self.assertEqual(hanat.sequence_number, 1)
- self.assertEqual(hanat.flags, 'ACK')
+ self.assertEqual(hanat.flags, "ACK")
self.assertEqual(hanat.version, 1)
self.assertEqual(hanat.thread_index, thread_index)
- stats = self.statistics['/nat44-ei/ha/ack-send']
+ stats = self.statistics["/nat44-ei/ha/ack-send"]
self.assertEqual(stats[:, 0].sum(), 1)
- stats = self.statistics['/nat44-ei/ha/add-event-recv']
+ stats = self.statistics["/nat44-ei/ha/add-event-recv"]
self.assertEqual(stats[:, 0].sum(), 2)
- users = self.statistics['/nat44-ei/total-users']
+ users = self.statistics["/nat44-ei/total-users"]
self.assertEqual(users[:, 0].sum(), 1)
- sessions = self.statistics['/nat44-ei/total-sessions']
+ sessions = self.statistics["/nat44-ei/total-sessions"]
self.assertEqual(sessions[:, 0].sum(), 2)
users = self.vapi.nat44_ei_user_dump()
self.assertEqual(len(users), 1)
- self.assertEqual(str(users[0].ip_address),
- self.pg0.remote_ip4)
+ self.assertEqual(str(users[0].ip_address), self.pg0.remote_ip4)
# there should be 2 sessions created by HA
sessions = self.vapi.nat44_ei_user_session_dump(
- users[0].ip_address, users[0].vrf_id)
+ users[0].ip_address, users[0].vrf_id
+ )
self.assertEqual(len(sessions), 2)
for session in sessions:
- self.assertEqual(str(session.inside_ip_address),
- self.pg0.remote_ip4)
- self.assertEqual(str(session.outside_ip_address),
- self.nat_addr)
- self.assertIn(session.inside_port,
- [self.tcp_port_in, self.udp_port_in])
- self.assertIn(session.outside_port,
- [self.tcp_port_out, self.udp_port_out])
+ self.assertEqual(str(session.inside_ip_address), self.pg0.remote_ip4)
+ self.assertEqual(str(session.outside_ip_address), self.nat_addr)
+ self.assertIn(session.inside_port, [self.tcp_port_in, self.udp_port_in])
+ self.assertIn(session.outside_port, [self.tcp_port_out, self.udp_port_out])
self.assertIn(session.protocol, [IP_PROTOS.tcp, IP_PROTOS.udp])
# send HA session delete event to failover/passive
- p = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
- UDP(sport=12346, dport=12345) /
- HANATStateSync(sequence_number=2, events=[
- Event(event_type='del', protocol='udp',
- in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr,
- in_port=self.udp_port_in, out_port=self.udp_port_out,
- eh_addr=self.pg1.remote_ip4,
- ehn_addr=self.pg1.remote_ip4,
- eh_port=self.udp_external_port,
- ehn_port=self.udp_external_port, fib_index=0)],
- thread_index=thread_index))
+ p = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4)
+ / UDP(sport=12346, dport=12345)
+ / HANATStateSync(
+ sequence_number=2,
+ events=[
+ Event(
+ event_type="del",
+ protocol="udp",
+ in_addr=self.pg0.remote_ip4,
+ out_addr=self.nat_addr,
+ in_port=self.udp_port_in,
+ out_port=self.udp_port_out,
+ eh_addr=self.pg1.remote_ip4,
+ ehn_addr=self.pg1.remote_ip4,
+ eh_port=self.udp_external_port,
+ ehn_port=self.udp_external_port,
+ fib_index=0,
+ )
+ ],
+ thread_index=thread_index,
+ )
+ )
self.pg3.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
@@ -3614,37 +3870,49 @@ class TestNAT44EI(MethodHolder):
raise
else:
self.assertEqual(hanat.sequence_number, 2)
- self.assertEqual(hanat.flags, 'ACK')
+ self.assertEqual(hanat.flags, "ACK")
self.assertEqual(hanat.version, 1)
users = self.vapi.nat44_ei_user_dump()
self.assertEqual(len(users), 1)
- self.assertEqual(str(users[0].ip_address),
- self.pg0.remote_ip4)
+ self.assertEqual(str(users[0].ip_address), self.pg0.remote_ip4)
# now we should have only 1 session, 1 deleted by HA
- sessions = self.vapi.nat44_ei_user_session_dump(users[0].ip_address,
- users[0].vrf_id)
+ sessions = self.vapi.nat44_ei_user_session_dump(
+ users[0].ip_address, users[0].vrf_id
+ )
self.assertEqual(len(sessions), 1)
- stats = self.statistics['/nat44-ei/ha/del-event-recv']
+ stats = self.statistics["/nat44-ei/ha/del-event-recv"]
self.assertEqual(stats[:, 0].sum(), 1)
- stats = self.statistics.get_err_counter(
- '/err/nat44-ei-ha/pkts-processed')
+ stats = self.statistics.get_err_counter("/err/nat44-ei-ha/pkts-processed")
self.assertEqual(stats, 2)
# send HA session refresh event to failover/passive
- p = (Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac) /
- IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4) /
- UDP(sport=12346, dport=12345) /
- HANATStateSync(sequence_number=3, events=[
- Event(event_type='refresh', protocol='tcp',
- in_addr=self.pg0.remote_ip4, out_addr=self.nat_addr,
- in_port=self.tcp_port_in, out_port=self.tcp_port_out,
- eh_addr=self.pg1.remote_ip4,
- ehn_addr=self.pg1.remote_ip4,
- eh_port=self.tcp_external_port,
- ehn_port=self.tcp_external_port, fib_index=0,
- total_bytes=1024, total_pkts=2)],
- thread_index=thread_index))
+ p = (
+ Ether(dst=self.pg3.local_mac, src=self.pg3.remote_mac)
+ / IP(src=self.pg3.remote_ip4, dst=self.pg3.local_ip4)
+ / UDP(sport=12346, dport=12345)
+ / HANATStateSync(
+ sequence_number=3,
+ events=[
+ Event(
+ event_type="refresh",
+ protocol="tcp",
+ in_addr=self.pg0.remote_ip4,
+ out_addr=self.nat_addr,
+ in_port=self.tcp_port_in,
+ out_port=self.tcp_port_out,
+ eh_addr=self.pg1.remote_ip4,
+ ehn_addr=self.pg1.remote_ip4,
+ eh_port=self.tcp_external_port,
+ ehn_port=self.tcp_external_port,
+ fib_index=0,
+ total_bytes=1024,
+ total_pkts=2,
+ )
+ ],
+ thread_index=thread_index,
+ )
+ )
self.pg3.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3658,29 +3926,30 @@ class TestNAT44EI(MethodHolder):
raise
else:
self.assertEqual(hanat.sequence_number, 3)
- self.assertEqual(hanat.flags, 'ACK')
+ self.assertEqual(hanat.flags, "ACK")
self.assertEqual(hanat.version, 1)
users = self.vapi.nat44_ei_user_dump()
self.assertEqual(len(users), 1)
- self.assertEqual(str(users[0].ip_address),
- self.pg0.remote_ip4)
+ self.assertEqual(str(users[0].ip_address), self.pg0.remote_ip4)
sessions = self.vapi.nat44_ei_user_session_dump(
- users[0].ip_address, users[0].vrf_id)
+ users[0].ip_address, users[0].vrf_id
+ )
self.assertEqual(len(sessions), 1)
session = sessions[0]
self.assertEqual(session.total_bytes, 1024)
self.assertEqual(session.total_pkts, 2)
- stats = self.statistics['/nat44-ei/ha/refresh-event-recv']
+ stats = self.statistics["/nat44-ei/ha/refresh-event-recv"]
self.assertEqual(stats[:, 0].sum(), 1)
- stats = self.statistics.get_err_counter(
- '/err/nat44-ei-ha/pkts-processed')
+ stats = self.statistics.get_err_counter("/err/nat44-ei-ha/pkts-processed")
self.assertEqual(stats, 3)
# send packet to test session created by HA
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- TCP(sport=self.tcp_external_port, dport=self.tcp_port_out))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=self.tcp_external_port, dport=self.tcp_port_out)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3706,7 +3975,7 @@ class TestNAT44EI(MethodHolder):
return self.vapi.nat44_ei_show_fq_options().frame_queue_nelts
def test_set_frame_queue_nelts(self):
- """ NAT44EI API test - worker handoff frame queue elements """
+ """NAT44EI API test - worker handoff frame queue elements"""
self.assertEqual(self.reconfigure_frame_queue_nelts(512), 512)
def show_commands_at_teardown(self):
@@ -3718,11 +3987,10 @@ class TestNAT44EI(MethodHolder):
self.logger.info(self.vapi.cli("show nat44 ei sessions detail"))
self.logger.info(self.vapi.cli("show nat44 ei hash tables detail"))
self.logger.info(self.vapi.cli("show nat44 ei ha"))
- self.logger.info(
- self.vapi.cli("show nat44 ei addr-port-assignment-alg"))
+ self.logger.info(self.vapi.cli("show nat44 ei addr-port-assignment-alg"))
def test_outside_address_distribution(self):
- """ Outside address distribution based on source address """
+ """Outside address distribution based on source address"""
x = 100
nat_addresses = []
@@ -3733,16 +4001,18 @@ class TestNAT44EI(MethodHolder):
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
self.vapi.nat44_ei_add_del_address_range(
first_ip_address=nat_addresses[0],
last_ip_address=nat_addresses[-1],
- vrf_id=0xFFFFFFFF, is_add=1)
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
self.pg0.generate_remote_hosts(x)
@@ -3750,11 +4020,12 @@ class TestNAT44EI(MethodHolder):
for i in range(x):
info = self.create_packet_info(self.pg0, self.pg1)
payload = self.info_to_payload(info)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_hosts[i].ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=7000+i, dport=8000+i) /
- Raw(payload))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_hosts[i].ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=7000 + i, dport=8000 + i)
+ / Raw(payload)
+ )
info.data = p
pkts.append(p)
@@ -3772,21 +4043,23 @@ class TestNAT44EI(MethodHolder):
packed = socket.inet_aton(p_sent[IP].src)
numeric = struct.unpack("!L", packed)[0]
numeric = socket.htonl(numeric)
- a = nat_addresses[(numeric-1) % len(nat_addresses)]
+ a = nat_addresses[(numeric - 1) % len(nat_addresses)]
self.assertEqual(
- a, p_recvd[IP].src,
+ a,
+ p_recvd[IP].src,
"Invalid packet (src IP %s translated to %s, but expected %s)"
- % (p_sent[IP].src, p_recvd[IP].src, a))
+ % (p_sent[IP].src, p_recvd[IP].src, a),
+ )
def test_default_user_sessions(self):
- """ NAT44EI default per-user session limit is used and reported """
+ """NAT44EI default per-user session limit is used and reported"""
nat44_ei_config = self.vapi.nat44_ei_show_running_config()
# a nonzero default should be reported for user_sessions
self.assertNotEqual(nat44_ei_config.user_sessions, 0)
class TestNAT44Out2InDPO(MethodHolder):
- """ NAT44EI Test Cases using out2in DPO """
+ """NAT44EI Test Cases using out2in DPO"""
@classmethod
def setUpClass(cls):
@@ -3799,8 +4072,8 @@ class TestNAT44Out2InDPO(MethodHolder):
cls.udp_port_out = 6304
cls.icmp_id_in = 6305
cls.icmp_id_out = 6305
- cls.nat_addr = '10.0.0.3'
- cls.dst_ip4 = '192.168.70.1'
+ cls.nat_addr = "10.0.0.3"
+ cls.dst_ip4 = "192.168.70.1"
cls.create_pg_interfaces(range(2))
@@ -3812,10 +4085,13 @@ class TestNAT44Out2InDPO(MethodHolder):
cls.pg1.config_ip6()
cls.pg1.resolve_ndp()
- r1 = VppIpRoute(cls, "::", 0,
- [VppRoutePath(cls.pg1.remote_ip6,
- cls.pg1.sw_if_index)],
- register=False)
+ r1 = VppIpRoute(
+ cls,
+ "::",
+ 0,
+ [VppRoutePath(cls.pg1.remote_ip6, cls.pg1.sw_if_index)],
+ register=False,
+ )
r1.add_vpp_config()
def setUp(self):
@@ -3830,37 +4106,44 @@ class TestNAT44Out2InDPO(MethodHolder):
self.vapi.cli("clear logging")
def configure_xlat(self):
- self.dst_ip6_pfx = '1:2:3::'
- self.dst_ip6_pfx_n = socket.inet_pton(socket.AF_INET6,
- self.dst_ip6_pfx)
+ self.dst_ip6_pfx = "1:2:3::"
+ self.dst_ip6_pfx_n = socket.inet_pton(socket.AF_INET6, self.dst_ip6_pfx)
self.dst_ip6_pfx_len = 96
- self.src_ip6_pfx = '4:5:6::'
- self.src_ip6_pfx_n = socket.inet_pton(socket.AF_INET6,
- self.src_ip6_pfx)
+ self.src_ip6_pfx = "4:5:6::"
+ self.src_ip6_pfx_n = socket.inet_pton(socket.AF_INET6, self.src_ip6_pfx)
self.src_ip6_pfx_len = 96
- self.vapi.map_add_domain(self.dst_ip6_pfx_n, self.dst_ip6_pfx_len,
- self.src_ip6_pfx_n, self.src_ip6_pfx_len,
- '\x00\x00\x00\x00', 0)
-
- @unittest.skip('Temporary disabled')
+ self.vapi.map_add_domain(
+ self.dst_ip6_pfx_n,
+ self.dst_ip6_pfx_len,
+ self.src_ip6_pfx_n,
+ self.src_ip6_pfx_len,
+ "\x00\x00\x00\x00",
+ 0,
+ )
+
+ @unittest.skip("Temporary disabled")
def test_464xlat_ce(self):
- """ Test 464XLAT CE with NAT44EI """
+ """Test 464XLAT CE with NAT44EI"""
self.configure_xlat()
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_add_del_address_range(
first_ip_address=self.nat_addr_n,
last_ip_address=self.nat_addr_n,
- vrf_id=0xFFFFFFFF, is_add=1)
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
- out_src_ip6 = self.compose_ip6(self.dst_ip4, self.dst_ip6_pfx,
- self.dst_ip6_pfx_len)
- out_dst_ip6 = self.compose_ip6(self.nat_addr, self.src_ip6_pfx,
- self.src_ip6_pfx_len)
+ out_src_ip6 = self.compose_ip6(
+ self.dst_ip4, self.dst_ip6_pfx, self.dst_ip6_pfx_len
+ )
+ out_dst_ip6 = self.compose_ip6(
+ self.nat_addr, self.src_ip6_pfx, self.src_ip6_pfx_len
+ )
try:
pkts = self.create_stream_in(self.pg0, self.pg1, self.dst_ip4)
@@ -3868,11 +4151,9 @@ class TestNAT44Out2InDPO(MethodHolder):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out_ip6(capture, nat_ip=out_dst_ip6,
- dst_ip=out_src_ip6)
+ self.verify_capture_out_ip6(capture, nat_ip=out_dst_ip6, dst_ip=out_src_ip6)
- pkts = self.create_stream_out_ip6(self.pg1, out_src_ip6,
- out_dst_ip6)
+ pkts = self.create_stream_out_ip6(self.pg1, out_src_ip6, out_dst_ip6)
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -3880,31 +4161,35 @@ class TestNAT44Out2InDPO(MethodHolder):
self.verify_capture_in(capture, self.pg0)
finally:
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags)
+ sw_if_index=self.pg0.sw_if_index, flags=flags
+ )
self.vapi.nat44_ei_add_del_address_range(
first_ip_address=self.nat_addr_n,
last_ip_address=self.nat_addr_n,
- vrf_id=0xFFFFFFFF)
+ vrf_id=0xFFFFFFFF,
+ )
- @unittest.skip('Temporary disabled')
+ @unittest.skip("Temporary disabled")
def test_464xlat_ce_no_nat(self):
- """ Test 464XLAT CE without NAT44EI """
+ """Test 464XLAT CE without NAT44EI"""
self.configure_xlat()
- out_src_ip6 = self.compose_ip6(self.dst_ip4, self.dst_ip6_pfx,
- self.dst_ip6_pfx_len)
- out_dst_ip6 = self.compose_ip6(self.pg0.remote_ip4, self.src_ip6_pfx,
- self.src_ip6_pfx_len)
+ out_src_ip6 = self.compose_ip6(
+ self.dst_ip4, self.dst_ip6_pfx, self.dst_ip6_pfx_len
+ )
+ out_dst_ip6 = self.compose_ip6(
+ self.pg0.remote_ip4, self.src_ip6_pfx, self.src_ip6_pfx_len
+ )
pkts = self.create_stream_in(self.pg0, self.pg1, self.dst_ip4)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out_ip6(capture, dst_ip=out_src_ip6,
- nat_ip=out_dst_ip6, same_port=True)
+ self.verify_capture_out_ip6(
+ capture, dst_ip=out_src_ip6, nat_ip=out_dst_ip6, same_port=True
+ )
pkts = self.create_stream_out_ip6(self.pg1, out_src_ip6, out_dst_ip6)
self.pg1.add_stream(pkts)
@@ -3915,7 +4200,8 @@ class TestNAT44Out2InDPO(MethodHolder):
class TestNAT44EIMW(MethodHolder):
- """ NAT44EI Test Cases (multiple workers) """
+ """NAT44EI Test Cases (multiple workers)"""
+
vpp_worker_count = 2
max_translations = 10240
max_users = 10240
@@ -3931,7 +4217,7 @@ class TestNAT44EIMW(MethodHolder):
cls.udp_port_out = 6304
cls.icmp_id_in = 6305
cls.icmp_id_out = 6305
- cls.nat_addr = '10.0.0.3'
+ cls.nat_addr = "10.0.0.3"
cls.ipfix_src_port = 4739
cls.ipfix_domain_id = 1
cls.tcp_external_port = 80
@@ -3952,8 +4238,8 @@ class TestNAT44EIMW(MethodHolder):
cls.pg1.configure_ipv4_neighbors()
cls.overlapping_interfaces = list(list(cls.pg_interfaces[4:7]))
- cls.vapi.ip_table_add_del(is_add=1, table={'table_id': 10})
- cls.vapi.ip_table_add_del(is_add=1, table={'table_id': 20})
+ cls.vapi.ip_table_add_del(is_add=1, table={"table_id": 10})
+ cls.vapi.ip_table_add_del(is_add=1, table={"table_id": 20})
cls.pg4._local_ip4 = "172.16.255.1"
cls.pg4._remote_hosts[0]._ip4 = "172.16.255.2"
@@ -3975,8 +4261,8 @@ class TestNAT44EIMW(MethodHolder):
cls.pg9.generate_remote_hosts(2)
cls.pg9.config_ip4()
cls.vapi.sw_interface_add_del_address(
- sw_if_index=cls.pg9.sw_if_index,
- prefix="10.0.0.1/24")
+ sw_if_index=cls.pg9.sw_if_index, prefix="10.0.0.1/24"
+ )
cls.pg9.admin_up()
cls.pg9.resolve_arp()
@@ -3987,16 +4273,15 @@ class TestNAT44EIMW(MethodHolder):
def setUp(self):
super(TestNAT44EIMW, self).setUp()
self.vapi.nat44_ei_plugin_enable_disable(
- sessions=self.max_translations,
- users=self.max_users, enable=1)
+ sessions=self.max_translations, users=self.max_users, enable=1
+ )
def tearDown(self):
super(TestNAT44EIMW, self).tearDown()
if not self.vpp_dead:
self.vapi.nat44_ei_ipfix_enable_disable(
- domain_id=self.ipfix_domain_id,
- src_port=self.ipfix_src_port,
- enable=0)
+ domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=0
+ )
self.ipfix_src_port = 4739
self.ipfix_domain_id = 1
@@ -4004,7 +4289,7 @@ class TestNAT44EIMW(MethodHolder):
self.vapi.cli("clear logging")
def test_hairpinning(self):
- """ NAT44EI hairpinning - 1:1 NAPT """
+ """NAT44EI hairpinning - 1:1 NAPT"""
host = self.pg0.remote_hosts[0]
server = self.pg0.remote_hosts[1]
@@ -4018,22 +4303,28 @@ class TestNAT44EIMW(MethodHolder):
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# add static mapping for server
- self.nat44_add_static_mapping(server.ip4, self.nat_addr,
- server_in_port, server_out_port,
- proto=IP_PROTOS.tcp)
-
- cnt = self.statistics['/nat44-ei/hairpinning']
+ self.nat44_add_static_mapping(
+ server.ip4,
+ self.nat_addr,
+ server_in_port,
+ server_out_port,
+ proto=IP_PROTOS.tcp,
+ )
+
+ cnt = self.statistics["/nat44-ei/hairpinning"]
# send packet from host to server
- p = (Ether(src=host.mac, dst=self.pg0.local_mac) /
- IP(src=host.ip4, dst=self.nat_addr) /
- TCP(sport=host_in_port, dport=server_out_port))
+ p = (
+ Ether(src=host.mac, dst=self.pg0.local_mac)
+ / IP(src=host.ip4, dst=self.nat_addr)
+ / TCP(sport=host_in_port, dport=server_out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -4052,15 +4343,17 @@ class TestNAT44EIMW(MethodHolder):
self.logger.error(ppp("Unexpected or invalid packet:", p))
raise
- after = self.statistics['/nat44-ei/hairpinning']
+ after = self.statistics["/nat44-ei/hairpinning"]
if_idx = self.pg0.sw_if_index
self.assertEqual(after[worker_2][if_idx] - cnt[worker_1][if_idx], 1)
# send reply from server to host
- p = (Ether(src=server.mac, dst=self.pg0.local_mac) /
- IP(src=server.ip4, dst=self.nat_addr) /
- TCP(sport=server_in_port, dport=host_out_port))
+ p = (
+ Ether(src=server.mac, dst=self.pg0.local_mac)
+ / IP(src=server.ip4, dst=self.nat_addr)
+ / TCP(sport=server_in_port, dport=host_out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -4078,13 +4371,13 @@ class TestNAT44EIMW(MethodHolder):
self.logger.error(ppp("Unexpected or invalid packet:", p))
raise
- after = self.statistics['/nat44-ei/hairpinning']
+ after = self.statistics["/nat44-ei/hairpinning"]
if_idx = self.pg0.sw_if_index
self.assertEqual(after[worker_1][if_idx] - cnt[worker_1][if_idx], 1)
self.assertEqual(after[worker_2][if_idx] - cnt[worker_2][if_idx], 2)
def test_hairpinning2(self):
- """ NAT44EI hairpinning - 1:1 NAT"""
+ """NAT44EI hairpinning - 1:1 NAT"""
server1_nat_ip = "10.0.0.10"
server2_nat_ip = "10.0.0.11"
@@ -4097,11 +4390,11 @@ class TestNAT44EIMW(MethodHolder):
self.nat44_add_address(self.nat_addr)
flags = self.config_flags.NAT44_EI_IF_INSIDE
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg0.sw_if_index,
- flags=flags, is_add=1)
+ sw_if_index=self.pg0.sw_if_index, flags=flags, is_add=1
+ )
self.vapi.nat44_ei_interface_add_del_feature(
- sw_if_index=self.pg1.sw_if_index,
- is_add=1)
+ sw_if_index=self.pg1.sw_if_index, is_add=1
+ )
# add static mapping for servers
self.nat44_add_static_mapping(server1.ip4, server1_nat_ip)
@@ -4109,17 +4402,23 @@ class TestNAT44EIMW(MethodHolder):
# host to server1
pkts = []
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=host.ip4, dst=server1_nat_ip) /
- TCP(sport=self.tcp_port_in, dport=server_tcp_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=host.ip4, dst=server1_nat_ip)
+ / TCP(sport=self.tcp_port_in, dport=server_tcp_port)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=host.ip4, dst=server1_nat_ip) /
- UDP(sport=self.udp_port_in, dport=server_udp_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=host.ip4, dst=server1_nat_ip)
+ / UDP(sport=self.udp_port_in, dport=server_udp_port)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=host.ip4, dst=server1_nat_ip) /
- ICMP(id=self.icmp_id_in, type='echo-request'))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=host.ip4, dst=server1_nat_ip)
+ / ICMP(id=self.icmp_id_in, type="echo-request")
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -4147,17 +4446,23 @@ class TestNAT44EIMW(MethodHolder):
# server1 to host
pkts = []
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=self.nat_addr) /
- TCP(sport=server_tcp_port, dport=self.tcp_port_out))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=self.nat_addr)
+ / TCP(sport=server_tcp_port, dport=self.tcp_port_out)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=self.nat_addr) /
- UDP(sport=server_udp_port, dport=self.udp_port_out))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=self.nat_addr)
+ / UDP(sport=server_udp_port, dport=self.udp_port_out)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=self.nat_addr) /
- ICMP(id=self.icmp_id_out, type='echo-reply'))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=self.nat_addr)
+ / ICMP(id=self.icmp_id_out, type="echo-reply")
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -4182,17 +4487,23 @@ class TestNAT44EIMW(MethodHolder):
# server2 to server1
pkts = []
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server2.ip4, dst=server1_nat_ip) /
- TCP(sport=self.tcp_port_in, dport=server_tcp_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server2.ip4, dst=server1_nat_ip)
+ / TCP(sport=self.tcp_port_in, dport=server_tcp_port)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server2.ip4, dst=server1_nat_ip) /
- UDP(sport=self.udp_port_in, dport=server_udp_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server2.ip4, dst=server1_nat_ip)
+ / UDP(sport=self.udp_port_in, dport=server_udp_port)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server2.ip4, dst=server1_nat_ip) /
- ICMP(id=self.icmp_id_in, type='echo-request'))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server2.ip4, dst=server1_nat_ip)
+ / ICMP(id=self.icmp_id_in, type="echo-request")
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -4220,17 +4531,23 @@ class TestNAT44EIMW(MethodHolder):
# server1 to server2
pkts = []
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=server2_nat_ip) /
- TCP(sport=server_tcp_port, dport=self.tcp_port_out))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=server2_nat_ip)
+ / TCP(sport=server_tcp_port, dport=self.tcp_port_out)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=server2_nat_ip) /
- UDP(sport=server_udp_port, dport=self.udp_port_out))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=server2_nat_ip)
+ / UDP(sport=server_udp_port, dport=self.udp_port_out)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=server1.ip4, dst=server2_nat_ip) /
- ICMP(id=self.icmp_id_out, type='echo-reply'))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=server1.ip4, dst=server2_nat_ip)
+ / ICMP(id=self.icmp_id_out, type="echo-reply")
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -4254,5 +4571,5 @@ class TestNAT44EIMW(MethodHolder):
raise
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_nat64.py b/test/test_nat64.py
index c51adac09de..214072addc9 100644
--- a/test/test_nat64.py
+++ b/test/test_nat64.py
@@ -16,8 +16,15 @@ from scapy.data import IP_PROTOS
from scapy.layers.inet import IP, TCP, UDP, ICMP
from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror
from scapy.layers.inet6 import ICMPv6DestUnreach, IPerror6, IPv6ExtHdrFragment
-from scapy.layers.inet6 import IPv6, ICMPv6EchoRequest, ICMPv6EchoReply, \
- ICMPv6ND_NS, ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, fragment6
+from scapy.layers.inet6 import (
+ IPv6,
+ ICMPv6EchoRequest,
+ ICMPv6EchoReply,
+ ICMPv6ND_NS,
+ ICMPv6ND_NA,
+ ICMPv6NDOptDstLLAddr,
+ fragment6,
+)
from scapy.layers.l2 import Ether, GRE
from scapy.packet import Raw
from syslog_rfc5424_parser import SyslogMessage, ParseError
@@ -28,7 +35,7 @@ from vpp_papi import VppEnum
@tag_fixme_vpp_workers
class TestNAT64(VppTestCase):
- """ NAT64 Test Cases """
+ """NAT64 Test Cases"""
@property
def SYSLOG_SEVERITY(self):
@@ -49,10 +56,10 @@ class TestNAT64(VppTestCase):
cls.icmp_id_in = 6305
cls.icmp_id_out = 6305
cls.tcp_external_port = 80
- cls.nat_addr = '10.0.0.3'
+ cls.nat_addr = "10.0.0.3"
cls.nat_addr_n = socket.inet_pton(socket.AF_INET, cls.nat_addr)
cls.vrf1_id = 10
- cls.vrf1_nat_addr = '10.0.10.3'
+ cls.vrf1_nat_addr = "10.0.10.3"
cls.ipfix_src_port = 4739
cls.ipfix_domain_id = 1
@@ -61,9 +68,9 @@ class TestNAT64(VppTestCase):
cls.ip6_interfaces.append(cls.pg_interfaces[2])
cls.ip4_interfaces = list(cls.pg_interfaces[1:2])
- cls.vapi.ip_table_add_del(is_add=1,
- table={'table_id': cls.vrf1_id,
- 'is_ip6': 1})
+ cls.vapi.ip_table_add_del(
+ is_add=1, table={"table_id": cls.vrf1_id, "is_ip6": 1}
+ )
cls.pg_interfaces[2].set_table_ip6(cls.vrf1_id)
@@ -94,8 +101,7 @@ class TestNAT64(VppTestCase):
def setUp(self):
super(TestNAT64, self).setUp()
- self.vapi.nat64_plugin_enable_disable(enable=1,
- bib_buckets=128, st_buckets=256)
+ self.vapi.nat64_plugin_enable_disable(enable=1, bib_buckets=128, st_buckets=256)
def tearDown(self):
super(TestNAT64, self).tearDown()
@@ -121,32 +127,37 @@ class TestNAT64(VppTestCase):
"""
pkts = []
if pref is None:
- dst = ''.join(['64:ff9b::', out_if.remote_ip4])
+ dst = "".join(["64:ff9b::", out_if.remote_ip4])
else:
dst = self.compose_ip6(out_if.remote_ip4, pref, plen)
# TCP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) /
- TCP(sport=self.tcp_port_in, dport=20))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim)
+ / TCP(sport=self.tcp_port_in, dport=20)
+ )
pkts.append(p)
# UDP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) /
- UDP(sport=self.udp_port_in, dport=20))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim)
+ / UDP(sport=self.udp_port_in, dport=20)
+ )
pkts.append(p)
# ICMP
- p = (Ether(dst=in_if.local_mac, src=in_if.remote_mac) /
- IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim) /
- ICMPv6EchoRequest(id=self.icmp_id_in))
+ p = (
+ Ether(dst=in_if.local_mac, src=in_if.remote_mac)
+ / IPv6(src=in_if.remote_ip6, dst=dst, hlim=hlim)
+ / ICMPv6EchoRequest(id=self.icmp_id_in)
+ )
pkts.append(p)
return pkts
- def create_stream_out(self, out_if, dst_ip=None, ttl=64,
- use_inside_ports=False):
+ def create_stream_out(self, out_if, dst_ip=None, ttl=64, use_inside_ports=False):
"""
Create packet stream for outside network
@@ -168,27 +179,40 @@ class TestNAT64(VppTestCase):
icmp_id = self.icmp_id_in
pkts = []
# TCP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- TCP(dport=tcp_port, sport=20))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / TCP(dport=tcp_port, sport=20)
+ )
pkts.extend([p, p])
# UDP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- UDP(dport=udp_port, sport=20))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / UDP(dport=udp_port, sport=20)
+ )
pkts.append(p)
# ICMP
- p = (Ether(dst=out_if.local_mac, src=out_if.remote_mac) /
- IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl) /
- ICMP(id=icmp_id, type='echo-reply'))
+ p = (
+ Ether(dst=out_if.local_mac, src=out_if.remote_mac)
+ / IP(src=out_if.remote_ip4, dst=dst_ip, ttl=ttl)
+ / ICMP(id=icmp_id, type="echo-reply")
+ )
pkts.append(p)
return pkts
- def verify_capture_out(self, capture, nat_ip=None, same_port=False,
- dst_ip=None, is_ip6=False, ignore_port=False):
+ def verify_capture_out(
+ self,
+ capture,
+ nat_ip=None,
+ same_port=False,
+ dst_ip=None,
+ is_ip6=False,
+ ignore_port=False,
+ ):
"""
Verify captured packets on outside network
@@ -216,35 +240,30 @@ class TestNAT64(VppTestCase):
if packet.haslayer(TCP):
if not ignore_port:
if same_port:
- self.assertEqual(
- packet[TCP].sport, self.tcp_port_in)
+ self.assertEqual(packet[TCP].sport, self.tcp_port_in)
else:
- self.assertNotEqual(
- packet[TCP].sport, self.tcp_port_in)
+ self.assertNotEqual(packet[TCP].sport, self.tcp_port_in)
self.tcp_port_out = packet[TCP].sport
self.assert_packet_checksums_valid(packet)
elif packet.haslayer(UDP):
if not ignore_port:
if same_port:
- self.assertEqual(
- packet[UDP].sport, self.udp_port_in)
+ self.assertEqual(packet[UDP].sport, self.udp_port_in)
else:
- self.assertNotEqual(
- packet[UDP].sport, self.udp_port_in)
+ self.assertNotEqual(packet[UDP].sport, self.udp_port_in)
self.udp_port_out = packet[UDP].sport
else:
if not ignore_port:
if same_port:
- self.assertEqual(
- packet[ICMP46].id, self.icmp_id_in)
+ self.assertEqual(packet[ICMP46].id, self.icmp_id_in)
else:
- self.assertNotEqual(
- packet[ICMP46].id, self.icmp_id_in)
+ self.assertNotEqual(packet[ICMP46].id, self.icmp_id_in)
self.icmp_id_out = packet[ICMP46].id
self.assert_packet_checksums_valid(packet)
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(outside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (outside network):", packet)
+ )
raise
def verify_capture_in_ip6(self, capture, src_ip, dst_ip):
@@ -265,15 +284,16 @@ class TestNAT64(VppTestCase):
elif packet.haslayer(UDP):
self.assertEqual(packet[UDP].dport, self.udp_port_in)
else:
- self.assertEqual(packet[ICMPv6EchoReply].id,
- self.icmp_id_in)
+ self.assertEqual(packet[ICMPv6EchoReply].id, self.icmp_id_in)
except:
- self.logger.error(ppp("Unexpected or invalid packet "
- "(inside network):", packet))
+ self.logger.error(
+ ppp("Unexpected or invalid packet (inside network):", packet)
+ )
raise
- def create_stream_frag(self, src_if, dst, sport, dport, data,
- proto=IP_PROTOS.tcp, echo_reply=False):
+ def create_stream_frag(
+ self, src_if, dst, sport, dport, data, proto=IP_PROTOS.tcp, echo_reply=False
+ ):
"""
Create fragmented packet stream
@@ -287,9 +307,11 @@ class TestNAT64(VppTestCase):
:returns: Fragments
"""
if proto == IP_PROTOS.tcp:
- p = (IP(src=src_if.remote_ip4, dst=dst) /
- TCP(sport=sport, dport=dport) /
- Raw(data))
+ p = (
+ IP(src=src_if.remote_ip4, dst=dst)
+ / TCP(sport=sport, dport=dport)
+ / Raw(data)
+ )
p = p.__class__(scapy.compat.raw(p))
chksum = p[TCP].chksum
proto_header = TCP(sport=sport, dport=dport, chksum=chksum)
@@ -297,9 +319,9 @@ class TestNAT64(VppTestCase):
proto_header = UDP(sport=sport, dport=dport)
elif proto == IP_PROTOS.icmp:
if not echo_reply:
- proto_header = ICMP(id=sport, type='echo-request')
+ proto_header = ICMP(id=sport, type="echo-request")
else:
- proto_header = ICMP(id=sport, type='echo-reply')
+ proto_header = ICMP(id=sport, type="echo-reply")
else:
raise Exception("Unsupported protocol")
id = random.randint(0, 65535)
@@ -308,33 +330,38 @@ class TestNAT64(VppTestCase):
raw = Raw(data[0:4])
else:
raw = Raw(data[0:16])
- p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
- IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id) /
- proto_header /
- raw)
+ p = (
+ Ether(src=src_if.remote_mac, dst=src_if.local_mac)
+ / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=0, id=id)
+ / proto_header
+ / raw
+ )
pkts.append(p)
if proto == IP_PROTOS.tcp:
raw = Raw(data[4:20])
else:
raw = Raw(data[16:32])
- p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
- IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id,
- proto=proto) /
- raw)
+ p = (
+ Ether(src=src_if.remote_mac, dst=src_if.local_mac)
+ / IP(src=src_if.remote_ip4, dst=dst, flags="MF", frag=3, id=id, proto=proto)
+ / raw
+ )
pkts.append(p)
if proto == IP_PROTOS.tcp:
raw = Raw(data[20:])
else:
raw = Raw(data[32:])
- p = (Ether(src=src_if.remote_mac, dst=src_if.local_mac) /
- IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto,
- id=id) /
- raw)
+ p = (
+ Ether(src=src_if.remote_mac, dst=src_if.local_mac)
+ / IP(src=src_if.remote_ip4, dst=dst, frag=5, proto=proto, id=id)
+ / raw
+ )
pkts.append(p)
return pkts
- def create_stream_frag_ip6(self, src_if, dst, sport, dport, data,
- pref=None, plen=0, frag_size=128):
+ def create_stream_frag_ip6(
+ self, src_if, dst, sport, dport, data, pref=None, plen=0, frag_size=128
+ ):
"""
Create fragmented packet stream
@@ -349,15 +376,17 @@ class TestNAT64(VppTestCase):
:returns: Fragments
"""
if pref is None:
- dst_ip6 = ''.join(['64:ff9b::', dst])
+ dst_ip6 = "".join(["64:ff9b::", dst])
else:
dst_ip6 = self.compose_ip6(dst, pref, plen)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IPv6(src=src_if.remote_ip6, dst=dst_ip6) /
- IPv6ExtHdrFragment(id=random.randint(0, 65535)) /
- TCP(sport=sport, dport=dport) /
- Raw(data))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IPv6(src=src_if.remote_ip6, dst=dst_ip6)
+ / IPv6ExtHdrFragment(id=random.randint(0, 65535))
+ / TCP(sport=sport, dport=dport)
+ / Raw(data)
+ )
return fragment6(p, frag_size)
@@ -378,17 +407,15 @@ class TestNAT64(VppTestCase):
self.assert_ip_checksum_valid(p)
buffer.seek(p[IP].frag * 8)
buffer.write(bytes(p[IP].payload))
- ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst,
- proto=frags[0][IP].proto)
+ ip = IP(src=frags[0][IP].src, dst=frags[0][IP].dst, proto=frags[0][IP].proto)
if ip.proto == IP_PROTOS.tcp:
- p = (ip / TCP(buffer.getvalue()))
+ p = ip / TCP(buffer.getvalue())
self.logger.debug(ppp("Reassembled:", p))
self.assert_tcp_checksum_valid(p)
elif ip.proto == IP_PROTOS.udp:
- p = (ip / UDP(buffer.getvalue()[:8]) /
- Raw(buffer.getvalue()[8:]))
+ p = ip / UDP(buffer.getvalue()[:8]) / Raw(buffer.getvalue()[8:])
elif ip.proto == IP_PROTOS.icmp:
- p = (ip / ICMP(buffer.getvalue()))
+ p = ip / ICMP(buffer.getvalue())
return p
def reass_frags_and_verify_ip6(self, frags, src, dst):
@@ -407,12 +434,15 @@ class TestNAT64(VppTestCase):
self.assertEqual(p[IPv6].dst, dst)
buffer.seek(p[IPv6ExtHdrFragment].offset * 8)
buffer.write(bytes(p[IPv6ExtHdrFragment].payload))
- ip = IPv6(src=frags[0][IPv6].src, dst=frags[0][IPv6].dst,
- nh=frags[0][IPv6ExtHdrFragment].nh)
+ ip = IPv6(
+ src=frags[0][IPv6].src,
+ dst=frags[0][IPv6].dst,
+ nh=frags[0][IPv6ExtHdrFragment].nh,
+ )
if ip.nh == IP_PROTOS.tcp:
- p = (ip / TCP(buffer.getvalue()))
+ p = ip / TCP(buffer.getvalue())
elif ip.nh == IP_PROTOS.udp:
- p = (ip / UDP(buffer.getvalue()))
+ p = ip / UDP(buffer.getvalue())
self.logger.debug(ppp("Reassembled:", p))
self.assert_packet_checksums_valid(p)
return p
@@ -461,8 +491,7 @@ class TestNAT64(VppTestCase):
# postNAPTSourceTransportPort
self.assertEqual(struct.pack("!H", self.tcp_port_out), record[227])
- def verify_ipfix_nat64_ses(self, data, is_create, src_addr, dst_addr,
- dst_port):
+ def verify_ipfix_nat64_ses(self, data, is_create, src_addr, dst_addr, dst_port):
"""
Verify IPFIX NAT64 session create and delete events
@@ -482,16 +511,16 @@ class TestNAT64(VppTestCase):
# sourceIPv6Address
self.assertEqual(src_addr, str(ipaddress.IPv6Address(record[27])))
# destinationIPv6Address
- self.assertEqual(socket.inet_pton(socket.AF_INET6,
- self.compose_ip6(dst_addr,
- '64:ff9b::',
- 96)),
- record[28])
+ self.assertEqual(
+ socket.inet_pton(
+ socket.AF_INET6, self.compose_ip6(dst_addr, "64:ff9b::", 96)
+ ),
+ record[28],
+ )
# postNATSourceIPv4Address
self.assertEqual(self.nat_addr_n, record[225])
# postNATDestinationIPv4Address
- self.assertEqual(socket.inet_pton(socket.AF_INET, dst_addr),
- record[226])
+ self.assertEqual(socket.inet_pton(socket.AF_INET, dst_addr), record[226])
# protocolIdentifier
self.assertEqual(IP_PROTOS.tcp, scapy.compat.orb(record[4]))
# ingressVRFID
@@ -506,7 +535,7 @@ class TestNAT64(VppTestCase):
self.assertEqual(struct.pack("!H", dst_port), record[228])
def verify_syslog_sess(self, data, is_add=True, is_ip6=False):
- message = data.decode('utf-8')
+ message = data.decode("utf-8")
try:
message = SyslogMessage.parse(message)
except ParseError as e:
@@ -514,26 +543,25 @@ class TestNAT64(VppTestCase):
raise
else:
self.assertEqual(message.severity, SyslogSeverity.info)
- self.assertEqual(message.appname, 'NAT')
- self.assertEqual(message.msgid, 'SADD' if is_add else 'SDEL')
- sd_params = message.sd.get('nsess')
+ self.assertEqual(message.appname, "NAT")
+ self.assertEqual(message.msgid, "SADD" if is_add else "SDEL")
+ sd_params = message.sd.get("nsess")
self.assertTrue(sd_params is not None)
if is_ip6:
- self.assertEqual(sd_params.get('IATYP'), 'IPv6')
- self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip6)
+ self.assertEqual(sd_params.get("IATYP"), "IPv6")
+ self.assertEqual(sd_params.get("ISADDR"), self.pg0.remote_ip6)
else:
- self.assertEqual(sd_params.get('IATYP'), 'IPv4')
- self.assertEqual(sd_params.get('ISADDR'), self.pg0.remote_ip4)
- self.assertTrue(sd_params.get('SSUBIX') is not None)
- self.assertEqual(sd_params.get('ISPORT'), "%d" % self.tcp_port_in)
- self.assertEqual(sd_params.get('XATYP'), 'IPv4')
- self.assertEqual(sd_params.get('XSADDR'), self.nat_addr)
- self.assertEqual(sd_params.get('XSPORT'), "%d" % self.tcp_port_out)
- self.assertEqual(sd_params.get('PROTO'), "%d" % IP_PROTOS.tcp)
- self.assertEqual(sd_params.get('SVLAN'), '0')
- self.assertEqual(sd_params.get('XDADDR'), self.pg1.remote_ip4)
- self.assertEqual(sd_params.get('XDPORT'),
- "%d" % self.tcp_external_port)
+ self.assertEqual(sd_params.get("IATYP"), "IPv4")
+ self.assertEqual(sd_params.get("ISADDR"), self.pg0.remote_ip4)
+ self.assertTrue(sd_params.get("SSUBIX") is not None)
+ self.assertEqual(sd_params.get("ISPORT"), "%d" % self.tcp_port_in)
+ self.assertEqual(sd_params.get("XATYP"), "IPv4")
+ self.assertEqual(sd_params.get("XSADDR"), self.nat_addr)
+ self.assertEqual(sd_params.get("XSPORT"), "%d" % self.tcp_port_out)
+ self.assertEqual(sd_params.get("PROTO"), "%d" % IP_PROTOS.tcp)
+ self.assertEqual(sd_params.get("SVLAN"), "0")
+ self.assertEqual(sd_params.get("XDADDR"), self.pg1.remote_ip4)
+ self.assertEqual(sd_params.get("XDPORT"), "%d" % self.tcp_external_port)
def compose_ip6(self, ip4, pref, plen):
"""
@@ -576,7 +604,7 @@ class TestNAT64(VppTestCase):
pref_n[13] = ip4_n[1]
pref_n[14] = ip4_n[2]
pref_n[15] = ip4_n[3]
- packed_pref_n = b''.join([scapy.compat.chb(x) for x in pref_n])
+ packed_pref_n = b"".join([scapy.compat.chb(x) for x in pref_n])
return socket.inet_ntop(socket.AF_INET6, packed_pref_n)
def verify_ipfix_max_sessions(self, data, limit):
@@ -596,16 +624,19 @@ class TestNAT64(VppTestCase):
self.assertEqual(struct.pack("I", limit), record[471])
def test_nat64_inside_interface_handles_neighbor_advertisement(self):
- """ NAT64 inside interface handles Neighbor Advertisement """
+ """NAT64 inside interface handles Neighbor Advertisement"""
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg5.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg5.sw_if_index
+ )
# Try to send ping
- ping = (Ether(dst=self.pg5.local_mac, src=self.pg5.remote_mac) /
- IPv6(src=self.pg5.remote_ip6, dst=self.pg5.local_ip6) /
- ICMPv6EchoRequest())
+ ping = (
+ Ether(dst=self.pg5.local_mac, src=self.pg5.remote_mac)
+ / IPv6(src=self.pg5.remote_ip6, dst=self.pg5.local_ip6)
+ / ICMPv6EchoRequest()
+ )
pkts = [ping]
self.pg5.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -623,10 +654,12 @@ class TestNAT64(VppTestCase):
raise
# Send Neighbor Advertisement
- p = (Ether(dst=self.pg5.local_mac, src=self.pg5.remote_mac) /
- IPv6(src=self.pg5.remote_ip6, dst=self.pg5.local_ip6) /
- ICMPv6ND_NA(tgt=tgt) /
- ICMPv6NDOptDstLLAddr(lladdr=self.pg5.remote_mac))
+ p = (
+ Ether(dst=self.pg5.local_mac, src=self.pg5.remote_mac)
+ / IPv6(src=self.pg5.remote_ip6, dst=self.pg5.local_ip6)
+ / ICMPv6ND_NA(tgt=tgt)
+ / ICMPv6NDOptDstLLAddr(lladdr=self.pg5.remote_mac)
+ )
pkts = [p]
self.pg5.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -650,31 +683,33 @@ class TestNAT64(VppTestCase):
raise
def test_pool(self):
- """ Add/delete address to NAT64 pool """
- nat_addr = '1.2.3.4'
+ """Add/delete address to NAT64 pool"""
+ nat_addr = "1.2.3.4"
- self.vapi.nat64_add_del_pool_addr_range(start_addr=nat_addr,
- end_addr=nat_addr,
- vrf_id=0xFFFFFFFF, is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=nat_addr, end_addr=nat_addr, vrf_id=0xFFFFFFFF, is_add=1
+ )
addresses = self.vapi.nat64_pool_addr_dump()
self.assertEqual(len(addresses), 1)
self.assertEqual(str(addresses[0].address), nat_addr)
- self.vapi.nat64_add_del_pool_addr_range(start_addr=nat_addr,
- end_addr=nat_addr,
- vrf_id=0xFFFFFFFF, is_add=0)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=nat_addr, end_addr=nat_addr, vrf_id=0xFFFFFFFF, is_add=0
+ )
addresses = self.vapi.nat64_pool_addr_dump()
self.assertEqual(len(addresses), 0)
def test_interface(self):
- """ Enable/disable NAT64 feature on the interface """
+ """Enable/disable NAT64 feature on the interface"""
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
interfaces = self.vapi.nat64_interface_dump()
self.assertEqual(len(interfaces), 2)
@@ -691,29 +726,37 @@ class TestNAT64(VppTestCase):
self.assertTrue(pg1_found)
features = self.vapi.cli("show interface features pg0")
- self.assertIn('nat64-in2out', features)
+ self.assertIn("nat64-in2out", features)
features = self.vapi.cli("show interface features pg1")
- self.assertIn('nat64-out2in', features)
+ self.assertIn("nat64-out2in", features)
- self.vapi.nat64_add_del_interface(is_add=0, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=0, flags=flags,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=0, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=0, flags=flags, sw_if_index=self.pg1.sw_if_index
+ )
interfaces = self.vapi.nat64_interface_dump()
self.assertEqual(len(interfaces), 0)
def test_static_bib(self):
- """ Add/delete static BIB entry """
- in_addr = '2001:db8:85a3::8a2e:370:7334'
- out_addr = '10.1.1.3'
+ """Add/delete static BIB entry"""
+ in_addr = "2001:db8:85a3::8a2e:370:7334"
+ out_addr = "10.1.1.3"
in_port = 1234
out_port = 5678
proto = IP_PROTOS.tcp
- self.vapi.nat64_add_del_static_bib(i_addr=in_addr, o_addr=out_addr,
- i_port=in_port, o_port=out_port,
- proto=proto, vrf_id=0, is_add=1)
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=in_addr,
+ o_addr=out_addr,
+ i_port=in_port,
+ o_port=out_port,
+ proto=proto,
+ vrf_id=0,
+ is_add=1,
+ )
bib = self.vapi.nat64_bib_dump(proto=IP_PROTOS.tcp)
static_bib_num = 0
for bibe in bib:
@@ -724,23 +767,29 @@ class TestNAT64(VppTestCase):
self.assertEqual(bibe.i_port, in_port)
self.assertEqual(bibe.o_port, out_port)
self.assertEqual(static_bib_num, 1)
- bibs = self.statistics.get_counter('/nat64/total-bibs')
+ bibs = self.statistics.get_counter("/nat64/total-bibs")
self.assertEqual(bibs[0][0], 1)
- self.vapi.nat64_add_del_static_bib(i_addr=in_addr, o_addr=out_addr,
- i_port=in_port, o_port=out_port,
- proto=proto, vrf_id=0, is_add=0)
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=in_addr,
+ o_addr=out_addr,
+ i_port=in_port,
+ o_port=out_port,
+ proto=proto,
+ vrf_id=0,
+ is_add=0,
+ )
bib = self.vapi.nat64_bib_dump(proto=IP_PROTOS.tcp)
static_bib_num = 0
for bibe in bib:
if bibe.flags & self.config_flags.NAT_IS_STATIC:
static_bib_num += 1
self.assertEqual(static_bib_num, 0)
- bibs = self.statistics.get_counter('/nat64/total-bibs')
+ bibs = self.statistics.get_counter("/nat64/total-bibs")
self.assertEqual(bibs[0][0], 0)
def test_set_timeouts(self):
- """ Set NAT64 timeouts """
+ """Set NAT64 timeouts"""
# verify default values
timeouts = self.vapi.nat64_get_timeouts()
self.assertEqual(timeouts.udp, 300)
@@ -749,8 +798,9 @@ class TestNAT64(VppTestCase):
self.assertEqual(timeouts.tcp_established, 7440)
# set and verify custom values
- self.vapi.nat64_set_timeouts(udp=200, tcp_established=7450,
- tcp_transitory=250, icmp=30)
+ self.vapi.nat64_set_timeouts(
+ udp=200, tcp_established=7450, tcp_transitory=250, icmp=30
+ )
timeouts = self.vapi.nat64_get_timeouts()
self.assertEqual(timeouts.udp, 200)
self.assertEqual(timeouts.icmp, 30)
@@ -758,74 +808,79 @@ class TestNAT64(VppTestCase):
self.assertEqual(timeouts.tcp_established, 7450)
def test_dynamic(self):
- """ NAT64 dynamic translation test """
+ """NAT64 dynamic translation test"""
self.tcp_port_in = 6303
self.udp_port_in = 6304
self.icmp_id_in = 6305
ses_num_start = self.nat64_get_ses_num()
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
# in2out
- tcpn = self.statistics.get_counter('/nat64/in2out/tcp')[0]
- udpn = self.statistics.get_counter('/nat64/in2out/udp')[0]
- icmpn = self.statistics.get_counter('/nat64/in2out/icmp')[0]
- drops = self.statistics.get_counter('/nat64/in2out/drops')[0]
+ tcpn = self.statistics.get_counter("/nat64/in2out/tcp")[0]
+ udpn = self.statistics.get_counter("/nat64/in2out/udp")[0]
+ icmpn = self.statistics.get_counter("/nat64/in2out/icmp")[0]
+ drops = self.statistics.get_counter("/nat64/in2out/drops")[0]
pkts = self.create_stream_in_ip6(self.pg0, self.pg1)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out(capture, nat_ip=self.nat_addr,
- dst_ip=self.pg1.remote_ip4)
+ self.verify_capture_out(
+ capture, nat_ip=self.nat_addr, dst_ip=self.pg1.remote_ip4
+ )
if_idx = self.pg0.sw_if_index
- cnt = self.statistics.get_counter('/nat64/in2out/tcp')[0]
+ cnt = self.statistics.get_counter("/nat64/in2out/tcp")[0]
self.assertEqual(cnt[if_idx] - tcpn[if_idx], 1)
- cnt = self.statistics.get_counter('/nat64/in2out/udp')[0]
+ cnt = self.statistics.get_counter("/nat64/in2out/udp")[0]
self.assertEqual(cnt[if_idx] - udpn[if_idx], 1)
- cnt = self.statistics.get_counter('/nat64/in2out/icmp')[0]
+ cnt = self.statistics.get_counter("/nat64/in2out/icmp")[0]
self.assertEqual(cnt[if_idx] - icmpn[if_idx], 1)
- cnt = self.statistics.get_counter('/nat64/in2out/drops')[0]
+ cnt = self.statistics.get_counter("/nat64/in2out/drops")[0]
self.assertEqual(cnt[if_idx] - drops[if_idx], 0)
# out2in
- tcpn = self.statistics.get_counter('/nat64/out2in/tcp')[0]
- udpn = self.statistics.get_counter('/nat64/out2in/udp')[0]
- icmpn = self.statistics.get_counter('/nat64/out2in/icmp')[0]
- drops = self.statistics.get_counter('/nat64/out2in/drops')[0]
+ tcpn = self.statistics.get_counter("/nat64/out2in/tcp")[0]
+ udpn = self.statistics.get_counter("/nat64/out2in/udp")[0]
+ icmpn = self.statistics.get_counter("/nat64/out2in/icmp")[0]
+ drops = self.statistics.get_counter("/nat64/out2in/drops")[0]
pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr)
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg0.get_capture(len(pkts))
- ip = IPv6(src=''.join(['64:ff9b::', self.pg1.remote_ip4]))
+ ip = IPv6(src="".join(["64:ff9b::", self.pg1.remote_ip4]))
self.verify_capture_in_ip6(capture, ip[IPv6].src, self.pg0.remote_ip6)
if_idx = self.pg1.sw_if_index
- cnt = self.statistics.get_counter('/nat64/out2in/tcp')[0]
+ cnt = self.statistics.get_counter("/nat64/out2in/tcp")[0]
self.assertEqual(cnt[if_idx] - tcpn[if_idx], 2)
- cnt = self.statistics.get_counter('/nat64/out2in/udp')[0]
+ cnt = self.statistics.get_counter("/nat64/out2in/udp")[0]
self.assertEqual(cnt[if_idx] - udpn[if_idx], 1)
- cnt = self.statistics.get_counter('/nat64/out2in/icmp')[0]
+ cnt = self.statistics.get_counter("/nat64/out2in/icmp")[0]
self.assertEqual(cnt[if_idx] - icmpn[if_idx], 1)
- cnt = self.statistics.get_counter('/nat64/out2in/drops')[0]
+ cnt = self.statistics.get_counter("/nat64/out2in/drops")[0]
self.assertEqual(cnt[if_idx] - drops[if_idx], 0)
- bibs = self.statistics.get_counter('/nat64/total-bibs')
+ bibs = self.statistics.get_counter("/nat64/total-bibs")
self.assertEqual(bibs[0][0], 3)
- sessions = self.statistics.get_counter('/nat64/total-sessions')
+ sessions = self.statistics.get_counter("/nat64/total-sessions")
self.assertEqual(sessions[0][0], 3)
# in2out
@@ -834,8 +889,9 @@ class TestNAT64(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out(capture, nat_ip=self.nat_addr,
- dst_ip=self.pg1.remote_ip4)
+ self.verify_capture_out(
+ capture, nat_ip=self.nat_addr, dst_ip=self.pg1.remote_ip4
+ )
# out2in
pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr)
@@ -850,20 +906,25 @@ class TestNAT64(VppTestCase):
self.assertEqual(ses_num_end - ses_num_start, 3)
# tenant with specific VRF
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.vrf1_nat_addr,
- end_addr=self.vrf1_nat_addr,
- vrf_id=self.vrf1_id, is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.vrf1_nat_addr,
+ end_addr=self.vrf1_nat_addr,
+ vrf_id=self.vrf1_id,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg2.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg2.sw_if_index
+ )
pkts = self.create_stream_in_ip6(self.pg2, self.pg1)
self.pg2.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out(capture, nat_ip=self.vrf1_nat_addr,
- dst_ip=self.pg1.remote_ip4)
+ self.verify_capture_out(
+ capture, nat_ip=self.vrf1_nat_addr, dst_ip=self.pg1.remote_ip4
+ )
pkts = self.create_stream_out(self.pg1, dst_ip=self.vrf1_nat_addr)
self.pg1.add_stream(pkts)
@@ -873,7 +934,7 @@ class TestNAT64(VppTestCase):
self.verify_capture_in_ip6(capture, ip[IPv6].src, self.pg2.remote_ip6)
def test_static(self):
- """ NAT64 static translation test """
+ """NAT64 static translation test"""
self.tcp_port_in = 60303
self.udp_port_in = 60304
self.icmp_id_in = 60305
@@ -883,34 +944,47 @@ class TestNAT64(VppTestCase):
ses_num_start = self.nat64_get_ses_num()
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
-
- self.vapi.nat64_add_del_static_bib(i_addr=self.pg0.remote_ip6,
- o_addr=self.nat_addr,
- i_port=self.tcp_port_in,
- o_port=self.tcp_port_out,
- proto=IP_PROTOS.tcp, vrf_id=0,
- is_add=1)
- self.vapi.nat64_add_del_static_bib(i_addr=self.pg0.remote_ip6,
- o_addr=self.nat_addr,
- i_port=self.udp_port_in,
- o_port=self.udp_port_out,
- proto=IP_PROTOS.udp, vrf_id=0,
- is_add=1)
- self.vapi.nat64_add_del_static_bib(i_addr=self.pg0.remote_ip6,
- o_addr=self.nat_addr,
- i_port=self.icmp_id_in,
- o_port=self.icmp_id_out,
- proto=IP_PROTOS.icmp, vrf_id=0,
- is_add=1)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
+
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=self.pg0.remote_ip6,
+ o_addr=self.nat_addr,
+ i_port=self.tcp_port_in,
+ o_port=self.tcp_port_out,
+ proto=IP_PROTOS.tcp,
+ vrf_id=0,
+ is_add=1,
+ )
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=self.pg0.remote_ip6,
+ o_addr=self.nat_addr,
+ i_port=self.udp_port_in,
+ o_port=self.udp_port_out,
+ proto=IP_PROTOS.udp,
+ vrf_id=0,
+ is_add=1,
+ )
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=self.pg0.remote_ip6,
+ o_addr=self.nat_addr,
+ i_port=self.icmp_id_in,
+ o_port=self.icmp_id_out,
+ proto=IP_PROTOS.icmp,
+ vrf_id=0,
+ is_add=1,
+ )
# in2out
pkts = self.create_stream_in_ip6(self.pg0, self.pg1)
@@ -918,8 +992,9 @@ class TestNAT64(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out(capture, nat_ip=self.nat_addr,
- dst_ip=self.pg1.remote_ip4, same_port=True)
+ self.verify_capture_out(
+ capture, nat_ip=self.nat_addr, dst_ip=self.pg1.remote_ip4, same_port=True
+ )
# out2in
pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr)
@@ -927,7 +1002,7 @@ class TestNAT64(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg0.get_capture(len(pkts))
- ip = IPv6(src=''.join(['64:ff9b::', self.pg1.remote_ip4]))
+ ip = IPv6(src="".join(["64:ff9b::", self.pg1.remote_ip4]))
self.verify_capture_in_ip6(capture, ip[IPv6].src, self.pg0.remote_ip6)
ses_num_end = self.nat64_get_ses_num()
@@ -935,20 +1010,24 @@ class TestNAT64(VppTestCase):
self.assertEqual(ses_num_end - ses_num_start, 3)
def test_session_timeout(self):
- """ NAT64 session timeout """
+ """NAT64 session timeout"""
self.icmp_id_in = 1234
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
- self.vapi.nat64_set_timeouts(udp=300, tcp_established=5,
- tcp_transitory=5,
- icmp=5)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
+ self.vapi.nat64_set_timeouts(
+ udp=300, tcp_established=5, tcp_transitory=5, icmp=5
+ )
pkts = self.create_stream_in_ip6(self.pg0, self.pg1)
self.pg0.add_stream(pkts)
@@ -965,20 +1044,24 @@ class TestNAT64(VppTestCase):
self.assertEqual(ses_num_before_timeout - ses_num_after_timeout, 2)
def test_icmp_error(self):
- """ NAT64 ICMP Error message translation """
+ """NAT64 ICMP Error message translation"""
self.tcp_port_in = 6303
self.udp_port_in = 6304
self.icmp_id_in = 6305
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
# send some packets to create sessions
pkts = self.create_stream_in_ip6(self.pg0, self.pg1)
@@ -986,24 +1069,26 @@ class TestNAT64(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture_ip4 = self.pg1.get_capture(len(pkts))
- self.verify_capture_out(capture_ip4,
- nat_ip=self.nat_addr,
- dst_ip=self.pg1.remote_ip4)
+ self.verify_capture_out(
+ capture_ip4, nat_ip=self.nat_addr, dst_ip=self.pg1.remote_ip4
+ )
pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr)
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture_ip6 = self.pg0.get_capture(len(pkts))
- ip = IPv6(src=''.join(['64:ff9b::', self.pg1.remote_ip4]))
- self.verify_capture_in_ip6(capture_ip6, ip[IPv6].src,
- self.pg0.remote_ip6)
+ ip = IPv6(src="".join(["64:ff9b::", self.pg1.remote_ip4]))
+ self.verify_capture_in_ip6(capture_ip6, ip[IPv6].src, self.pg0.remote_ip6)
# in2out
- pkts = [Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=ip[IPv6].src) /
- ICMPv6DestUnreach(code=1) /
- packet[IPv6] for packet in capture_ip6]
+ pkts = [
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=ip[IPv6].src)
+ / ICMPv6DestUnreach(code=1)
+ / packet[IPv6]
+ for packet in capture_ip6
+ ]
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1029,10 +1114,13 @@ class TestNAT64(VppTestCase):
raise
# out2in
- pkts = [Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- ICMP(type=3, code=13) /
- packet[IP] for packet in capture_ip4]
+ pkts = [
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / ICMP(type=3, code=13)
+ / packet[IP]
+ for packet in capture_ip4
+ ]
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1052,14 +1140,13 @@ class TestNAT64(VppTestCase):
elif inner.haslayer(UDPerror):
self.assertEqual(inner[UDPerror].sport, self.udp_port_in)
else:
- self.assertEqual(inner[ICMPv6EchoRequest].id,
- self.icmp_id_in)
+ self.assertEqual(inner[ICMPv6EchoRequest].id, self.icmp_id_in)
except:
self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
def test_hairpinning(self):
- """ NAT64 hairpinning """
+ """NAT64 hairpinning"""
client = self.pg0.remote_hosts[0]
server = self.pg0.remote_hosts[1]
@@ -1071,41 +1158,55 @@ class TestNAT64(VppTestCase):
client_udp_in_port = 1235
client_tcp_out_port = 0
client_udp_out_port = 0
- ip = IPv6(src=''.join(['64:ff9b::', self.nat_addr]))
+ ip = IPv6(src="".join(["64:ff9b::", self.nat_addr]))
nat_addr_ip6 = ip.src
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
-
- self.vapi.nat64_add_del_static_bib(i_addr=server.ip6n,
- o_addr=self.nat_addr,
- i_port=server_tcp_in_port,
- o_port=server_tcp_out_port,
- proto=IP_PROTOS.tcp, vrf_id=0,
- is_add=1)
- self.vapi.nat64_add_del_static_bib(i_addr=server.ip6n,
- o_addr=self.nat_addr,
- i_port=server_udp_in_port,
- o_port=server_udp_out_port,
- proto=IP_PROTOS.udp, vrf_id=0,
- is_add=1)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
+
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=server.ip6n,
+ o_addr=self.nat_addr,
+ i_port=server_tcp_in_port,
+ o_port=server_tcp_out_port,
+ proto=IP_PROTOS.tcp,
+ vrf_id=0,
+ is_add=1,
+ )
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=server.ip6n,
+ o_addr=self.nat_addr,
+ i_port=server_udp_in_port,
+ o_port=server_udp_out_port,
+ proto=IP_PROTOS.udp,
+ vrf_id=0,
+ is_add=1,
+ )
# client to server
pkts = []
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=client.ip6, dst=nat_addr_ip6) /
- TCP(sport=client_tcp_in_port, dport=server_tcp_out_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=client.ip6, dst=nat_addr_ip6)
+ / TCP(sport=client_tcp_in_port, dport=server_tcp_out_port)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=client.ip6, dst=nat_addr_ip6) /
- UDP(sport=client_udp_in_port, dport=server_udp_out_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=client.ip6, dst=nat_addr_ip6)
+ / UDP(sport=client_udp_in_port, dport=server_udp_out_port)
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -1130,13 +1231,17 @@ class TestNAT64(VppTestCase):
# server to client
pkts = []
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=server.ip6, dst=nat_addr_ip6) /
- TCP(sport=server_tcp_in_port, dport=client_tcp_out_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=server.ip6, dst=nat_addr_ip6)
+ / TCP(sport=server_tcp_in_port, dport=client_tcp_out_port)
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=server.ip6, dst=nat_addr_ip6) /
- UDP(sport=server_udp_in_port, dport=client_udp_out_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=server.ip6, dst=nat_addr_ip6)
+ / UDP(sport=server_udp_in_port, dport=client_udp_out_port)
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -1159,10 +1264,13 @@ class TestNAT64(VppTestCase):
# ICMP error
pkts = []
- pkts = [Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=client.ip6, dst=nat_addr_ip6) /
- ICMPv6DestUnreach(code=1) /
- packet[IPv6] for packet in capture]
+ pkts = [
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=client.ip6, dst=nat_addr_ip6)
+ / ICMPv6DestUnreach(code=1)
+ / packet[IPv6]
+ for packet in capture
+ ]
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1179,40 +1287,45 @@ class TestNAT64(VppTestCase):
self.assert_packet_checksums_valid(packet)
if inner.haslayer(TCPerror):
self.assertEqual(inner[TCPerror].sport, server_tcp_in_port)
- self.assertEqual(inner[TCPerror].dport,
- client_tcp_out_port)
+ self.assertEqual(inner[TCPerror].dport, client_tcp_out_port)
else:
self.assertEqual(inner[UDPerror].sport, server_udp_in_port)
- self.assertEqual(inner[UDPerror].dport,
- client_udp_out_port)
+ self.assertEqual(inner[UDPerror].dport, client_udp_out_port)
except:
self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
def test_prefix(self):
- """ NAT64 Network-Specific Prefix """
+ """NAT64 Network-Specific Prefix"""
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.vrf1_nat_addr,
- end_addr=self.vrf1_nat_addr,
- vrf_id=self.vrf1_id, is_add=1)
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg2.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.vrf1_nat_addr,
+ end_addr=self.vrf1_nat_addr,
+ vrf_id=self.vrf1_id,
+ is_add=1,
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg2.sw_if_index
+ )
# Add global prefix
global_pref64 = "2001:db8::"
global_pref64_len = 32
global_pref64_str = "{}/{}".format(global_pref64, global_pref64_len)
- self.vapi.nat64_add_del_prefix(prefix=global_pref64_str, vrf_id=0,
- is_add=1)
+ self.vapi.nat64_add_del_prefix(prefix=global_pref64_str, vrf_id=0, is_add=1)
prefix = self.vapi.nat64_prefix_dump()
self.assertEqual(len(prefix), 1)
@@ -1223,84 +1336,89 @@ class TestNAT64(VppTestCase):
vrf1_pref64 = "2001:db8:122:300::"
vrf1_pref64_len = 56
vrf1_pref64_str = "{}/{}".format(vrf1_pref64, vrf1_pref64_len)
- self.vapi.nat64_add_del_prefix(prefix=vrf1_pref64_str,
- vrf_id=self.vrf1_id, is_add=1)
+ self.vapi.nat64_add_del_prefix(
+ prefix=vrf1_pref64_str, vrf_id=self.vrf1_id, is_add=1
+ )
prefix = self.vapi.nat64_prefix_dump()
self.assertEqual(len(prefix), 2)
# Global prefix
- pkts = self.create_stream_in_ip6(self.pg0,
- self.pg1,
- pref=global_pref64,
- plen=global_pref64_len)
+ pkts = self.create_stream_in_ip6(
+ self.pg0, self.pg1, pref=global_pref64, plen=global_pref64_len
+ )
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out(capture, nat_ip=self.nat_addr,
- dst_ip=self.pg1.remote_ip4)
+ self.verify_capture_out(
+ capture, nat_ip=self.nat_addr, dst_ip=self.pg1.remote_ip4
+ )
pkts = self.create_stream_out(self.pg1, dst_ip=self.nat_addr)
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg0.get_capture(len(pkts))
- dst_ip = self.compose_ip6(self.pg1.remote_ip4,
- global_pref64,
- global_pref64_len)
+ dst_ip = self.compose_ip6(self.pg1.remote_ip4, global_pref64, global_pref64_len)
self.verify_capture_in_ip6(capture, dst_ip, self.pg0.remote_ip6)
# Tenant specific prefix
- pkts = self.create_stream_in_ip6(self.pg2,
- self.pg1,
- pref=vrf1_pref64,
- plen=vrf1_pref64_len)
+ pkts = self.create_stream_in_ip6(
+ self.pg2, self.pg1, pref=vrf1_pref64, plen=vrf1_pref64_len
+ )
self.pg2.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg1.get_capture(len(pkts))
- self.verify_capture_out(capture, nat_ip=self.vrf1_nat_addr,
- dst_ip=self.pg1.remote_ip4)
+ self.verify_capture_out(
+ capture, nat_ip=self.vrf1_nat_addr, dst_ip=self.pg1.remote_ip4
+ )
pkts = self.create_stream_out(self.pg1, dst_ip=self.vrf1_nat_addr)
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
capture = self.pg2.get_capture(len(pkts))
- dst_ip = self.compose_ip6(self.pg1.remote_ip4,
- vrf1_pref64,
- vrf1_pref64_len)
+ dst_ip = self.compose_ip6(self.pg1.remote_ip4, vrf1_pref64, vrf1_pref64_len)
self.verify_capture_in_ip6(capture, dst_ip, self.pg2.remote_ip6)
def test_unknown_proto(self):
- """ NAT64 translate packet with unknown protocol """
+ """NAT64 translate packet with unknown protocol"""
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
- remote_ip6 = self.compose_ip6(self.pg1.remote_ip4, '64:ff9b::', 96)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
+ remote_ip6 = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96)
# in2out
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=remote_ip6) /
- TCP(sport=self.tcp_port_in, dport=20))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=remote_ip6)
+ / TCP(sport=self.tcp_port_in, dport=20)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
p = self.pg1.get_capture(1)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=remote_ip6, nh=47) /
- GRE() /
- IP(src=self.pg2.local_ip4, dst=self.pg2.remote_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=remote_ip6, nh=47)
+ / GRE()
+ / IP(src=self.pg2.local_ip4, dst=self.pg2.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1316,11 +1434,13 @@ class TestNAT64(VppTestCase):
raise
# out2in
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.nat_addr) /
- GRE() /
- IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.nat_addr)
+ / GRE()
+ / IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1335,7 +1455,7 @@ class TestNAT64(VppTestCase):
raise
def test_hairpinning_unknown_proto(self):
- """ NAT64 translate packet with unknown protocol - hairpinning """
+ """NAT64 translate packet with unknown protocol - hairpinning"""
client = self.pg0.remote_hosts[0]
server = self.pg0.remote_hosts[1]
@@ -1345,53 +1465,71 @@ class TestNAT64(VppTestCase):
client_tcp_out_port = 1235
server_nat_ip = "10.0.0.100"
client_nat_ip = "10.0.0.110"
- server_nat_ip6 = self.compose_ip6(server_nat_ip, '64:ff9b::', 96)
- client_nat_ip6 = self.compose_ip6(client_nat_ip, '64:ff9b::', 96)
+ server_nat_ip6 = self.compose_ip6(server_nat_ip, "64:ff9b::", 96)
+ client_nat_ip6 = self.compose_ip6(client_nat_ip, "64:ff9b::", 96)
- self.vapi.nat64_add_del_pool_addr_range(start_addr=server_nat_ip,
- end_addr=client_nat_ip,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=server_nat_ip,
+ end_addr=client_nat_ip,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
-
- self.vapi.nat64_add_del_static_bib(i_addr=server.ip6n,
- o_addr=server_nat_ip,
- i_port=server_tcp_in_port,
- o_port=server_tcp_out_port,
- proto=IP_PROTOS.tcp, vrf_id=0,
- is_add=1)
-
- self.vapi.nat64_add_del_static_bib(i_addr=server.ip6n,
- o_addr=server_nat_ip, i_port=0,
- o_port=0,
- proto=IP_PROTOS.gre, vrf_id=0,
- is_add=1)
-
- self.vapi.nat64_add_del_static_bib(i_addr=client.ip6n,
- o_addr=client_nat_ip,
- i_port=client_tcp_in_port,
- o_port=client_tcp_out_port,
- proto=IP_PROTOS.tcp, vrf_id=0,
- is_add=1)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
+
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=server.ip6n,
+ o_addr=server_nat_ip,
+ i_port=server_tcp_in_port,
+ o_port=server_tcp_out_port,
+ proto=IP_PROTOS.tcp,
+ vrf_id=0,
+ is_add=1,
+ )
+
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=server.ip6n,
+ o_addr=server_nat_ip,
+ i_port=0,
+ o_port=0,
+ proto=IP_PROTOS.gre,
+ vrf_id=0,
+ is_add=1,
+ )
+
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=client.ip6n,
+ o_addr=client_nat_ip,
+ i_port=client_tcp_in_port,
+ o_port=client_tcp_out_port,
+ proto=IP_PROTOS.tcp,
+ vrf_id=0,
+ is_add=1,
+ )
# client to server
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=client.ip6, dst=server_nat_ip6) /
- TCP(sport=client_tcp_in_port, dport=server_tcp_out_port))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=client.ip6, dst=server_nat_ip6)
+ / TCP(sport=client_tcp_in_port, dport=server_tcp_out_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
p = self.pg0.get_capture(1)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=client.ip6, dst=server_nat_ip6, nh=IP_PROTOS.gre) /
- GRE() /
- IP(src=self.pg2.local_ip4, dst=self.pg2.remote_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=client.ip6, dst=server_nat_ip6, nh=IP_PROTOS.gre)
+ / GRE()
+ / IP(src=self.pg2.local_ip4, dst=self.pg2.remote_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1406,11 +1544,13 @@ class TestNAT64(VppTestCase):
raise
# server to client
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=server.ip6, dst=client_nat_ip6, nh=IP_PROTOS.gre) /
- GRE() /
- IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4) /
- TCP(sport=1234, dport=1234))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=server.ip6, dst=client_nat_ip6, nh=IP_PROTOS.gre)
+ / GRE()
+ / IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4)
+ / TCP(sport=1234, dport=1234)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1425,26 +1565,30 @@ class TestNAT64(VppTestCase):
raise
def test_one_armed_nat64(self):
- """ One armed NAT64 """
+ """One armed NAT64"""
external_port = 0
- remote_host_ip6 = self.compose_ip6(self.pg3.remote_ip4,
- '64:ff9b::',
- 96)
-
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ remote_host_ip6 = self.compose_ip6(self.pg3.remote_ip4, "64:ff9b::", 96)
+
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg3.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg3.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg3.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg3.sw_if_index
+ )
# in2out
- p = (Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac) /
- IPv6(src=self.pg3.remote_ip6, dst=remote_host_ip6) /
- TCP(sport=12345, dport=80))
+ p = (
+ Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac)
+ / IPv6(src=self.pg3.remote_ip6, dst=remote_host_ip6)
+ / TCP(sport=12345, dport=80)
+ )
self.pg3.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1464,9 +1608,11 @@ class TestNAT64(VppTestCase):
raise
# out2in
- p = (Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac) /
- IP(src=self.pg3.remote_ip4, dst=self.nat_addr) /
- TCP(sport=80, dport=external_port))
+ p = (
+ Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac)
+ / IP(src=self.pg3.remote_ip4, dst=self.nat_addr)
+ / TCP(sport=80, dport=external_port)
+ )
self.pg3.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1485,30 +1631,33 @@ class TestNAT64(VppTestCase):
raise
def test_frag_in_order(self):
- """ NAT64 translate fragments arriving in order """
+ """NAT64 translate fragments arriving in order"""
self.tcp_port_in = random.randint(1025, 65535)
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
# in2out
- data = b'a' * 200
- pkts = self.create_stream_frag_ip6(self.pg0, self.pg1.remote_ip4,
- self.tcp_port_in, 20, data)
+ data = b"a" * 200
+ pkts = self.create_stream_frag_ip6(
+ self.pg0, self.pg1.remote_ip4, self.tcp_port_in, 20, data
+ )
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg1.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- self.nat_addr,
- self.pg1.remote_ip4)
+ p = self.reass_frags_and_verify(frags, self.nat_addr, self.pg1.remote_ip4)
self.assertEqual(p[TCP].dport, 20)
self.assertNotEqual(p[TCP].sport, self.tcp_port_in)
self.tcp_port_out = p[TCP].sport
@@ -1516,56 +1665,59 @@ class TestNAT64(VppTestCase):
# out2in
data = b"A" * 4 + b"b" * 16 + b"C" * 3
- pkts = self.create_stream_frag(self.pg1,
- self.nat_addr,
- 20,
- self.tcp_port_out,
- data)
+ pkts = self.create_stream_frag(
+ self.pg1, self.nat_addr, 20, self.tcp_port_out, data
+ )
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg0.get_capture(len(pkts))
self.logger.debug(ppc("Captured:", frags))
- src = self.compose_ip6(self.pg1.remote_ip4, '64:ff9b::', 96)
+ src = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96)
p = self.reass_frags_and_verify_ip6(frags, src, self.pg0.remote_ip6)
self.assertEqual(p[TCP].sport, 20)
self.assertEqual(p[TCP].dport, self.tcp_port_in)
self.assertEqual(data, p[Raw].load)
def test_reass_hairpinning(self):
- """ NAT64 fragments hairpinning """
- data = b'a' * 200
+ """NAT64 fragments hairpinning"""
+ data = b"a" * 200
server = self.pg0.remote_hosts[1]
server_in_port = random.randint(1025, 65535)
server_out_port = random.randint(1025, 65535)
client_in_port = random.randint(1025, 65535)
- ip = IPv6(src=''.join(['64:ff9b::', self.nat_addr]))
+ ip = IPv6(src="".join(["64:ff9b::", self.nat_addr]))
nat_addr_ip6 = ip.src
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
# add static BIB entry for server
- self.vapi.nat64_add_del_static_bib(i_addr=server.ip6n,
- o_addr=self.nat_addr,
- i_port=server_in_port,
- o_port=server_out_port,
- proto=IP_PROTOS.tcp, vrf_id=0,
- is_add=1)
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=server.ip6n,
+ o_addr=self.nat_addr,
+ i_port=server_in_port,
+ o_port=server_out_port,
+ proto=IP_PROTOS.tcp,
+ vrf_id=0,
+ is_add=1,
+ )
# send packet from host to server
- pkts = self.create_stream_frag_ip6(self.pg0,
- self.nat_addr,
- client_in_port,
- server_out_port,
- data)
+ pkts = self.create_stream_frag_ip6(
+ self.pg0, self.nat_addr, client_in_port, server_out_port, data
+ )
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1577,31 +1729,34 @@ class TestNAT64(VppTestCase):
self.assertEqual(data, p[Raw].load)
def test_frag_out_of_order(self):
- """ NAT64 translate fragments arriving out of order """
+ """NAT64 translate fragments arriving out of order"""
self.tcp_port_in = random.randint(1025, 65535)
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
# in2out
- data = b'a' * 200
- pkts = self.create_stream_frag_ip6(self.pg0, self.pg1.remote_ip4,
- self.tcp_port_in, 20, data)
+ data = b"a" * 200
+ pkts = self.create_stream_frag_ip6(
+ self.pg0, self.pg1.remote_ip4, self.tcp_port_in, 20, data
+ )
pkts.reverse()
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg1.get_capture(len(pkts))
- p = self.reass_frags_and_verify(frags,
- self.nat_addr,
- self.pg1.remote_ip4)
+ p = self.reass_frags_and_verify(frags, self.nat_addr, self.pg1.remote_ip4)
self.assertEqual(p[TCP].dport, 20)
self.assertNotEqual(p[TCP].sport, self.tcp_port_in)
self.tcp_port_out = p[TCP].sport
@@ -1609,27 +1764,25 @@ class TestNAT64(VppTestCase):
# out2in
data = b"A" * 4 + b"B" * 16 + b"C" * 3
- pkts = self.create_stream_frag(self.pg1,
- self.nat_addr,
- 20,
- self.tcp_port_out,
- data)
+ pkts = self.create_stream_frag(
+ self.pg1, self.nat_addr, 20, self.tcp_port_out, data
+ )
pkts.reverse()
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
frags = self.pg0.get_capture(len(pkts))
- src = self.compose_ip6(self.pg1.remote_ip4, '64:ff9b::', 96)
+ src = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96)
p = self.reass_frags_and_verify_ip6(frags, src, self.pg0.remote_ip6)
self.assertEqual(p[TCP].sport, 20)
self.assertEqual(p[TCP].dport, self.tcp_port_in)
self.assertEqual(data, p[Raw].load)
def test_interface_addr(self):
- """ Acquire NAT64 pool addresses from interface """
+ """Acquire NAT64 pool addresses from interface"""
self.vapi.nat64_add_del_interface_addr(
- is_add=1,
- sw_if_index=self.pg4.sw_if_index)
+ is_add=1, sw_if_index=self.pg4.sw_if_index
+ )
# no address in NAT64 pool
addresses = self.vapi.nat44_address_dump()
@@ -1640,8 +1793,7 @@ class TestNAT64(VppTestCase):
addresses = self.vapi.nat64_pool_addr_dump()
self.assertEqual(len(addresses), 1)
- self.assertEqual(str(addresses[0].address),
- self.pg4.local_ip4)
+ self.assertEqual(str(addresses[0].address), self.pg4.local_ip4)
# remove interface address and check NAT64 address pool
self.pg4.unconfig_ip4()
@@ -1650,51 +1802,61 @@ class TestNAT64(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_ipfix_max_bibs_sessions(self):
- """ IPFIX logging maximum session and BIB entries exceeded """
+ """IPFIX logging maximum session and BIB entries exceeded"""
max_bibs = 1280
max_sessions = 2560
- remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4,
- '64:ff9b::',
- 96)
-
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96)
+
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
pkts = []
src = ""
for i in range(0, max_bibs):
src = "fd01:aa::%x" % (i)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=src, dst=remote_host_ip6) /
- TCP(sport=12345, dport=80))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=src, dst=remote_host_ip6)
+ / TCP(sport=12345, dport=80)
+ )
pkts.append(p)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=src, dst=remote_host_ip6) /
- TCP(sport=12345, dport=22))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=src, dst=remote_host_ip6)
+ / TCP(sport=12345, dport=22)
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
self.pg1.get_capture(max_sessions)
- self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4,
- src_address=self.pg3.local_ip4,
- path_mtu=512,
- template_interval=10)
- self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
- src_port=self.ipfix_src_port,
- enable=1)
-
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=src, dst=remote_host_ip6) /
- TCP(sport=12345, dport=25))
+ self.vapi.set_ipfix_exporter(
+ collector_address=self.pg3.remote_ip4,
+ src_address=self.pg3.local_ip4,
+ path_mtu=512,
+ template_interval=10,
+ )
+ self.vapi.nat_ipfix_enable_disable(
+ domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=1
+ )
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=src, dst=remote_host_ip6)
+ / TCP(sport=12345, dport=25)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1709,8 +1871,7 @@ class TestNAT64(VppTestCase):
self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
self.assertEqual(p[UDP].sport, self.ipfix_src_port)
self.assertEqual(p[UDP].dport, 4739)
- self.assertEqual(p[IPFIX].observationDomainID,
- self.ipfix_domain_id)
+ self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id)
if p.haslayer(Template):
ipfix.add_template(p.getlayer(Template))
# verify events in data set
@@ -1719,9 +1880,11 @@ class TestNAT64(VppTestCase):
data = ipfix.decode_data_set(p.getlayer(Set))
self.verify_ipfix_max_sessions(data, max_sessions)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) /
- TCP(sport=12345, dport=80))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6)
+ / TCP(sport=12345, dport=80)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1735,40 +1898,45 @@ class TestNAT64(VppTestCase):
self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
self.assertEqual(p[UDP].sport, self.ipfix_src_port)
self.assertEqual(p[UDP].dport, 4739)
- self.assertEqual(p[IPFIX].observationDomainID,
- self.ipfix_domain_id)
+ self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id)
if p.haslayer(Data):
data = ipfix.decode_data_set(p.getlayer(Set))
self.verify_ipfix_max_bibs(data, max_bibs)
def test_ipfix_bib_ses(self):
- """ IPFIX logging NAT64 BIB/session create and delete events """
+ """IPFIX logging NAT64 BIB/session create and delete events"""
self.tcp_port_in = random.randint(1025, 65535)
- remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4,
- '64:ff9b::',
- 96)
-
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96)
+
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
- self.vapi.set_ipfix_exporter(collector_address=self.pg3.remote_ip4,
- src_address=self.pg3.local_ip4,
- path_mtu=512,
- template_interval=10)
- self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
- src_port=self.ipfix_src_port,
- enable=1)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
+ self.vapi.set_ipfix_exporter(
+ collector_address=self.pg3.remote_ip4,
+ src_address=self.pg3.local_ip4,
+ path_mtu=512,
+ template_interval=10,
+ )
+ self.vapi.nat_ipfix_enable_disable(
+ domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=1
+ )
# Create
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) /
- TCP(sport=self.tcp_port_in, dport=25))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6)
+ / TCP(sport=self.tcp_port_in, dport=25)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1784,8 +1952,7 @@ class TestNAT64(VppTestCase):
self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
self.assertEqual(p[UDP].sport, self.ipfix_src_port)
self.assertEqual(p[UDP].dport, 4739)
- self.assertEqual(p[IPFIX].observationDomainID,
- self.ipfix_domain_id)
+ self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id)
if p.haslayer(Template):
ipfix.add_template(p.getlayer(Template))
# verify events in data set
@@ -1795,20 +1962,20 @@ class TestNAT64(VppTestCase):
if scapy.compat.orb(data[0][230]) == 10:
self.verify_ipfix_bib(data, 1, self.pg0.remote_ip6)
elif scapy.compat.orb(data[0][230]) == 6:
- self.verify_ipfix_nat64_ses(data,
- 1,
- self.pg0.remote_ip6,
- self.pg1.remote_ip4,
- 25)
+ self.verify_ipfix_nat64_ses(
+ data, 1, self.pg0.remote_ip6, self.pg1.remote_ip4, 25
+ )
else:
self.logger.error(ppp("Unexpected or invalid packet: ", p))
# Delete
self.pg_enable_capture(self.pg_interfaces)
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=0)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=0,
+ )
self.vapi.ipfix_flush()
capture = self.pg3.get_capture(2)
# verify events in data set
@@ -1818,44 +1985,44 @@ class TestNAT64(VppTestCase):
self.assertEqual(p[IP].dst, self.pg3.remote_ip4)
self.assertEqual(p[UDP].sport, self.ipfix_src_port)
self.assertEqual(p[UDP].dport, 4739)
- self.assertEqual(p[IPFIX].observationDomainID,
- self.ipfix_domain_id)
+ self.assertEqual(p[IPFIX].observationDomainID, self.ipfix_domain_id)
if p.haslayer(Data):
data = ipfix.decode_data_set(p.getlayer(Set))
if scapy.compat.orb(data[0][230]) == 11:
self.verify_ipfix_bib(data, 0, self.pg0.remote_ip6)
elif scapy.compat.orb(data[0][230]) == 7:
- self.verify_ipfix_nat64_ses(data,
- 0,
- self.pg0.remote_ip6,
- self.pg1.remote_ip4,
- 25)
+ self.verify_ipfix_nat64_ses(
+ data, 0, self.pg0.remote_ip6, self.pg1.remote_ip4, 25
+ )
else:
self.logger.error(ppp("Unexpected or invalid packet: ", p))
def test_syslog_sess(self):
- """ Test syslog session creation and deletion """
+ """Test syslog session creation and deletion"""
self.tcp_port_in = random.randint(1025, 65535)
- remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4,
- '64:ff9b::',
- 96)
-
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=1)
+ remote_host_ip6 = self.compose_ip6(self.pg1.remote_ip4, "64:ff9b::", 96)
+
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=1,
+ )
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat64_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat64_add_del_interface(is_add=1, flags=0,
- sw_if_index=self.pg1.sw_if_index)
- self.vapi.syslog_set_filter(
- self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_INFO)
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat64_add_del_interface(
+ is_add=1, flags=0, sw_if_index=self.pg1.sw_if_index
+ )
+ self.vapi.syslog_set_filter(self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_INFO)
self.vapi.syslog_set_sender(self.pg3.local_ip4, self.pg3.remote_ip4)
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6) /
- TCP(sport=self.tcp_port_in, dport=self.tcp_external_port))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=remote_host_ip6)
+ / TCP(sport=self.tcp_port_in, dport=self.tcp_external_port)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1866,10 +2033,12 @@ class TestNAT64(VppTestCase):
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.vapi.nat64_add_del_pool_addr_range(start_addr=self.nat_addr,
- end_addr=self.nat_addr,
- vrf_id=0xFFFFFFFF,
- is_add=0)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=self.nat_addr,
+ end_addr=self.nat_addr,
+ vrf_id=0xFFFFFFFF,
+ is_add=0,
+ )
capture = self.pg3.get_capture(1)
self.verify_syslog_sess(capture[0][Raw].load, False, True)
@@ -1884,51 +2053,57 @@ class TestNAT64(VppTestCase):
"""
Clear NAT64 configuration.
"""
- self.vapi.nat_ipfix_enable_disable(domain_id=self.ipfix_domain_id,
- src_port=self.ipfix_src_port,
- enable=0)
+ self.vapi.nat_ipfix_enable_disable(
+ domain_id=self.ipfix_domain_id, src_port=self.ipfix_src_port, enable=0
+ )
self.ipfix_src_port = 4739
self.ipfix_domain_id = 1
- self.vapi.syslog_set_filter(
- self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_EMERG)
+ self.vapi.syslog_set_filter(self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_EMERG)
- self.vapi.nat64_set_timeouts(udp=300, tcp_established=7440,
- tcp_transitory=240, icmp=60)
+ self.vapi.nat64_set_timeouts(
+ udp=300, tcp_established=7440, tcp_transitory=240, icmp=60
+ )
interfaces = self.vapi.nat64_interface_dump()
for intf in interfaces:
- self.vapi.nat64_add_del_interface(is_add=0, flags=intf.flags,
- sw_if_index=intf.sw_if_index)
+ self.vapi.nat64_add_del_interface(
+ is_add=0, flags=intf.flags, sw_if_index=intf.sw_if_index
+ )
bib = self.vapi.nat64_bib_dump(proto=255)
for bibe in bib:
if bibe.flags & self.config_flags.NAT_IS_STATIC:
- self.vapi.nat64_add_del_static_bib(i_addr=bibe.i_addr,
- o_addr=bibe.o_addr,
- i_port=bibe.i_port,
- o_port=bibe.o_port,
- proto=bibe.proto,
- vrf_id=bibe.vrf_id,
- is_add=0)
+ self.vapi.nat64_add_del_static_bib(
+ i_addr=bibe.i_addr,
+ o_addr=bibe.o_addr,
+ i_port=bibe.i_port,
+ o_port=bibe.o_port,
+ proto=bibe.proto,
+ vrf_id=bibe.vrf_id,
+ is_add=0,
+ )
adresses = self.vapi.nat64_pool_addr_dump()
for addr in adresses:
- self.vapi.nat64_add_del_pool_addr_range(start_addr=addr.address,
- end_addr=addr.address,
- vrf_id=addr.vrf_id,
- is_add=0)
+ self.vapi.nat64_add_del_pool_addr_range(
+ start_addr=addr.address,
+ end_addr=addr.address,
+ vrf_id=addr.vrf_id,
+ is_add=0,
+ )
prefixes = self.vapi.nat64_prefix_dump()
for prefix in prefixes:
- self.vapi.nat64_add_del_prefix(prefix=str(prefix.prefix),
- vrf_id=prefix.vrf_id, is_add=0)
+ self.vapi.nat64_add_del_prefix(
+ prefix=str(prefix.prefix), vrf_id=prefix.vrf_id, is_add=0
+ )
- bibs = self.statistics.get_counter('/nat64/total-bibs')
+ bibs = self.statistics.get_counter("/nat64/total-bibs")
self.assertEqual(bibs[0][0], 0)
- sessions = self.statistics.get_counter('/nat64/total-sessions')
+ sessions = self.statistics.get_counter("/nat64/total-sessions")
self.assertEqual(sessions[0][0], 0)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_nat66.py b/test/test_nat66.py
index 02b2882a28b..f3bec78ec5a 100644
--- a/test/test_nat66.py
+++ b/test/test_nat66.py
@@ -10,15 +10,32 @@ from io import BytesIO
import scapy.compat
from framework import VppTestCase, VppTestRunner
from ipfix import IPFIX, Set, Template, Data, IPFIXDecoder
-from scapy.all import bind_layers, Packet, ByteEnumField, ShortField, \
- IPField, IntField, LongField, XByteField, FlagsField, FieldLenField, \
- PacketListField
+from scapy.all import (
+ bind_layers,
+ Packet,
+ ByteEnumField,
+ ShortField,
+ IPField,
+ IntField,
+ LongField,
+ XByteField,
+ FlagsField,
+ FieldLenField,
+ PacketListField,
+)
from scapy.data import IP_PROTOS
from scapy.layers.inet import IP, TCP, UDP, ICMP
from scapy.layers.inet import IPerror, TCPerror, UDPerror, ICMPerror
from scapy.layers.inet6 import ICMPv6DestUnreach, IPerror6, IPv6ExtHdrFragment
-from scapy.layers.inet6 import IPv6, ICMPv6EchoRequest, ICMPv6EchoReply, \
- ICMPv6ND_NS, ICMPv6ND_NA, ICMPv6NDOptDstLLAddr, fragment6
+from scapy.layers.inet6 import (
+ IPv6,
+ ICMPv6EchoRequest,
+ ICMPv6EchoReply,
+ ICMPv6ND_NS,
+ ICMPv6ND_NA,
+ ICMPv6NDOptDstLLAddr,
+ fragment6,
+)
from scapy.layers.l2 import Ether, ARP, GRE
from scapy.packet import Raw
from syslog_rfc5424_parser import SyslogMessage, ParseError
@@ -32,13 +49,13 @@ from vpp_papi import VppEnum
class TestNAT66(VppTestCase):
- """ NAT66 Test Cases """
+ """NAT66 Test Cases"""
@classmethod
def setUpClass(cls):
super(TestNAT66, cls).setUpClass()
- cls.nat_addr = 'fd01:ff::2'
+ cls.nat_addr = "fd01:ff::2"
cls.create_pg_interfaces(range(2))
cls.interfaces = list(cls.pg_interfaces)
@@ -67,34 +84,45 @@ class TestNAT66(VppTestCase):
self.plugin_disable()
def test_static(self):
- """ 1:1 NAT66 test """
+ """1:1 NAT66 test"""
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat66_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat66_add_del_interface(is_add=1,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.nat66_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat66_add_del_interface(is_add=1, sw_if_index=self.pg1.sw_if_index)
self.vapi.nat66_add_del_static_mapping(
local_ip_address=self.pg0.remote_ip6,
external_ip_address=self.nat_addr,
- is_add=1)
+ is_add=1,
+ )
# in2out
pkts = []
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) /
- TCP())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6)
+ / TCP()
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) /
- UDP())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6)
+ / UDP()
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) /
- ICMPv6EchoRequest())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6)
+ / ICMPv6EchoRequest()
+ )
pkts.append(p)
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) /
- GRE() / IP() / TCP())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6)
+ / GRE()
+ / IP()
+ / TCP()
+ )
pkts.append(p)
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -112,21 +140,31 @@ class TestNAT66(VppTestCase):
# out2in
pkts = []
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) /
- TCP())
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr)
+ / TCP()
+ )
pkts.append(p)
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) /
- UDP())
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr)
+ / UDP()
+ )
pkts.append(p)
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) /
- ICMPv6EchoReply())
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr)
+ / ICMPv6EchoReply()
+ )
pkts.append(p)
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr) /
- GRE() / IP() / TCP())
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst=self.nat_addr)
+ / GRE()
+ / IP()
+ / TCP()
+ )
pkts.append(p)
self.pg1.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
@@ -146,21 +184,26 @@ class TestNAT66(VppTestCase):
self.assertEqual(sm[0].total_pkts, 8)
def test_check_no_translate(self):
- """ NAT66 translate only when egress interface is outside interface """
+ """NAT66 translate only when egress interface is outside interface"""
flags = self.config_flags.NAT_IS_INSIDE
- self.vapi.nat66_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg0.sw_if_index)
- self.vapi.nat66_add_del_interface(is_add=1, flags=flags,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.nat66_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg0.sw_if_index
+ )
+ self.vapi.nat66_add_del_interface(
+ is_add=1, flags=flags, sw_if_index=self.pg1.sw_if_index
+ )
self.vapi.nat66_add_del_static_mapping(
local_ip_address=self.pg0.remote_ip6,
external_ip_address=self.nat_addr,
- is_add=1)
+ is_add=1,
+ )
# in2out
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6) /
- UDP())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6)
+ / UDP()
+ )
self.pg0.add_stream([p])
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -174,5 +217,5 @@ class TestNAT66(VppTestCase):
raise
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_neighbor.py b/test/test_neighbor.py
index 0cbaf062f12..e1b37a0a124 100644
--- a/test/test_neighbor.py
+++ b/test/test_neighbor.py
@@ -7,8 +7,15 @@ from socket import AF_INET, AF_INET6, inet_pton
from framework import tag_fixme_vpp_workers
from framework import VppTestCase, VppTestRunner
from vpp_neighbor import VppNeighbor, find_nbr
-from vpp_ip_route import VppIpRoute, VppRoutePath, find_route, \
- VppIpTable, DpoProto, FibPathType, VppIpInterfaceAddress
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ find_route,
+ VppIpTable,
+ DpoProto,
+ FibPathType,
+ VppIpInterfaceAddress,
+)
from vpp_papi import VppEnum
from vpp_ip import VppIpPuntRedirect
@@ -28,7 +35,7 @@ arp_opts = {"who-has": 1, "is-at": 2}
class ARPTestCase(VppTestCase):
- """ ARP Test Case """
+ """ARP Test Case"""
@classmethod
def setUpClass(cls):
@@ -125,8 +132,7 @@ class ARPTestCase(VppTestCase):
self.assertEqual(arp.plen, 4)
self.assertEqual(arp.op, arp_opts["is-at"])
self.assertNotEqual(arp.hwsrc, smac)
- self.assertTrue("00:00:5e:00:01" in arp.hwsrc or
- "00:00:5E:00:01" in arp.hwsrc)
+ self.assertTrue("00:00:5e:00:01" in arp.hwsrc or "00:00:5E:00:01" in arp.hwsrc)
self.assertEqual(arp.hwdst, dmac)
self.assertEqual(arp.psrc, sip)
self.assertEqual(arp.pdst, dip)
@@ -155,7 +161,7 @@ class ARPTestCase(VppTestCase):
self.assertEqual(ip.dst, dip)
def test_arp(self):
- """ ARP """
+ """ARP"""
#
# Generate some hosts on the LAN
@@ -168,15 +174,16 @@ class ARPTestCase(VppTestCase):
# - all neighbor events on pg1
# - neighbor events for host[1] on pg1
#
- self.vapi.want_ip_neighbor_events(enable=1,
- pid=os.getpid())
- self.vapi.want_ip_neighbor_events(enable=1,
- pid=os.getpid(),
- sw_if_index=self.pg1.sw_if_index)
- self.vapi.want_ip_neighbor_events(enable=1,
- pid=os.getpid(),
- sw_if_index=self.pg1.sw_if_index,
- ip=self.pg1.remote_hosts[1].ip4)
+ self.vapi.want_ip_neighbor_events(enable=1, pid=os.getpid())
+ self.vapi.want_ip_neighbor_events(
+ enable=1, pid=os.getpid(), sw_if_index=self.pg1.sw_if_index
+ )
+ self.vapi.want_ip_neighbor_events(
+ enable=1,
+ pid=os.getpid(),
+ sw_if_index=self.pg1.sw_if_index,
+ ip=self.pg1.remote_hosts[1].ip4,
+ )
self.logger.info(self.vapi.cli("sh ip neighbor-watcher"))
@@ -184,10 +191,12 @@ class ARPTestCase(VppTestCase):
# Send IP traffic to one of these unresolved hosts.
# expect the generation of an ARP request
#
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[1].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[1].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
@@ -195,38 +204,38 @@ class ARPTestCase(VppTestCase):
rx = self.pg1.get_capture(1)
- self.verify_arp_req(rx[0],
- self.pg1.local_mac,
- self.pg1.local_ip4,
- self.pg1._remote_hosts[1].ip4)
+ self.verify_arp_req(
+ rx[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1._remote_hosts[1].ip4
+ )
#
# And a dynamic ARP entry for host 1
#
- dyn_arp = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[1].mac,
- self.pg1.remote_hosts[1].ip4)
+ dyn_arp = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[1].mac,
+ self.pg1.remote_hosts[1].ip4,
+ )
dyn_arp.add_vpp_config()
self.assertTrue(dyn_arp.query_vpp_config())
self.logger.info(self.vapi.cli("show ip neighbor-watcher"))
# this matches all of the listnerers
- es = [self.vapi.wait_for_event(1, "ip_neighbor_event")
- for i in range(3)]
+ es = [self.vapi.wait_for_event(1, "ip_neighbor_event") for i in range(3)]
for e in es:
- self.assertEqual(str(e.neighbor.ip_address),
- self.pg1.remote_hosts[1].ip4)
+ self.assertEqual(str(e.neighbor.ip_address), self.pg1.remote_hosts[1].ip4)
#
# now we expect IP traffic forwarded
#
- dyn_p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1._remote_hosts[1].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ dyn_p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[1].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
self.pg0.add_stream(dyn_p)
self.pg_enable_capture(self.pg_interfaces)
@@ -234,32 +243,35 @@ class ARPTestCase(VppTestCase):
rx = self.pg1.get_capture(1)
- self.verify_ip(rx[0],
- self.pg1.local_mac,
- self.pg1.remote_hosts[1].mac,
- self.pg0.remote_ip4,
- self.pg1._remote_hosts[1].ip4)
+ self.verify_ip(
+ rx[0],
+ self.pg1.local_mac,
+ self.pg1.remote_hosts[1].mac,
+ self.pg0.remote_ip4,
+ self.pg1._remote_hosts[1].ip4,
+ )
#
# And a Static ARP entry for host 2
#
- static_arp = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[2].mac,
- self.pg1.remote_hosts[2].ip4,
- is_static=1)
+ static_arp = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[2].mac,
+ self.pg1.remote_hosts[2].ip4,
+ is_static=1,
+ )
static_arp.add_vpp_config()
- es = [self.vapi.wait_for_event(1, "ip_neighbor_event")
- for i in range(2)]
+ es = [self.vapi.wait_for_event(1, "ip_neighbor_event") for i in range(2)]
for e in es:
- self.assertEqual(str(e.neighbor.ip_address),
- self.pg1.remote_hosts[2].ip4)
+ self.assertEqual(str(e.neighbor.ip_address), self.pg1.remote_hosts[2].ip4)
- static_p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1._remote_hosts[2].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ static_p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[2].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
self.pg0.add_stream(static_p)
self.pg_enable_capture(self.pg_interfaces)
@@ -267,24 +279,27 @@ class ARPTestCase(VppTestCase):
rx = self.pg1.get_capture(1)
- self.verify_ip(rx[0],
- self.pg1.local_mac,
- self.pg1.remote_hosts[2].mac,
- self.pg0.remote_ip4,
- self.pg1._remote_hosts[2].ip4)
+ self.verify_ip(
+ rx[0],
+ self.pg1.local_mac,
+ self.pg1.remote_hosts[2].mac,
+ self.pg0.remote_ip4,
+ self.pg1._remote_hosts[2].ip4,
+ )
#
# remove all the listeners
#
- self.vapi.want_ip_neighbor_events(enable=0,
- pid=os.getpid())
- self.vapi.want_ip_neighbor_events(enable=0,
- pid=os.getpid(),
- sw_if_index=self.pg1.sw_if_index)
- self.vapi.want_ip_neighbor_events(enable=0,
- pid=os.getpid(),
- sw_if_index=self.pg1.sw_if_index,
- ip=self.pg1.remote_hosts[1].ip4)
+ self.vapi.want_ip_neighbor_events(enable=0, pid=os.getpid())
+ self.vapi.want_ip_neighbor_events(
+ enable=0, pid=os.getpid(), sw_if_index=self.pg1.sw_if_index
+ )
+ self.vapi.want_ip_neighbor_events(
+ enable=0,
+ pid=os.getpid(),
+ sw_if_index=self.pg1.sw_if_index,
+ ip=self.pg1.remote_hosts[1].ip4,
+ )
#
# flap the link. dynamic ARPs get flush, statics don't
@@ -297,69 +312,76 @@ class ARPTestCase(VppTestCase):
self.pg_start()
rx = self.pg1.get_capture(1)
- self.verify_ip(rx[0],
- self.pg1.local_mac,
- self.pg1.remote_hosts[2].mac,
- self.pg0.remote_ip4,
- self.pg1._remote_hosts[2].ip4)
+ self.verify_ip(
+ rx[0],
+ self.pg1.local_mac,
+ self.pg1.remote_hosts[2].mac,
+ self.pg0.remote_ip4,
+ self.pg1._remote_hosts[2].ip4,
+ )
self.pg0.add_stream(dyn_p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg1.get_capture(1)
- self.verify_arp_req(rx[0],
- self.pg1.local_mac,
- self.pg1.local_ip4,
- self.pg1._remote_hosts[1].ip4)
+ self.verify_arp_req(
+ rx[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1._remote_hosts[1].ip4
+ )
self.assertFalse(dyn_arp.query_vpp_config())
self.assertTrue(static_arp.query_vpp_config())
#
# Send an ARP request from one of the so-far unlearned remote hosts
#
- p = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg1._remote_hosts[3].mac) /
- ARP(op="who-has",
- hwsrc=self.pg1._remote_hosts[3].mac,
- pdst=self.pg1.local_ip4,
- psrc=self.pg1._remote_hosts[3].ip4))
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1._remote_hosts[3].mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg1._remote_hosts[3].mac,
+ pdst=self.pg1.local_ip4,
+ psrc=self.pg1._remote_hosts[3].ip4,
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg1.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg1.local_mac,
- self.pg1._remote_hosts[3].mac,
- self.pg1.local_ip4,
- self.pg1._remote_hosts[3].ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg1.local_mac,
+ self.pg1._remote_hosts[3].mac,
+ self.pg1.local_ip4,
+ self.pg1._remote_hosts[3].ip4,
+ )
#
# VPP should have learned the mapping for the remote host
#
- self.assertTrue(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg1._remote_hosts[3].ip4))
+ self.assertTrue(
+ find_nbr(self, self.pg1.sw_if_index, self.pg1._remote_hosts[3].ip4)
+ )
#
# Fire in an ARP request before the interface becomes IP enabled
#
self.pg2.generate_remote_hosts(4)
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg2.remote_mac,
- pdst=self.pg1.local_ip4,
- psrc=self.pg2.remote_hosts[3].ip4))
- pt = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) /
- Dot1Q(vlan=0) /
- ARP(op="who-has",
- hwsrc=self.pg2.remote_mac,
- pdst=self.pg1.local_ip4,
- psrc=self.pg2.remote_hosts[3].ip4))
- self.send_and_assert_no_replies(self.pg2, p,
- "interface not IP enabled")
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg2.remote_mac,
+ pdst=self.pg1.local_ip4,
+ psrc=self.pg2.remote_hosts[3].ip4,
+ )
+ pt = (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac)
+ / Dot1Q(vlan=0)
+ / ARP(
+ op="who-has",
+ hwsrc=self.pg2.remote_mac,
+ pdst=self.pg1.local_ip4,
+ psrc=self.pg2.remote_hosts[3].ip4,
+ )
+ )
+ self.send_and_assert_no_replies(self.pg2, p, "interface not IP enabled")
#
# Make pg2 un-numbered to pg1
@@ -384,12 +406,15 @@ class ARPTestCase(VppTestCase):
# once an attached route to the source is known
#
self.send_and_assert_no_replies(
- self.pg2, p,
- "ARP req for unnumbered address - no source")
-
- attached_host = VppIpRoute(self, self.pg2.remote_hosts[3].ip4, 32,
- [VppRoutePath("0.0.0.0",
- self.pg2.sw_if_index)])
+ self.pg2, p, "ARP req for unnumbered address - no source"
+ )
+
+ attached_host = VppIpRoute(
+ self,
+ self.pg2.remote_hosts[3].ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", self.pg2.sw_if_index)],
+ )
attached_host.add_vpp_config()
self.pg2.add_stream(p)
@@ -397,57 +422,64 @@ class ARPTestCase(VppTestCase):
self.pg_start()
rx = self.pg2.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg2.local_mac,
- self.pg2.remote_mac,
- self.pg1.local_ip4,
- self.pg2.remote_hosts[3].ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg2.local_mac,
+ self.pg2.remote_mac,
+ self.pg1.local_ip4,
+ self.pg2.remote_hosts[3].ip4,
+ )
self.pg2.add_stream(pt)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg2.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg2.local_mac,
- self.pg2.remote_mac,
- self.pg1.local_ip4,
- self.pg2.remote_hosts[3].ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg2.local_mac,
+ self.pg2.remote_mac,
+ self.pg1.local_ip4,
+ self.pg2.remote_hosts[3].ip4,
+ )
#
# A neighbor entry that has no associated FIB-entry
#
- arp_no_fib = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[4].mac,
- self.pg1.remote_hosts[4].ip4,
- is_no_fib_entry=1)
+ arp_no_fib = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[4].mac,
+ self.pg1.remote_hosts[4].ip4,
+ is_no_fib_entry=1,
+ )
arp_no_fib.add_vpp_config()
#
# check we have the neighbor, but no route
#
- self.assertTrue(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg1._remote_hosts[4].ip4))
- self.assertFalse(find_route(self,
- self.pg1._remote_hosts[4].ip4,
- 32))
+ self.assertTrue(
+ find_nbr(self, self.pg1.sw_if_index, self.pg1._remote_hosts[4].ip4)
+ )
+ self.assertFalse(find_route(self, self.pg1._remote_hosts[4].ip4, 32))
#
# pg2 is unnumbered to pg1, so we can form adjacencies out of pg2
# from within pg1's subnet
#
- arp_unnum = VppNeighbor(self,
- self.pg2.sw_if_index,
- self.pg1.remote_hosts[5].mac,
- self.pg1.remote_hosts[5].ip4)
+ arp_unnum = VppNeighbor(
+ self,
+ self.pg2.sw_if_index,
+ self.pg1.remote_hosts[5].mac,
+ self.pg1.remote_hosts[5].ip4,
+ )
arp_unnum.add_vpp_config()
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1._remote_hosts[5].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[5].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
@@ -455,47 +487,56 @@ class ARPTestCase(VppTestCase):
rx = self.pg2.get_capture(1)
- self.verify_ip(rx[0],
- self.pg2.local_mac,
- self.pg1.remote_hosts[5].mac,
- self.pg0.remote_ip4,
- self.pg1._remote_hosts[5].ip4)
+ self.verify_ip(
+ rx[0],
+ self.pg2.local_mac,
+ self.pg1.remote_hosts[5].mac,
+ self.pg0.remote_ip4,
+ self.pg1._remote_hosts[5].ip4,
+ )
#
# ARP requests from hosts in pg1's subnet sent on pg2 are replied to
# with the unnumbered interface's address as the source
#
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg2.remote_mac,
- pdst=self.pg1.local_ip4,
- psrc=self.pg1.remote_hosts[6].ip4))
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg2.remote_mac,
+ pdst=self.pg1.local_ip4,
+ psrc=self.pg1.remote_hosts[6].ip4,
+ )
self.pg2.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg2.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg2.local_mac,
- self.pg2.remote_mac,
- self.pg1.local_ip4,
- self.pg1.remote_hosts[6].ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg2.local_mac,
+ self.pg2.remote_mac,
+ self.pg1.local_ip4,
+ self.pg1.remote_hosts[6].ip4,
+ )
#
# An attached host route out of pg2 for an undiscovered hosts generates
# an ARP request with the unnumbered address as the source
#
- att_unnum = VppIpRoute(self, self.pg1.remote_hosts[7].ip4, 32,
- [VppRoutePath("0.0.0.0",
- self.pg2.sw_if_index)])
+ att_unnum = VppIpRoute(
+ self,
+ self.pg1.remote_hosts[7].ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", self.pg2.sw_if_index)],
+ )
att_unnum.add_vpp_config()
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1._remote_hosts[7].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1._remote_hosts[7].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
@@ -503,135 +544,158 @@ class ARPTestCase(VppTestCase):
rx = self.pg2.get_capture(1)
- self.verify_arp_req(rx[0],
- self.pg2.local_mac,
- self.pg1.local_ip4,
- self.pg1._remote_hosts[7].ip4)
+ self.verify_arp_req(
+ rx[0], self.pg2.local_mac, self.pg1.local_ip4, self.pg1._remote_hosts[7].ip4
+ )
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg2.remote_mac,
- pdst=self.pg1.local_ip4,
- psrc=self.pg1.remote_hosts[7].ip4))
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg2.remote_mac,
+ pdst=self.pg1.local_ip4,
+ psrc=self.pg1.remote_hosts[7].ip4,
+ )
self.pg2.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg2.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg2.local_mac,
- self.pg2.remote_mac,
- self.pg1.local_ip4,
- self.pg1.remote_hosts[7].ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg2.local_mac,
+ self.pg2.remote_mac,
+ self.pg1.local_ip4,
+ self.pg1.remote_hosts[7].ip4,
+ )
#
# An attached host route as yet unresolved out of pg2 for an
# undiscovered host, an ARP requests begets a response.
#
- att_unnum1 = VppIpRoute(self, self.pg1.remote_hosts[8].ip4, 32,
- [VppRoutePath("0.0.0.0",
- self.pg2.sw_if_index)])
+ att_unnum1 = VppIpRoute(
+ self,
+ self.pg1.remote_hosts[8].ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", self.pg2.sw_if_index)],
+ )
att_unnum1.add_vpp_config()
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg2.remote_mac,
- pdst=self.pg1.local_ip4,
- psrc=self.pg1.remote_hosts[8].ip4))
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg2.remote_mac,
+ pdst=self.pg1.local_ip4,
+ psrc=self.pg1.remote_hosts[8].ip4,
+ )
self.pg2.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg2.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg2.local_mac,
- self.pg2.remote_mac,
- self.pg1.local_ip4,
- self.pg1.remote_hosts[8].ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg2.local_mac,
+ self.pg2.remote_mac,
+ self.pg1.local_ip4,
+ self.pg1.remote_hosts[8].ip4,
+ )
#
# Send an ARP request from one of the so-far unlearned remote hosts
# with a VLAN0 tag
#
- p = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg1._remote_hosts[9].mac) /
- Dot1Q(vlan=0) /
- ARP(op="who-has",
- hwsrc=self.pg1._remote_hosts[9].mac,
- pdst=self.pg1.local_ip4,
- psrc=self.pg1._remote_hosts[9].ip4))
+ p = (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1._remote_hosts[9].mac)
+ / Dot1Q(vlan=0)
+ / ARP(
+ op="who-has",
+ hwsrc=self.pg1._remote_hosts[9].mac,
+ pdst=self.pg1.local_ip4,
+ psrc=self.pg1._remote_hosts[9].ip4,
+ )
+ )
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg1.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg1.local_mac,
- self.pg1._remote_hosts[9].mac,
- self.pg1.local_ip4,
- self.pg1._remote_hosts[9].ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg1.local_mac,
+ self.pg1._remote_hosts[9].mac,
+ self.pg1.local_ip4,
+ self.pg1._remote_hosts[9].ip4,
+ )
#
# Add a hierarchy of routes for a host in the sub-net.
# Should still get an ARP resp since the cover is attached
#
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg1.remote_mac,
- pdst=self.pg1.local_ip4,
- psrc=self.pg1.remote_hosts[10].ip4))
-
- r1 = VppIpRoute(self, self.pg1.remote_hosts[10].ip4, 30,
- [VppRoutePath(self.pg1.remote_hosts[10].ip4,
- self.pg1.sw_if_index)])
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg1.remote_mac,
+ pdst=self.pg1.local_ip4,
+ psrc=self.pg1.remote_hosts[10].ip4,
+ )
+
+ r1 = VppIpRoute(
+ self,
+ self.pg1.remote_hosts[10].ip4,
+ 30,
+ [VppRoutePath(self.pg1.remote_hosts[10].ip4, self.pg1.sw_if_index)],
+ )
r1.add_vpp_config()
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg1.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg1.local_mac,
- self.pg1.remote_mac,
- self.pg1.local_ip4,
- self.pg1.remote_hosts[10].ip4)
-
- r2 = VppIpRoute(self, self.pg1.remote_hosts[10].ip4, 32,
- [VppRoutePath(self.pg1.remote_hosts[10].ip4,
- self.pg1.sw_if_index)])
+ self.verify_arp_resp(
+ rx[0],
+ self.pg1.local_mac,
+ self.pg1.remote_mac,
+ self.pg1.local_ip4,
+ self.pg1.remote_hosts[10].ip4,
+ )
+
+ r2 = VppIpRoute(
+ self,
+ self.pg1.remote_hosts[10].ip4,
+ 32,
+ [VppRoutePath(self.pg1.remote_hosts[10].ip4, self.pg1.sw_if_index)],
+ )
r2.add_vpp_config()
self.pg1.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg1.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg1.local_mac,
- self.pg1.remote_mac,
- self.pg1.local_ip4,
- self.pg1.remote_hosts[10].ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg1.local_mac,
+ self.pg1.remote_mac,
+ self.pg1.local_ip4,
+ self.pg1.remote_hosts[10].ip4,
+ )
#
# add an ARP entry that's not on the sub-net and so whose
# adj-fib fails the refinement check. then send an ARP request
# from that source
#
- a1 = VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_mac,
- "100.100.100.50")
+ a1 = VppNeighbor(
+ self, self.pg0.sw_if_index, self.pg0.remote_mac, "100.100.100.50"
+ )
a1.add_vpp_config()
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg0.remote_mac,
- psrc="100.100.100.50",
- pdst=self.pg0.remote_ip4))
- self.send_and_assert_no_replies(self.pg0, p,
- "ARP req for from failed adj-fib")
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg0.remote_mac,
+ psrc="100.100.100.50",
+ pdst=self.pg0.remote_ip4,
+ )
+ self.send_and_assert_no_replies(self.pg0, p, "ARP req for from failed adj-fib")
#
# ERROR Cases
@@ -640,101 +704,103 @@ class ARPTestCase(VppTestCase):
# 1b - nor within the unnumbered subnet
# 1c - nor within the subnet of a different interface
#
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg0.remote_mac,
- pdst="10.10.10.3",
- psrc=self.pg0.remote_ip4))
- self.send_and_assert_no_replies(self.pg0, p,
- "ARP req for non-local destination")
- self.assertFalse(find_nbr(self,
- self.pg0.sw_if_index,
- "10.10.10.3"))
-
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg2.remote_mac,
- pdst="10.10.10.3",
- psrc=self.pg1.remote_hosts[7].ip4))
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg0.remote_mac,
+ pdst="10.10.10.3",
+ psrc=self.pg0.remote_ip4,
+ )
+ self.send_and_assert_no_replies(
+ self.pg0, p, "ARP req for non-local destination"
+ )
+ self.assertFalse(find_nbr(self, self.pg0.sw_if_index, "10.10.10.3"))
+
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg2.remote_mac,
+ pdst="10.10.10.3",
+ psrc=self.pg1.remote_hosts[7].ip4,
+ )
self.send_and_assert_no_replies(
- self.pg0, p,
- "ARP req for non-local destination - unnum")
+ self.pg0, p, "ARP req for non-local destination - unnum"
+ )
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg0.remote_mac,
- pdst=self.pg1.local_ip4,
- psrc=self.pg1.remote_ip4))
- self.send_and_assert_no_replies(self.pg0, p,
- "ARP req diff sub-net")
- self.assertFalse(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg1.remote_ip4))
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg0.remote_mac,
+ pdst=self.pg1.local_ip4,
+ psrc=self.pg1.remote_ip4,
+ )
+ self.send_and_assert_no_replies(self.pg0, p, "ARP req diff sub-net")
+ self.assertFalse(find_nbr(self, self.pg0.sw_if_index, self.pg1.remote_ip4))
#
# 2 - don't respond to ARP request from an address not within the
# interface's sub-net
# 2b - to a proxied address
# 2c - not within a different interface's sub-net
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg0.remote_mac,
- psrc="10.10.10.3",
- pdst=self.pg0.local_ip4))
- self.send_and_assert_no_replies(self.pg0, p,
- "ARP req for non-local source")
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg2.remote_mac,
- psrc="10.10.10.3",
- pdst=self.pg0.local_ip4))
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg0.remote_mac,
+ psrc="10.10.10.3",
+ pdst=self.pg0.local_ip4,
+ )
+ self.send_and_assert_no_replies(self.pg0, p, "ARP req for non-local source")
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg2.remote_mac,
+ psrc="10.10.10.3",
+ pdst=self.pg0.local_ip4,
+ )
self.send_and_assert_no_replies(
- self.pg0, p,
- "ARP req for non-local source - unnum")
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg0.remote_mac,
- psrc=self.pg1.remote_ip4,
- pdst=self.pg0.local_ip4))
- self.send_and_assert_no_replies(self.pg0, p,
- "ARP req for non-local source 2c")
+ self.pg0, p, "ARP req for non-local source - unnum"
+ )
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg0.remote_mac,
+ psrc=self.pg1.remote_ip4,
+ pdst=self.pg0.local_ip4,
+ )
+ self.send_and_assert_no_replies(self.pg0, p, "ARP req for non-local source 2c")
#
# 3 - don't respond to ARP request from an address that belongs to
# the router
#
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg0.remote_mac,
- psrc=self.pg0.local_ip4,
- pdst=self.pg0.local_ip4))
- self.send_and_assert_no_replies(self.pg0, p,
- "ARP req for non-local source")
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg0.remote_mac,
+ psrc=self.pg0.local_ip4,
+ pdst=self.pg0.local_ip4,
+ )
+ self.send_and_assert_no_replies(self.pg0, p, "ARP req for non-local source")
#
# 4 - don't respond to ARP requests that has mac source different
# from ARP request HW source
#
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) /
- ARP(op="who-has",
- hwsrc="00:00:00:DE:AD:BE",
- psrc=self.pg0.remote_ip4,
- pdst=self.pg0.local_ip4))
- self.send_and_assert_no_replies(self.pg0, p,
- "ARP req for non-local source")
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op="who-has",
+ hwsrc="00:00:00:DE:AD:BE",
+ psrc=self.pg0.remote_ip4,
+ pdst=self.pg0.local_ip4,
+ )
+ self.send_and_assert_no_replies(self.pg0, p, "ARP req for non-local source")
#
# 5 - don't respond to ARP requests for address within the
# interface's sub-net but not the interface's address
#
self.pg0.generate_remote_hosts(2)
- p = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) /
- ARP(op="who-has",
- hwsrc=self.pg0.remote_mac,
- psrc=self.pg0.remote_hosts[0].ip4,
- pdst=self.pg0.remote_hosts[1].ip4))
- self.send_and_assert_no_replies(self.pg0, p,
- "ARP req for non-local destination")
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op="who-has",
+ hwsrc=self.pg0.remote_mac,
+ psrc=self.pg0.remote_hosts[0].ip4,
+ pdst=self.pg0.remote_hosts[1].ip4,
+ )
+ self.send_and_assert_no_replies(
+ self.pg0, p, "ARP req for non-local destination"
+ )
#
# cleanup
@@ -748,7 +814,7 @@ class ARPTestCase(VppTestCase):
self.pg1.admin_down()
def test_proxy_mirror_arp(self):
- """ Interface Mirror Proxy ARP """
+ """Interface Mirror Proxy ARP"""
#
# When VPP has an interface whose address is also applied to a TAP
@@ -759,20 +825,24 @@ class ARPTestCase(VppTestCase):
#
self.pg0.generate_remote_hosts(2)
- arp_req_from_me = (Ether(src=self.pg2.remote_mac,
- dst="ff:ff:ff:ff:ff:ff") /
- ARP(op="who-has",
- hwsrc=self.pg2.remote_mac,
- pdst=self.pg0.remote_hosts[1].ip4,
- psrc=self.pg0.local_ip4))
+ arp_req_from_me = Ether(src=self.pg2.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op="who-has",
+ hwsrc=self.pg2.remote_mac,
+ pdst=self.pg0.remote_hosts[1].ip4,
+ psrc=self.pg0.local_ip4,
+ )
#
# Configure Proxy ARP for the subnet on PG0addresses on pg0
#
- self.vapi.proxy_arp_add_del(proxy={'table_id': 0,
- 'low': self.pg0._local_ip4_subnet,
- 'hi': self.pg0._local_ip4_bcast},
- is_add=1)
+ self.vapi.proxy_arp_add_del(
+ proxy={
+ "table_id": 0,
+ "low": self.pg0._local_ip4_subnet,
+ "hi": self.pg0._local_ip4_bcast,
+ },
+ is_add=1,
+ )
# Make pg2 un-numbered to pg0
#
@@ -788,43 +858,49 @@ class ARPTestCase(VppTestCase):
# is VPP's own address
#
rx = self.send_and_expect(self.pg2, [arp_req_from_me], self.pg2)
- self.verify_arp_resp(rx[0],
- self.pg2.local_mac,
- self.pg2.remote_mac,
- self.pg0.remote_hosts[1].ip4,
- self.pg0.local_ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg2.local_mac,
+ self.pg2.remote_mac,
+ self.pg0.remote_hosts[1].ip4,
+ self.pg0.local_ip4,
+ )
#
# validate we have not learned an ARP entry as a result of this
#
- self.assertFalse(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg0.local_ip4))
+ self.assertFalse(find_nbr(self, self.pg2.sw_if_index, self.pg0.local_ip4))
#
# setup a punt redirect so packets from the uplink go to the tap
#
- redirect = VppIpPuntRedirect(self, self.pg0.sw_if_index,
- self.pg2.sw_if_index, self.pg0.local_ip4)
+ redirect = VppIpPuntRedirect(
+ self, self.pg0.sw_if_index, self.pg2.sw_if_index, self.pg0.local_ip4
+ )
redirect.add_vpp_config()
- p_tcp = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac,) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg0.local_ip4) /
- TCP(sport=80, dport=80) /
- Raw())
+ p_tcp = (
+ Ether(
+ src=self.pg0.remote_mac,
+ dst=self.pg0.local_mac,
+ )
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / TCP(sport=80, dport=80)
+ / Raw()
+ )
rx = self.send_and_expect(self.pg0, [p_tcp], self.pg2)
# there's no ARP entry so this is an ARP req
self.assertTrue(rx[0].haslayer(ARP))
# and ARP entry for VPP's pg0 address on the host interface
- n1 = VppNeighbor(self,
- self.pg2.sw_if_index,
- self.pg2.remote_mac,
- self.pg0.local_ip4,
- is_no_fib_entry=True).add_vpp_config()
+ n1 = VppNeighbor(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_mac,
+ self.pg0.local_ip4,
+ is_no_fib_entry=True,
+ ).add_vpp_config()
# now the packets shold forward
rx = self.send_and_expect(self.pg0, [p_tcp], self.pg2)
self.assertFalse(rx[0].haslayer(ARP))
@@ -839,75 +915,81 @@ class ARPTestCase(VppTestCase):
# ensure we can still resolve the ARPs on the uplink
self.pg0.resolve_arp()
- self.assertTrue(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0.remote_ip4))
+ self.assertTrue(find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_ip4))
#
# cleanup
#
- self.vapi.proxy_arp_add_del(proxy={'table_id': 0,
- 'low': self.pg0._local_ip4_subnet,
- 'hi': self.pg0._local_ip4_bcast},
- is_add=0)
+ self.vapi.proxy_arp_add_del(
+ proxy={
+ "table_id": 0,
+ "low": self.pg0._local_ip4_subnet,
+ "hi": self.pg0._local_ip4_bcast,
+ },
+ is_add=0,
+ )
redirect.remove_vpp_config()
def test_proxy_arp(self):
- """ Proxy ARP """
+ """Proxy ARP"""
self.pg1.generate_remote_hosts(2)
#
# Proxy ARP request packets for each interface
#
- arp_req_pg0 = (Ether(src=self.pg0.remote_mac,
- dst="ff:ff:ff:ff:ff:ff") /
- ARP(op="who-has",
- hwsrc=self.pg0.remote_mac,
- pdst="10.10.10.3",
- psrc=self.pg0.remote_ip4))
- arp_req_pg0_tagged = (Ether(src=self.pg0.remote_mac,
- dst="ff:ff:ff:ff:ff:ff") /
- Dot1Q(vlan=0) /
- ARP(op="who-has",
- hwsrc=self.pg0.remote_mac,
- pdst="10.10.10.3",
- psrc=self.pg0.remote_ip4))
- arp_req_pg1 = (Ether(src=self.pg1.remote_mac,
- dst="ff:ff:ff:ff:ff:ff") /
- ARP(op="who-has",
- hwsrc=self.pg1.remote_mac,
- pdst="10.10.10.3",
- psrc=self.pg1.remote_ip4))
- arp_req_pg2 = (Ether(src=self.pg2.remote_mac,
- dst="ff:ff:ff:ff:ff:ff") /
- ARP(op="who-has",
- hwsrc=self.pg2.remote_mac,
- pdst="10.10.10.3",
- psrc=self.pg1.remote_hosts[1].ip4))
- arp_req_pg3 = (Ether(src=self.pg3.remote_mac,
- dst="ff:ff:ff:ff:ff:ff") /
- ARP(op="who-has",
- hwsrc=self.pg3.remote_mac,
- pdst="10.10.10.3",
- psrc=self.pg3.remote_ip4))
+ arp_req_pg0 = Ether(src=self.pg0.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op="who-has",
+ hwsrc=self.pg0.remote_mac,
+ pdst="10.10.10.3",
+ psrc=self.pg0.remote_ip4,
+ )
+ arp_req_pg0_tagged = (
+ Ether(src=self.pg0.remote_mac, dst="ff:ff:ff:ff:ff:ff")
+ / Dot1Q(vlan=0)
+ / ARP(
+ op="who-has",
+ hwsrc=self.pg0.remote_mac,
+ pdst="10.10.10.3",
+ psrc=self.pg0.remote_ip4,
+ )
+ )
+ arp_req_pg1 = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op="who-has",
+ hwsrc=self.pg1.remote_mac,
+ pdst="10.10.10.3",
+ psrc=self.pg1.remote_ip4,
+ )
+ arp_req_pg2 = Ether(src=self.pg2.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op="who-has",
+ hwsrc=self.pg2.remote_mac,
+ pdst="10.10.10.3",
+ psrc=self.pg1.remote_hosts[1].ip4,
+ )
+ arp_req_pg3 = Ether(src=self.pg3.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op="who-has",
+ hwsrc=self.pg3.remote_mac,
+ pdst="10.10.10.3",
+ psrc=self.pg3.remote_ip4,
+ )
#
# Configure Proxy ARP for 10.10.10.0 -> 10.10.10.124
#
- self.vapi.proxy_arp_add_del(proxy={'table_id': 0,
- 'low': "10.10.10.2",
- 'hi': "10.10.10.124"},
- is_add=1)
+ self.vapi.proxy_arp_add_del(
+ proxy={"table_id": 0, "low": "10.10.10.2", "hi": "10.10.10.124"}, is_add=1
+ )
#
# No responses are sent when the interfaces are not enabled for proxy
# ARP
#
- self.send_and_assert_no_replies(self.pg0, arp_req_pg0,
- "ARP req from unconfigured interface")
- self.send_and_assert_no_replies(self.pg2, arp_req_pg2,
- "ARP req from unconfigured interface")
+ self.send_and_assert_no_replies(
+ self.pg0, arp_req_pg0, "ARP req from unconfigured interface"
+ )
+ self.send_and_assert_no_replies(
+ self.pg2, arp_req_pg2, "ARP req from unconfigured interface"
+ )
#
# Make pg2 un-numbered to pg1
@@ -915,8 +997,9 @@ class ARPTestCase(VppTestCase):
#
self.pg2.set_unnumbered(self.pg1.sw_if_index)
- self.send_and_assert_no_replies(self.pg2, arp_req_pg2,
- "ARP req from unnumbered interface")
+ self.send_and_assert_no_replies(
+ self.pg2, arp_req_pg2, "ARP req from unnumbered interface"
+ )
#
# Enable each interface to reply to proxy ARPs
@@ -933,71 +1016,82 @@ class ARPTestCase(VppTestCase):
self.pg_start()
rx = self.pg0.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg0.local_mac,
- self.pg0.remote_mac,
- "10.10.10.3",
- self.pg0.remote_ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg0.local_mac,
+ self.pg0.remote_mac,
+ "10.10.10.3",
+ self.pg0.remote_ip4,
+ )
self.pg0.add_stream(arp_req_pg0_tagged)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg0.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg0.local_mac,
- self.pg0.remote_mac,
- "10.10.10.3",
- self.pg0.remote_ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg0.local_mac,
+ self.pg0.remote_mac,
+ "10.10.10.3",
+ self.pg0.remote_ip4,
+ )
self.pg1.add_stream(arp_req_pg1)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg1.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg1.local_mac,
- self.pg1.remote_mac,
- "10.10.10.3",
- self.pg1.remote_ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg1.local_mac,
+ self.pg1.remote_mac,
+ "10.10.10.3",
+ self.pg1.remote_ip4,
+ )
self.pg2.add_stream(arp_req_pg2)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg2.get_capture(1)
- self.verify_arp_resp(rx[0],
- self.pg2.local_mac,
- self.pg2.remote_mac,
- "10.10.10.3",
- self.pg1.remote_hosts[1].ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg2.local_mac,
+ self.pg2.remote_mac,
+ "10.10.10.3",
+ self.pg1.remote_hosts[1].ip4,
+ )
#
# A request for an address out of the configured range
#
- arp_req_pg1_hi = (Ether(src=self.pg1.remote_mac,
- dst="ff:ff:ff:ff:ff:ff") /
- ARP(op="who-has",
- hwsrc=self.pg1.remote_mac,
- pdst="10.10.10.125",
- psrc=self.pg1.remote_ip4))
- self.send_and_assert_no_replies(self.pg1, arp_req_pg1_hi,
- "ARP req out of range HI")
- arp_req_pg1_low = (Ether(src=self.pg1.remote_mac,
- dst="ff:ff:ff:ff:ff:ff") /
- ARP(op="who-has",
- hwsrc=self.pg1.remote_mac,
- pdst="10.10.10.1",
- psrc=self.pg1.remote_ip4))
- self.send_and_assert_no_replies(self.pg1, arp_req_pg1_low,
- "ARP req out of range Low")
+ arp_req_pg1_hi = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op="who-has",
+ hwsrc=self.pg1.remote_mac,
+ pdst="10.10.10.125",
+ psrc=self.pg1.remote_ip4,
+ )
+ self.send_and_assert_no_replies(
+ self.pg1, arp_req_pg1_hi, "ARP req out of range HI"
+ )
+ arp_req_pg1_low = Ether(src=self.pg1.remote_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
+ op="who-has",
+ hwsrc=self.pg1.remote_mac,
+ pdst="10.10.10.1",
+ psrc=self.pg1.remote_ip4,
+ )
+ self.send_and_assert_no_replies(
+ self.pg1, arp_req_pg1_low, "ARP req out of range Low"
+ )
#
# Request for an address in the proxy range but from an interface
# in a different VRF
#
- self.send_and_assert_no_replies(self.pg3, arp_req_pg3,
- "ARP req from different VRF")
+ self.send_and_assert_no_replies(
+ self.pg3, arp_req_pg3, "ARP req from different VRF"
+ )
#
# Disable Each interface for proxy ARP
@@ -1006,12 +1100,9 @@ class ARPTestCase(VppTestCase):
for i in self.pg_interfaces:
i.set_proxy_arp(0)
- self.send_and_assert_no_replies(self.pg0, arp_req_pg0,
- "ARP req from disable")
- self.send_and_assert_no_replies(self.pg1, arp_req_pg1,
- "ARP req from disable")
- self.send_and_assert_no_replies(self.pg2, arp_req_pg2,
- "ARP req from disable")
+ self.send_and_assert_no_replies(self.pg0, arp_req_pg0, "ARP req from disable")
+ self.send_and_assert_no_replies(self.pg1, arp_req_pg1, "ARP req from disable")
+ self.send_and_assert_no_replies(self.pg2, arp_req_pg2, "ARP req from disable")
#
# clean up on interface 2
@@ -1019,7 +1110,7 @@ class ARPTestCase(VppTestCase):
self.pg2.unset_unnumbered(self.pg1.sw_if_index)
def test_mpls(self):
- """ MPLS """
+ """MPLS"""
#
# Interface 2 does not yet have ip4 config
@@ -1030,30 +1121,36 @@ class ARPTestCase(VppTestCase):
#
# Add a route with out going label via an ARP unresolved next-hop
#
- ip_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- [VppRoutePath(self.pg2.remote_hosts[1].ip4,
- self.pg2.sw_if_index,
- labels=[55])])
+ ip_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ [
+ VppRoutePath(
+ self.pg2.remote_hosts[1].ip4, self.pg2.sw_if_index, labels=[55]
+ )
+ ],
+ )
ip_10_0_0_1.add_vpp_config()
#
# packets should generate an ARP request
#
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.0.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.0.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg2.get_capture(1)
- self.verify_arp_req(rx[0],
- self.pg2.local_mac,
- self.pg2.local_ip4,
- self.pg2._remote_hosts[1].ip4)
+ self.verify_arp_req(
+ rx[0], self.pg2.local_mac, self.pg2.local_ip4, self.pg2._remote_hosts[1].ip4
+ )
#
# now resolve the neighbours
@@ -1070,42 +1167,48 @@ class ARPTestCase(VppTestCase):
self.pg_start()
rx = self.pg2.get_capture(1)
- self.verify_ip_o_mpls(rx[0],
- self.pg2.local_mac,
- self.pg2.remote_hosts[1].mac,
- 55,
- self.pg0.remote_ip4,
- "10.0.0.1")
+ self.verify_ip_o_mpls(
+ rx[0],
+ self.pg2.local_mac,
+ self.pg2.remote_hosts[1].mac,
+ 55,
+ self.pg0.remote_ip4,
+ "10.0.0.1",
+ )
self.pg2.unconfig_ip4()
def test_arp_vrrp(self):
- """ ARP reply with VRRP virtual src hw addr """
+ """ARP reply with VRRP virtual src hw addr"""
#
# IP packet destined for pg1 remote host arrives on pg0 resulting
# in an ARP request for the address of the remote host on pg1
#
- p0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p0 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
rx1 = self.send_and_expect(self.pg0, [p0], self.pg1)
- self.verify_arp_req(rx1[0],
- self.pg1.local_mac,
- self.pg1.local_ip4,
- self.pg1.remote_ip4)
+ self.verify_arp_req(
+ rx1[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1.remote_ip4
+ )
#
# ARP reply for address of pg1 remote host arrives on pg1 with
# the hw src addr set to a value in the VRRP IPv4 range of
# MAC addresses
#
- p1 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- ARP(op="is-at", hwdst=self.pg1.local_mac,
- hwsrc="00:00:5e:00:01:09", pdst=self.pg1.local_ip4,
- psrc=self.pg1.remote_ip4))
+ p1 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / ARP(
+ op="is-at",
+ hwdst=self.pg1.local_mac,
+ hwsrc="00:00:5e:00:01:09",
+ pdst=self.pg1.local_ip4,
+ psrc=self.pg1.remote_ip4,
+ )
self.send_and_assert_no_replies(self.pg1, p1, "ARP reply")
@@ -1116,17 +1219,19 @@ class ARPTestCase(VppTestCase):
#
rx1 = self.send_and_expect(self.pg0, [p0], self.pg1)
- self.verify_ip(rx1[0],
- self.pg1.local_mac,
- "00:00:5e:00:01:09",
- self.pg0.remote_ip4,
- self.pg1.remote_ip4)
+ self.verify_ip(
+ rx1[0],
+ self.pg1.local_mac,
+ "00:00:5e:00:01:09",
+ self.pg0.remote_ip4,
+ self.pg1.remote_ip4,
+ )
self.pg1.admin_down()
self.pg1.admin_up()
def test_arp_duplicates(self):
- """ ARP Duplicates"""
+ """ARP Duplicates"""
#
# Generate some hosts on the LAN
@@ -1136,26 +1241,30 @@ class ARPTestCase(VppTestCase):
#
# Add host 1 on pg1 and pg2
#
- arp_pg1 = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[1].mac,
- self.pg1.remote_hosts[1].ip4)
+ arp_pg1 = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[1].mac,
+ self.pg1.remote_hosts[1].ip4,
+ )
arp_pg1.add_vpp_config()
- arp_pg2 = VppNeighbor(self,
- self.pg2.sw_if_index,
- self.pg2.remote_mac,
- self.pg1.remote_hosts[1].ip4)
+ arp_pg2 = VppNeighbor(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_mac,
+ self.pg1.remote_hosts[1].ip4,
+ )
arp_pg2.add_vpp_config()
#
# IP packet destined for pg1 remote host arrives on pg1 again.
#
- p = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_hosts[1].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[1].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
self.pg0.add_stream(p)
self.pg_enable_capture(self.pg_interfaces)
@@ -1163,11 +1272,13 @@ class ARPTestCase(VppTestCase):
rx1 = self.pg1.get_capture(1)
- self.verify_ip(rx1[0],
- self.pg1.local_mac,
- self.pg1.remote_hosts[1].mac,
- self.pg0.remote_ip4,
- self.pg1.remote_hosts[1].ip4)
+ self.verify_ip(
+ rx1[0],
+ self.pg1.local_mac,
+ self.pg1.remote_hosts[1].mac,
+ self.pg0.remote_ip4,
+ self.pg1.remote_hosts[1].ip4,
+ )
#
# remove the duplicate on pg1
@@ -1181,10 +1292,9 @@ class ARPTestCase(VppTestCase):
rx1 = self.pg1.get_capture(1)
- self.verify_arp_req(rx1[0],
- self.pg1.local_mac,
- self.pg1.local_ip4,
- self.pg1.remote_hosts[1].ip4)
+ self.verify_arp_req(
+ rx1[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1.remote_hosts[1].ip4
+ )
#
# Add it back
@@ -1197,24 +1307,28 @@ class ARPTestCase(VppTestCase):
rx1 = self.pg1.get_capture(1)
- self.verify_ip(rx1[0],
- self.pg1.local_mac,
- self.pg1.remote_hosts[1].mac,
- self.pg0.remote_ip4,
- self.pg1.remote_hosts[1].ip4)
+ self.verify_ip(
+ rx1[0],
+ self.pg1.local_mac,
+ self.pg1.remote_hosts[1].mac,
+ self.pg0.remote_ip4,
+ self.pg1.remote_hosts[1].ip4,
+ )
def test_arp_static(self):
- """ ARP Static"""
+ """ARP Static"""
self.pg2.generate_remote_hosts(3)
#
# Add a static ARP entry
#
- static_arp = VppNeighbor(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[1].mac,
- self.pg2.remote_hosts[1].ip4,
- is_static=1)
+ static_arp = VppNeighbor(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_hosts[1].mac,
+ self.pg2.remote_hosts[1].ip4,
+ is_static=1,
+ )
static_arp.add_vpp_config()
#
@@ -1225,13 +1339,12 @@ class ARPTestCase(VppTestCase):
#
# We should now find the adj-fib
#
- self.assertTrue(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[1].ip4,
- is_static=1))
- self.assertTrue(find_route(self,
- self.pg2.remote_hosts[1].ip4,
- 32))
+ self.assertTrue(
+ find_nbr(
+ self, self.pg2.sw_if_index, self.pg2.remote_hosts[1].ip4, is_static=1
+ )
+ )
+ self.assertTrue(find_route(self, self.pg2.remote_hosts[1].ip4, 32))
#
# remove the connected
@@ -1248,10 +1361,7 @@ class ARPTestCase(VppTestCase):
# adj fib in the new table
#
self.pg2.config_ip4()
- self.assertTrue(find_route(self,
- self.pg2.remote_hosts[1].ip4,
- 32,
- table_id=1))
+ self.assertTrue(find_route(self, self.pg2.remote_hosts[1].ip4, 32, table_id=1))
#
# clean-up
@@ -1261,18 +1371,22 @@ class ARPTestCase(VppTestCase):
self.pg2.set_table_ip4(0)
def test_arp_static_replace_dynamic_same_mac(self):
- """ ARP Static can replace Dynamic (same mac) """
+ """ARP Static can replace Dynamic (same mac)"""
self.pg2.generate_remote_hosts(1)
- dyn_arp = VppNeighbor(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[0].mac,
- self.pg2.remote_hosts[0].ip4)
- static_arp = VppNeighbor(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[0].mac,
- self.pg2.remote_hosts[0].ip4,
- is_static=1)
+ dyn_arp = VppNeighbor(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_hosts[0].mac,
+ self.pg2.remote_hosts[0].ip4,
+ )
+ static_arp = VppNeighbor(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_hosts[0].mac,
+ self.pg2.remote_hosts[0].ip4,
+ is_static=1,
+ )
#
# Add a dynamic ARP entry
@@ -1282,15 +1396,20 @@ class ARPTestCase(VppTestCase):
#
# We should find the dynamic nbr
#
- self.assertFalse(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[0].ip4,
- is_static=1))
- self.assertTrue(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[0].ip4,
- is_static=0,
- mac=self.pg2.remote_hosts[0].mac))
+ self.assertFalse(
+ find_nbr(
+ self, self.pg2.sw_if_index, self.pg2.remote_hosts[0].ip4, is_static=1
+ )
+ )
+ self.assertTrue(
+ find_nbr(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_hosts[0].ip4,
+ is_static=0,
+ mac=self.pg2.remote_hosts[0].mac,
+ )
+ )
#
# Add a static ARP entry with the same mac
@@ -1300,15 +1419,20 @@ class ARPTestCase(VppTestCase):
#
# We should now find the static nbr with the same mac
#
- self.assertFalse(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[0].ip4,
- is_static=0))
- self.assertTrue(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[0].ip4,
- is_static=1,
- mac=self.pg2.remote_hosts[0].mac))
+ self.assertFalse(
+ find_nbr(
+ self, self.pg2.sw_if_index, self.pg2.remote_hosts[0].ip4, is_static=0
+ )
+ )
+ self.assertTrue(
+ find_nbr(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_hosts[0].ip4,
+ is_static=1,
+ mac=self.pg2.remote_hosts[0].mac,
+ )
+ )
#
# clean-up
@@ -1316,18 +1440,22 @@ class ARPTestCase(VppTestCase):
static_arp.remove_vpp_config()
def test_arp_static_replace_dynamic_diff_mac(self):
- """ ARP Static can replace Dynamic (diff mac) """
+ """ARP Static can replace Dynamic (diff mac)"""
self.pg2.generate_remote_hosts(2)
- dyn_arp = VppNeighbor(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[0].mac,
- self.pg2.remote_hosts[0].ip4)
- static_arp = VppNeighbor(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[1].mac,
- self.pg2.remote_hosts[0].ip4,
- is_static=1)
+ dyn_arp = VppNeighbor(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_hosts[0].mac,
+ self.pg2.remote_hosts[0].ip4,
+ )
+ static_arp = VppNeighbor(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_hosts[1].mac,
+ self.pg2.remote_hosts[0].ip4,
+ is_static=1,
+ )
#
# Add a dynamic ARP entry
@@ -1337,15 +1465,20 @@ class ARPTestCase(VppTestCase):
#
# We should find the dynamic nbr
#
- self.assertFalse(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[0].ip4,
- is_static=1))
- self.assertTrue(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[0].ip4,
- is_static=0,
- mac=self.pg2.remote_hosts[0].mac))
+ self.assertFalse(
+ find_nbr(
+ self, self.pg2.sw_if_index, self.pg2.remote_hosts[0].ip4, is_static=1
+ )
+ )
+ self.assertTrue(
+ find_nbr(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_hosts[0].ip4,
+ is_static=0,
+ mac=self.pg2.remote_hosts[0].mac,
+ )
+ )
#
# Add a static ARP entry with a changed mac
@@ -1355,15 +1488,20 @@ class ARPTestCase(VppTestCase):
#
# We should now find the static nbr with a changed mac
#
- self.assertFalse(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[0].ip4,
- is_static=0))
- self.assertTrue(find_nbr(self,
- self.pg2.sw_if_index,
- self.pg2.remote_hosts[0].ip4,
- is_static=1,
- mac=self.pg2.remote_hosts[1].mac))
+ self.assertFalse(
+ find_nbr(
+ self, self.pg2.sw_if_index, self.pg2.remote_hosts[0].ip4, is_static=0
+ )
+ )
+ self.assertTrue(
+ find_nbr(
+ self,
+ self.pg2.sw_if_index,
+ self.pg2.remote_hosts[0].ip4,
+ is_static=1,
+ mac=self.pg2.remote_hosts[1].mac,
+ )
+ )
#
# clean-up
@@ -1371,95 +1509,109 @@ class ARPTestCase(VppTestCase):
static_arp.remove_vpp_config()
def test_arp_incomplete(self):
- """ ARP Incomplete"""
+ """ARP Incomplete"""
self.pg1.generate_remote_hosts(4)
- p0 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_hosts[1].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
- p1 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_hosts[2].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
- p2 = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst="1.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p0 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[1].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
+ p1 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[2].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
+ p2 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="1.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
#
# a packet to an unresolved destination generates an ARP request
#
rx = self.send_and_expect(self.pg0, [p0], self.pg1)
- self.verify_arp_req(rx[0],
- self.pg1.local_mac,
- self.pg1.local_ip4,
- self.pg1._remote_hosts[1].ip4)
+ self.verify_arp_req(
+ rx[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1._remote_hosts[1].ip4
+ )
#
# add a neighbour for remote host 1
#
- static_arp = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[1].mac,
- self.pg1.remote_hosts[1].ip4,
- is_static=1)
+ static_arp = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[1].mac,
+ self.pg1.remote_hosts[1].ip4,
+ is_static=1,
+ )
static_arp.add_vpp_config()
#
# add a route through remote host 3 hence we get an incomplete
#
- VppIpRoute(self, "1.1.1.1", 32,
- [VppRoutePath(self.pg1.remote_hosts[3].ip4,
- self.pg1.sw_if_index)]).add_vpp_config()
+ VppIpRoute(
+ self,
+ "1.1.1.1",
+ 32,
+ [VppRoutePath(self.pg1.remote_hosts[3].ip4, self.pg1.sw_if_index)],
+ ).add_vpp_config()
rx = self.send_and_expect(self.pg0, [p2], self.pg1)
- self.verify_arp_req(rx[0],
- self.pg1.local_mac,
- self.pg1.local_ip4,
- self.pg1._remote_hosts[3].ip4)
+ self.verify_arp_req(
+ rx[0], self.pg1.local_mac, self.pg1.local_ip4, self.pg1._remote_hosts[3].ip4
+ )
#
# change the interface's MAC
#
- self.vapi.sw_interface_set_mac_address(self.pg1.sw_if_index,
- "00:00:00:33:33:33")
+ self.vapi.sw_interface_set_mac_address(
+ self.pg1.sw_if_index, "00:00:00:33:33:33"
+ )
#
# now ARP requests come from the new source mac
#
rx = self.send_and_expect(self.pg0, [p1], self.pg1)
- self.verify_arp_req(rx[0],
- "00:00:00:33:33:33",
- self.pg1.local_ip4,
- self.pg1._remote_hosts[2].ip4)
+ self.verify_arp_req(
+ rx[0],
+ "00:00:00:33:33:33",
+ self.pg1.local_ip4,
+ self.pg1._remote_hosts[2].ip4,
+ )
rx = self.send_and_expect(self.pg0, [p2], self.pg1)
- self.verify_arp_req(rx[0],
- "00:00:00:33:33:33",
- self.pg1.local_ip4,
- self.pg1._remote_hosts[3].ip4)
+ self.verify_arp_req(
+ rx[0],
+ "00:00:00:33:33:33",
+ self.pg1.local_ip4,
+ self.pg1._remote_hosts[3].ip4,
+ )
#
# packets to the resolved host also have the new source mac
#
rx = self.send_and_expect(self.pg0, [p0], self.pg1)
- self.verify_ip(rx[0],
- "00:00:00:33:33:33",
- self.pg1.remote_hosts[1].mac,
- self.pg0.remote_ip4,
- self.pg1.remote_hosts[1].ip4)
+ self.verify_ip(
+ rx[0],
+ "00:00:00:33:33:33",
+ self.pg1.remote_hosts[1].mac,
+ self.pg0.remote_ip4,
+ self.pg1.remote_hosts[1].ip4,
+ )
#
# set the mac address on the interface that does not have a
# configured subnet and thus no glean
#
- self.vapi.sw_interface_set_mac_address(self.pg2.sw_if_index,
- "00:00:00:33:33:33")
+ self.vapi.sw_interface_set_mac_address(
+ self.pg2.sw_if_index, "00:00:00:33:33:33"
+ )
def test_garp(self):
- """ GARP """
+ """GARP"""
#
# Generate some hosts on the LAN
@@ -1470,92 +1622,106 @@ class ARPTestCase(VppTestCase):
#
# And an ARP entry
#
- arp = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[1].mac,
- self.pg1.remote_hosts[1].ip4)
+ arp = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[1].mac,
+ self.pg1.remote_hosts[1].ip4,
+ )
arp.add_vpp_config()
- self.assertTrue(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[1].ip4,
- mac=self.pg1.remote_hosts[1].mac))
+ self.assertTrue(
+ find_nbr(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[1].ip4,
+ mac=self.pg1.remote_hosts[1].mac,
+ )
+ )
#
# Send a GARP (request) to swap the host 1's address to that of host 2
#
- p1 = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg1.remote_hosts[2].mac) /
- ARP(op="who-has",
- hwdst=self.pg1.local_mac,
- hwsrc=self.pg1.remote_hosts[2].mac,
- pdst=self.pg1.remote_hosts[1].ip4,
- psrc=self.pg1.remote_hosts[1].ip4))
+ p1 = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_hosts[2].mac) / ARP(
+ op="who-has",
+ hwdst=self.pg1.local_mac,
+ hwsrc=self.pg1.remote_hosts[2].mac,
+ pdst=self.pg1.remote_hosts[1].ip4,
+ psrc=self.pg1.remote_hosts[1].ip4,
+ )
self.pg1.add_stream(p1)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.assertTrue(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[1].ip4,
- mac=self.pg1.remote_hosts[2].mac))
+ self.assertTrue(
+ find_nbr(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[1].ip4,
+ mac=self.pg1.remote_hosts[2].mac,
+ )
+ )
#
# Send a GARP (reply) to swap the host 1's address to that of host 3
#
- p1 = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg1.remote_hosts[3].mac) /
- ARP(op="is-at",
- hwdst=self.pg1.local_mac,
- hwsrc=self.pg1.remote_hosts[3].mac,
- pdst=self.pg1.remote_hosts[1].ip4,
- psrc=self.pg1.remote_hosts[1].ip4))
+ p1 = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_hosts[3].mac) / ARP(
+ op="is-at",
+ hwdst=self.pg1.local_mac,
+ hwsrc=self.pg1.remote_hosts[3].mac,
+ pdst=self.pg1.remote_hosts[1].ip4,
+ psrc=self.pg1.remote_hosts[1].ip4,
+ )
self.pg1.add_stream(p1)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.assertTrue(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[1].ip4,
- mac=self.pg1.remote_hosts[3].mac))
+ self.assertTrue(
+ find_nbr(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[1].ip4,
+ mac=self.pg1.remote_hosts[3].mac,
+ )
+ )
#
# GARPs (request nor replies) for host we don't know yet
# don't result in new neighbour entries
#
- p1 = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg1.remote_hosts[3].mac) /
- ARP(op="who-has",
- hwdst=self.pg1.local_mac,
- hwsrc=self.pg1.remote_hosts[3].mac,
- pdst=self.pg1.remote_hosts[2].ip4,
- psrc=self.pg1.remote_hosts[2].ip4))
+ p1 = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_hosts[3].mac) / ARP(
+ op="who-has",
+ hwdst=self.pg1.local_mac,
+ hwsrc=self.pg1.remote_hosts[3].mac,
+ pdst=self.pg1.remote_hosts[2].ip4,
+ psrc=self.pg1.remote_hosts[2].ip4,
+ )
self.pg1.add_stream(p1)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.assertFalse(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[2].ip4))
+ self.assertFalse(
+ find_nbr(self, self.pg1.sw_if_index, self.pg1.remote_hosts[2].ip4)
+ )
- p1 = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg1.remote_hosts[3].mac) /
- ARP(op="is-at",
- hwdst=self.pg1.local_mac,
- hwsrc=self.pg1.remote_hosts[3].mac,
- pdst=self.pg1.remote_hosts[2].ip4,
- psrc=self.pg1.remote_hosts[2].ip4))
+ p1 = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg1.remote_hosts[3].mac) / ARP(
+ op="is-at",
+ hwdst=self.pg1.local_mac,
+ hwsrc=self.pg1.remote_hosts[3].mac,
+ pdst=self.pg1.remote_hosts[2].ip4,
+ psrc=self.pg1.remote_hosts[2].ip4,
+ )
self.pg1.add_stream(p1)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- self.assertFalse(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[2].ip4))
+ self.assertFalse(
+ find_nbr(self, self.pg1.sw_if_index, self.pg1.remote_hosts[2].ip4)
+ )
#
# IP address in different subnets are not learnt
@@ -1563,32 +1729,44 @@ class ARPTestCase(VppTestCase):
self.pg2.configure_ipv4_neighbors()
for op in ["is-at", "who-has"]:
- p1 = [(Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg2.remote_hosts[1].mac) /
- ARP(op=op,
- hwdst=self.pg2.local_mac,
- hwsrc=self.pg2.remote_hosts[1].mac,
- pdst=self.pg2.remote_hosts[1].ip4,
- psrc=self.pg2.remote_hosts[1].ip4)),
- (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg2.remote_hosts[1].mac) /
- ARP(op=op,
- hwdst="ff:ff:ff:ff:ff:ff",
- hwsrc=self.pg2.remote_hosts[1].mac,
- pdst=self.pg2.remote_hosts[1].ip4,
- psrc=self.pg2.remote_hosts[1].ip4))]
+ p1 = [
+ (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_hosts[1].mac)
+ / ARP(
+ op=op,
+ hwdst=self.pg2.local_mac,
+ hwsrc=self.pg2.remote_hosts[1].mac,
+ pdst=self.pg2.remote_hosts[1].ip4,
+ psrc=self.pg2.remote_hosts[1].ip4,
+ )
+ ),
+ (
+ Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg2.remote_hosts[1].mac)
+ / ARP(
+ op=op,
+ hwdst="ff:ff:ff:ff:ff:ff",
+ hwsrc=self.pg2.remote_hosts[1].mac,
+ pdst=self.pg2.remote_hosts[1].ip4,
+ psrc=self.pg2.remote_hosts[1].ip4,
+ )
+ ),
+ ]
self.send_and_assert_no_replies(self.pg1, p1)
- self.assertFalse(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg2.remote_hosts[1].ip4))
+ self.assertFalse(
+ find_nbr(self, self.pg1.sw_if_index, self.pg2.remote_hosts[1].ip4)
+ )
# they are all dropped because the subnet's don't match
- self.assertEqual(4, self.statistics.get_err_counter(
- "/err/arp-reply/IP4 destination address not local to subnet"))
+ self.assertEqual(
+ 4,
+ self.statistics.get_err_counter(
+ "/err/arp-reply/IP4 destination address not local to subnet"
+ ),
+ )
def test_arp_incomplete2(self):
- """ Incomplete Entries """
+ """Incomplete Entries"""
#
# ensure that we throttle the ARP and ND requests
@@ -1598,17 +1776,20 @@ class ARPTestCase(VppTestCase):
#
# IPv4/ARP
#
- ip_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- [VppRoutePath(self.pg0.remote_hosts[1].ip4,
- self.pg0.sw_if_index)])
+ ip_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ [VppRoutePath(self.pg0.remote_hosts[1].ip4, self.pg0.sw_if_index)],
+ )
ip_10_0_0_1.add_vpp_config()
- p1 = (Ether(dst=self.pg1.local_mac,
- src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4,
- dst="10.0.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p1 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst="10.0.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
self.pg1.add_stream(p1 * 257)
self.pg_enable_capture(self.pg_interfaces)
@@ -1624,18 +1805,26 @@ class ARPTestCase(VppTestCase):
#
# IPv6/ND
#
- ip_10_1 = VppIpRoute(self, "10::1", 128,
- [VppRoutePath(self.pg0.remote_hosts[1].ip6,
- self.pg0.sw_if_index,
- proto=DpoProto.DPO_PROTO_IP6)])
+ ip_10_1 = VppIpRoute(
+ self,
+ "10::1",
+ 128,
+ [
+ VppRoutePath(
+ self.pg0.remote_hosts[1].ip6,
+ self.pg0.sw_if_index,
+ proto=DpoProto.DPO_PROTO_IP6,
+ )
+ ],
+ )
ip_10_1.add_vpp_config()
- p1 = (Ether(dst=self.pg1.local_mac,
- src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_ip6,
- dst="10::1") /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p1 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst="10::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
self.pg1.add_stream(p1 * 257)
self.pg_enable_capture(self.pg_interfaces)
@@ -1649,7 +1838,7 @@ class ARPTestCase(VppTestCase):
self.assertLess(len(rx), 64)
def test_arp_forus(self):
- """ ARP for for-us """
+ """ARP for for-us"""
#
# Test that VPP responds with ARP requests to addresses that
@@ -1661,27 +1850,36 @@ class ARPTestCase(VppTestCase):
self.pg0.generate_remote_hosts(2)
forus = VppIpRoute(
- self, self.pg0.remote_hosts[1].ip4, 32,
- [VppRoutePath("0.0.0.0",
- self.pg0.sw_if_index,
- type=FibPathType.FIB_PATH_TYPE_LOCAL)])
+ self,
+ self.pg0.remote_hosts[1].ip4,
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ self.pg0.sw_if_index,
+ type=FibPathType.FIB_PATH_TYPE_LOCAL,
+ )
+ ],
+ )
forus.add_vpp_config()
- p = (Ether(dst="ff:ff:ff:ff:ff:ff",
- src=self.pg0.remote_mac) /
- ARP(op="who-has",
- hwdst=self.pg0.local_mac,
- hwsrc=self.pg0.remote_mac,
- pdst=self.pg0.remote_hosts[1].ip4,
- psrc=self.pg0.remote_ip4))
+ p = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op="who-has",
+ hwdst=self.pg0.local_mac,
+ hwsrc=self.pg0.remote_mac,
+ pdst=self.pg0.remote_hosts[1].ip4,
+ psrc=self.pg0.remote_ip4,
+ )
rx = self.send_and_expect(self.pg0, [p], self.pg0)
- self.verify_arp_resp(rx[0],
- self.pg0.local_mac,
- self.pg0.remote_mac,
- self.pg0.remote_hosts[1].ip4,
- self.pg0.remote_ip4)
+ self.verify_arp_resp(
+ rx[0],
+ self.pg0.local_mac,
+ self.pg0.remote_mac,
+ self.pg0.remote_hosts[1].ip4,
+ self.pg0.remote_ip4,
+ )
def test_arp_table_swap(self):
#
@@ -1692,15 +1890,21 @@ class ARPTestCase(VppTestCase):
for n in range(N_NBRS):
# a route thru each neighbour
- VppIpRoute(self, "10.0.0.%d" % n, 32,
- [VppRoutePath(self.pg1.remote_hosts[n].ip4,
- self.pg1.sw_if_index)]).add_vpp_config()
+ VppIpRoute(
+ self,
+ "10.0.0.%d" % n,
+ 32,
+ [VppRoutePath(self.pg1.remote_hosts[n].ip4, self.pg1.sw_if_index)],
+ ).add_vpp_config()
# resolve each neighbour
- p1 = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- ARP(op="is-at", hwdst=self.pg1.local_mac,
- hwsrc="00:00:5e:00:01:09", pdst=self.pg1.local_ip4,
- psrc=self.pg1.remote_hosts[n].ip4))
+ p1 = Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) / ARP(
+ op="is-at",
+ hwdst=self.pg1.local_mac,
+ hwsrc="00:00:5e:00:01:09",
+ pdst=self.pg1.local_ip4,
+ psrc=self.pg1.remote_hosts[n].ip4,
+ )
self.send_and_assert_no_replies(self.pg1, p1, "ARP reply")
@@ -1719,87 +1923,80 @@ class ARPTestCase(VppTestCase):
# all neighbours are cleared
#
for n in range(N_NBRS):
- self.assertFalse(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[n].ip4))
+ self.assertFalse(
+ find_nbr(self, self.pg1.sw_if_index, self.pg1.remote_hosts[n].ip4)
+ )
#
# packets to all neighbours generate ARP requests
#
for n in range(N_NBRS):
# a route thru each neighbour
- VppIpRoute(self, "10.0.0.%d" % n, 32,
- [VppRoutePath(self.pg1.remote_hosts[n].ip4,
- self.pg1.sw_if_index)],
- table_id=100).add_vpp_config()
-
- p = (Ether(src=self.pg1.remote_hosts[n].mac,
- dst=self.pg1.local_mac) /
- IP(src=self.pg1.remote_hosts[n].ip4,
- dst="10.0.0.%d" % n) /
- Raw(b'0x5' * 100))
+ VppIpRoute(
+ self,
+ "10.0.0.%d" % n,
+ 32,
+ [VppRoutePath(self.pg1.remote_hosts[n].ip4, self.pg1.sw_if_index)],
+ table_id=100,
+ ).add_vpp_config()
+
+ p = (
+ Ether(src=self.pg1.remote_hosts[n].mac, dst=self.pg1.local_mac)
+ / IP(src=self.pg1.remote_hosts[n].ip4, dst="10.0.0.%d" % n)
+ / Raw(b"0x5" * 100)
+ )
rxs = self.send_and_expect(self.pg1, [p], self.pg1)
for rx in rxs:
- self.verify_arp_req(rx,
- self.pg1.local_mac,
- self.pg1.local_ip4,
- self.pg1.remote_hosts[n].ip4)
+ self.verify_arp_req(
+ rx,
+ self.pg1.local_mac,
+ self.pg1.local_ip4,
+ self.pg1.remote_hosts[n].ip4,
+ )
self.pg1.unconfig_ip4()
self.pg1.set_table_ip4(0)
def test_glean_src_select(self):
- """ Multi Connecteds """
+ """Multi Connecteds"""
#
# configure multiple connected subnets on an interface
# and ensure that ARP requests for hosts on those subnets
# pick up the correct source address
#
- conn1 = VppIpInterfaceAddress(self, self.pg1,
- "10.0.0.1", 24).add_vpp_config()
- conn2 = VppIpInterfaceAddress(self, self.pg1,
- "10.0.1.1", 24).add_vpp_config()
+ conn1 = VppIpInterfaceAddress(self, self.pg1, "10.0.0.1", 24).add_vpp_config()
+ conn2 = VppIpInterfaceAddress(self, self.pg1, "10.0.1.1", 24).add_vpp_config()
- p1 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg1.remote_ip4,
- dst="10.0.0.128") /
- Raw(b'0x5' * 100))
+ p1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst="10.0.0.128")
+ / Raw(b"0x5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, [p1], self.pg1)
for rx in rxs:
- self.verify_arp_req(rx,
- self.pg1.local_mac,
- "10.0.0.1",
- "10.0.0.128")
+ self.verify_arp_req(rx, self.pg1.local_mac, "10.0.0.1", "10.0.0.128")
- p2 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg1.remote_ip4,
- dst="10.0.1.128") /
- Raw(b'0x5' * 100))
+ p2 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst="10.0.1.128")
+ / Raw(b"0x5" * 100)
+ )
rxs = self.send_and_expect(self.pg0, [p2], self.pg1)
for rx in rxs:
- self.verify_arp_req(rx,
- self.pg1.local_mac,
- "10.0.1.1",
- "10.0.1.128")
+ self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.1", "10.0.1.128")
#
# add a local address in the same subnet
# the source addresses are equivalent. VPP happens to
# choose the last one that was added
- conn3 = VppIpInterfaceAddress(self, self.pg1,
- "10.0.1.2", 24).add_vpp_config()
+ conn3 = VppIpInterfaceAddress(self, self.pg1, "10.0.1.2", 24).add_vpp_config()
rxs = self.send_and_expect(self.pg0, [p2], self.pg1)
for rx in rxs:
- self.verify_arp_req(rx,
- self.pg1.local_mac,
- "10.0.1.2",
- "10.0.1.128")
+ self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.2", "10.0.1.128")
#
# remove
@@ -1807,44 +2004,34 @@ class ARPTestCase(VppTestCase):
conn3.remove_vpp_config()
rxs = self.send_and_expect(self.pg0, [p2], self.pg1)
for rx in rxs:
- self.verify_arp_req(rx,
- self.pg1.local_mac,
- "10.0.1.1",
- "10.0.1.128")
+ self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.1", "10.0.1.128")
#
# add back, this time remove the first one
#
- conn3 = VppIpInterfaceAddress(self, self.pg1,
- "10.0.1.2", 24).add_vpp_config()
+ conn3 = VppIpInterfaceAddress(self, self.pg1, "10.0.1.2", 24).add_vpp_config()
rxs = self.send_and_expect(self.pg0, [p2], self.pg1)
for rx in rxs:
- self.verify_arp_req(rx,
- self.pg1.local_mac,
- "10.0.1.2",
- "10.0.1.128")
+ self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.2", "10.0.1.128")
conn1.remove_vpp_config()
rxs = self.send_and_expect(self.pg0, [p2], self.pg1)
for rx in rxs:
- self.verify_arp_req(rx,
- self.pg1.local_mac,
- "10.0.1.2",
- "10.0.1.128")
+ self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.2", "10.0.1.128")
# apply a connected prefix to an interface in a different table
- VppIpRoute(self, "10.0.1.0", 24,
- [VppRoutePath("0.0.0.0",
- self.pg1.sw_if_index)],
- table_id=1).add_vpp_config()
+ VppIpRoute(
+ self,
+ "10.0.1.0",
+ 24,
+ [VppRoutePath("0.0.0.0", self.pg1.sw_if_index)],
+ table_id=1,
+ ).add_vpp_config()
rxs = self.send_and_expect(self.pg3, [p2], self.pg1)
for rx in rxs:
- self.verify_arp_req(rx,
- self.pg1.local_mac,
- "10.0.1.2",
- "10.0.1.128")
+ self.verify_arp_req(rx, self.pg1.local_mac, "10.0.1.2", "10.0.1.128")
# cleanup
conn3.remove_vpp_config()
@@ -1853,7 +2040,7 @@ class ARPTestCase(VppTestCase):
@tag_fixme_vpp_workers
class NeighborStatsTestCase(VppTestCase):
- """ ARP/ND Counters """
+ """ARP/ND Counters"""
@classmethod
def setUpClass(cls):
@@ -1887,86 +2074,94 @@ class NeighborStatsTestCase(VppTestCase):
i.admin_down()
def test_arp_stats(self):
- """ ARP Counters """
+ """ARP Counters"""
self.vapi.cli("adj counters enable")
self.pg1.generate_remote_hosts(2)
- arp1 = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[0].mac,
- self.pg1.remote_hosts[0].ip4)
+ arp1 = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[0].mac,
+ self.pg1.remote_hosts[0].ip4,
+ )
arp1.add_vpp_config()
- arp2 = VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[1].mac,
- self.pg1.remote_hosts[1].ip4)
+ arp2 = VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[1].mac,
+ self.pg1.remote_hosts[1].ip4,
+ )
arp2.add_vpp_config()
- p1 = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_hosts[0].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
- p2 = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_hosts[1].ip4) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p1 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[0].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
+ p2 = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_hosts[1].ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
rx = self.send_and_expect(self.pg0, p1 * NUM_PKTS, self.pg1)
rx = self.send_and_expect(self.pg0, p2 * NUM_PKTS, self.pg1)
- self.assertEqual(NUM_PKTS, arp1.get_stats()['packets'])
- self.assertEqual(NUM_PKTS, arp2.get_stats()['packets'])
+ self.assertEqual(NUM_PKTS, arp1.get_stats()["packets"])
+ self.assertEqual(NUM_PKTS, arp2.get_stats()["packets"])
rx = self.send_and_expect(self.pg0, p1 * NUM_PKTS, self.pg1)
- self.assertEqual(NUM_PKTS*2, arp1.get_stats()['packets'])
+ self.assertEqual(NUM_PKTS * 2, arp1.get_stats()["packets"])
def test_nd_stats(self):
- """ ND Counters """
+ """ND Counters"""
self.vapi.cli("adj counters enable")
self.pg0.generate_remote_hosts(3)
- nd1 = VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[1].mac,
- self.pg0.remote_hosts[1].ip6)
+ nd1 = VppNeighbor(
+ self,
+ self.pg0.sw_if_index,
+ self.pg0.remote_hosts[1].mac,
+ self.pg0.remote_hosts[1].ip6,
+ )
nd1.add_vpp_config()
- nd2 = VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[2].mac,
- self.pg0.remote_hosts[2].ip6)
+ nd2 = VppNeighbor(
+ self,
+ self.pg0.sw_if_index,
+ self.pg0.remote_hosts[2].mac,
+ self.pg0.remote_hosts[2].ip6,
+ )
nd2.add_vpp_config()
- p1 = (Ether(dst=self.pg1.local_mac,
- src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_ip6,
- dst=self.pg0.remote_hosts[1].ip6) /
- UDP(sport=1234, dport=1234) /
- Raw())
- p2 = (Ether(dst=self.pg1.local_mac,
- src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_ip6,
- dst=self.pg0.remote_hosts[2].ip6) /
- UDP(sport=1234, dport=1234) /
- Raw())
+ p1 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.remote_hosts[1].ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
+ p2 = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg0.remote_hosts[2].ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw()
+ )
rx = self.send_and_expect(self.pg1, p1 * 16, self.pg0)
rx = self.send_and_expect(self.pg1, p2 * 16, self.pg0)
- self.assertEqual(16, nd1.get_stats()['packets'])
- self.assertEqual(16, nd2.get_stats()['packets'])
+ self.assertEqual(16, nd1.get_stats()["packets"])
+ self.assertEqual(16, nd2.get_stats()["packets"])
rx = self.send_and_expect(self.pg1, p1 * NUM_PKTS, self.pg0)
- self.assertEqual(NUM_PKTS+16, nd1.get_stats()['packets'])
+ self.assertEqual(NUM_PKTS + 16, nd1.get_stats()["packets"])
class NeighborAgeTestCase(VppTestCase):
- """ ARP/ND Aging """
+ """ARP/ND Aging"""
@classmethod
def setUpClass(cls):
@@ -2016,10 +2211,10 @@ class NeighborAgeTestCase(VppTestCase):
self.assertEqual(arp.pdst, dip)
def test_age(self):
- """ Aging/Recycle """
+ """Aging/Recycle"""
self.vapi.cli("set logging unthrottle 0")
- self.vapi.cli("set logging size %d" % 0xffff)
+ self.vapi.cli("set logging size %d" % 0xFFFF)
self.pg0.generate_remote_hosts(201)
@@ -2036,56 +2231,59 @@ class NeighborAgeTestCase(VppTestCase):
# age = 0 seconds
# recycle = false
#
- self.vapi.ip_neighbor_config(af=vaf.ADDRESS_IP4,
- max_number=200,
- max_age=0,
- recycle=False)
+ self.vapi.ip_neighbor_config(
+ af=vaf.ADDRESS_IP4, max_number=200, max_age=0, recycle=False
+ )
self.vapi.cli("sh ip neighbor-config")
# add the 198 neighbours that should pass (-1 for one created in setup)
for ii in range(200):
- VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[ii].mac,
- self.pg0.remote_hosts[ii].ip4).add_vpp_config()
+ VppNeighbor(
+ self,
+ self.pg0.sw_if_index,
+ self.pg0.remote_hosts[ii].mac,
+ self.pg0.remote_hosts[ii].ip4,
+ ).add_vpp_config()
# one more neighbor over the limit should fail
with self.vapi.assert_negative_api_retval():
- VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[200].mac,
- self.pg0.remote_hosts[200].ip4).add_vpp_config()
+ VppNeighbor(
+ self,
+ self.pg0.sw_if_index,
+ self.pg0.remote_hosts[200].mac,
+ self.pg0.remote_hosts[200].ip4,
+ ).add_vpp_config()
#
# change the config to allow recycling the old neighbors
#
- self.vapi.ip_neighbor_config(af=vaf.ADDRESS_IP4,
- max_number=200,
- max_age=0,
- recycle=True)
+ self.vapi.ip_neighbor_config(
+ af=vaf.ADDRESS_IP4, max_number=200, max_age=0, recycle=True
+ )
# now new additions are allowed
- VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[200].mac,
- self.pg0.remote_hosts[200].ip4).add_vpp_config()
+ VppNeighbor(
+ self,
+ self.pg0.sw_if_index,
+ self.pg0.remote_hosts[200].mac,
+ self.pg0.remote_hosts[200].ip4,
+ ).add_vpp_config()
# add the first neighbor we configured has been re-used
- self.assertFalse(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[0].ip4))
- self.assertTrue(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[200].ip4))
+ self.assertFalse(
+ find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[0].ip4)
+ )
+ self.assertTrue(
+ find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[200].ip4)
+ )
#
# change the config to age old neighbors
#
- self.vapi.ip_neighbor_config(af=vaf.ADDRESS_IP4,
- max_number=200,
- max_age=2,
- recycle=True)
+ self.vapi.ip_neighbor_config(
+ af=vaf.ADDRESS_IP4, max_number=200, max_age=2, recycle=True
+ )
self.vapi.cli("sh ip4 neighbor-sorted")
@@ -2099,7 +2297,7 @@ class NeighborAgeTestCase(VppTestCase):
for ii in range(3):
for jj in range(200):
- rx = rxs[ii*200 + jj]
+ rx = rxs[ii * 200 + jj]
# rx.show()
#
@@ -2108,8 +2306,9 @@ class NeighborAgeTestCase(VppTestCase):
#
self.virtual_sleep(1)
- self.assertFalse(self.vapi.ip_neighbor_dump(sw_if_index=0xffffffff,
- af=vaf.ADDRESS_IP4))
+ self.assertFalse(
+ self.vapi.ip_neighbor_dump(sw_if_index=0xFFFFFFFF, af=vaf.ADDRESS_IP4)
+ )
#
# load up some neighbours again with 2s aging enabled
@@ -2120,28 +2319,27 @@ class NeighborAgeTestCase(VppTestCase):
self.vapi.want_ip_neighbor_events_v2(enable=1)
for ii in range(10):
- VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[ii].mac,
- self.pg0.remote_hosts[ii].ip4).add_vpp_config()
+ VppNeighbor(
+ self,
+ self.pg0.sw_if_index,
+ self.pg0.remote_hosts[ii].mac,
+ self.pg0.remote_hosts[ii].ip4,
+ ).add_vpp_config()
e = self.vapi.wait_for_event(1, "ip_neighbor_event_v2")
- self.assertEqual(e.flags,
- enum.IP_NEIGHBOR_API_EVENT_FLAG_ADDED)
- self.assertEqual(str(e.neighbor.ip_address),
- self.pg0.remote_hosts[ii].ip4)
- self.assertEqual(e.neighbor.mac_address,
- self.pg0.remote_hosts[ii].mac)
+ self.assertEqual(e.flags, enum.IP_NEIGHBOR_API_EVENT_FLAG_ADDED)
+ self.assertEqual(str(e.neighbor.ip_address), self.pg0.remote_hosts[ii].ip4)
+ self.assertEqual(e.neighbor.mac_address, self.pg0.remote_hosts[ii].mac)
self.virtual_sleep(10)
- self.assertFalse(self.vapi.ip_neighbor_dump(sw_if_index=0xffffffff,
- af=vaf.ADDRESS_IP4))
+ self.assertFalse(
+ self.vapi.ip_neighbor_dump(sw_if_index=0xFFFFFFFF, af=vaf.ADDRESS_IP4)
+ )
evs = []
for ii in range(10):
e = self.vapi.wait_for_event(1, "ip_neighbor_event_v2")
- self.assertEqual(e.flags,
- enum.IP_NEIGHBOR_API_EVENT_FLAG_REMOVED)
+ self.assertEqual(e.flags, enum.IP_NEIGHBOR_API_EVENT_FLAG_REMOVED)
evs.append(e)
# check we got the correct mac/ip pairs - done separately
@@ -2153,8 +2351,7 @@ class NeighborAgeTestCase(VppTestCase):
ip = self.pg0.remote_hosts[ii].ip4
for e in evs:
- if (e.neighbor.mac_address == mac and
- str(e.neighbor.ip_address) == ip):
+ if e.neighbor.mac_address == mac and str(e.neighbor.ip_address) == ip:
found = True
break
self.assertTrue(found)
@@ -2162,33 +2359,33 @@ class NeighborAgeTestCase(VppTestCase):
#
# check if we can set age and recycle with empty neighbor list
#
- self.vapi.ip_neighbor_config(af=vaf.ADDRESS_IP4,
- max_number=200,
- max_age=1000,
- recycle=True)
+ self.vapi.ip_neighbor_config(
+ af=vaf.ADDRESS_IP4, max_number=200, max_age=1000, recycle=True
+ )
#
# load up some neighbours again, then disable the aging
# they should still be there in 10 seconds time
#
for ii in range(10):
- VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[ii].mac,
- self.pg0.remote_hosts[ii].ip4).add_vpp_config()
- self.vapi.ip_neighbor_config(af=vaf.ADDRESS_IP4,
- max_number=200,
- max_age=0,
- recycle=False)
+ VppNeighbor(
+ self,
+ self.pg0.sw_if_index,
+ self.pg0.remote_hosts[ii].mac,
+ self.pg0.remote_hosts[ii].ip4,
+ ).add_vpp_config()
+ self.vapi.ip_neighbor_config(
+ af=vaf.ADDRESS_IP4, max_number=200, max_age=0, recycle=False
+ )
self.virtual_sleep(10)
- self.assertTrue(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[0].ip4))
+ self.assertTrue(
+ find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[0].ip4)
+ )
class NeighborReplaceTestCase(VppTestCase):
- """ ARP/ND Replacement """
+ """ARP/ND Replacement"""
@classmethod
def setUpClass(cls):
@@ -2222,7 +2419,7 @@ class NeighborReplaceTestCase(VppTestCase):
i.admin_down()
def test_replace(self):
- """ replace """
+ """replace"""
N_HOSTS = 16
@@ -2237,26 +2434,24 @@ class NeighborReplaceTestCase(VppTestCase):
for i in self.pg_interfaces:
for h in range(N_HOSTS):
- self.assertFalse(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[h].ip4))
- self.assertFalse(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[h].ip6))
+ self.assertFalse(
+ find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[h].ip4)
+ )
+ self.assertFalse(
+ find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[h].ip6)
+ )
#
# and them all back via the API
#
for i in self.pg_interfaces:
for h in range(N_HOSTS):
- VppNeighbor(self,
- i.sw_if_index,
- i.remote_hosts[h].mac,
- i.remote_hosts[h].ip4).add_vpp_config()
- VppNeighbor(self,
- i.sw_if_index,
- i.remote_hosts[h].mac,
- i.remote_hosts[h].ip6).add_vpp_config()
+ VppNeighbor(
+ self, i.sw_if_index, i.remote_hosts[h].mac, i.remote_hosts[h].ip4
+ ).add_vpp_config()
+ VppNeighbor(
+ self, i.sw_if_index, i.remote_hosts[h].mac, i.remote_hosts[h].ip6
+ ).add_vpp_config()
#
# begin the replacement again, this time touch some
@@ -2266,14 +2461,18 @@ class NeighborReplaceTestCase(VppTestCase):
# update from the API all neighbours on pg1
for h in range(N_HOSTS):
- VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[h].mac,
- self.pg1.remote_hosts[h].ip4).add_vpp_config()
- VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[h].mac,
- self.pg1.remote_hosts[h].ip6).add_vpp_config()
+ VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[h].mac,
+ self.pg1.remote_hosts[h].ip4,
+ ).add_vpp_config()
+ VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[h].mac,
+ self.pg1.remote_hosts[h].ip6,
+ ).add_vpp_config()
# update from the data-plane all neighbours on pg3
self.pg3.configure_ipv4_neighbors()
@@ -2287,25 +2486,25 @@ class NeighborReplaceTestCase(VppTestCase):
if i == self.pg1 or i == self.pg3:
# neighbours on pg1 and pg3 are still present
for h in range(N_HOSTS):
- self.assertTrue(find_nbr(self,
- i.sw_if_index,
- i.remote_hosts[h].ip4))
- self.assertTrue(find_nbr(self,
- i.sw_if_index,
- i.remote_hosts[h].ip6))
+ self.assertTrue(
+ find_nbr(self, i.sw_if_index, i.remote_hosts[h].ip4)
+ )
+ self.assertTrue(
+ find_nbr(self, i.sw_if_index, i.remote_hosts[h].ip6)
+ )
else:
# all other neighbours are toast
for h in range(N_HOSTS):
- self.assertFalse(find_nbr(self,
- i.sw_if_index,
- i.remote_hosts[h].ip4))
- self.assertFalse(find_nbr(self,
- i.sw_if_index,
- i.remote_hosts[h].ip6))
+ self.assertFalse(
+ find_nbr(self, i.sw_if_index, i.remote_hosts[h].ip4)
+ )
+ self.assertFalse(
+ find_nbr(self, i.sw_if_index, i.remote_hosts[h].ip6)
+ )
class NeighborFlush(VppTestCase):
- """ Neighbor Flush """
+ """Neighbor Flush"""
@classmethod
def setUpClass(cls):
@@ -2336,7 +2535,7 @@ class NeighborFlush(VppTestCase):
i.admin_down()
def test_flush(self):
- """ Neighbour Flush """
+ """Neighbour Flush"""
e = VppEnum
nf = e.vl_api_ip_neighbor_flags_t
@@ -2349,72 +2548,88 @@ class NeighborFlush(VppTestCase):
for s in static:
# a few v4 and v6 dynamic neoghbors
for n in range(N_HOSTS):
- VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[n].mac,
- self.pg0.remote_hosts[n].ip4,
- is_static=s).add_vpp_config()
- VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[n].mac,
- self.pg1.remote_hosts[n].ip6,
- is_static=s).add_vpp_config()
+ VppNeighbor(
+ self,
+ self.pg0.sw_if_index,
+ self.pg0.remote_hosts[n].mac,
+ self.pg0.remote_hosts[n].ip4,
+ is_static=s,
+ ).add_vpp_config()
+ VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[n].mac,
+ self.pg1.remote_hosts[n].ip6,
+ is_static=s,
+ ).add_vpp_config()
# flush the interfaces individually
self.vapi.ip_neighbor_flush(af.ADDRESS_IP4, self.pg0.sw_if_index)
# check we haven't flushed that which we shouldn't
for n in range(N_HOSTS):
- self.assertTrue(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[n].ip6,
- is_static=s))
+ self.assertTrue(
+ find_nbr(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[n].ip6,
+ is_static=s,
+ )
+ )
self.vapi.ip_neighbor_flush(af.ADDRESS_IP6, self.pg1.sw_if_index)
for n in range(N_HOSTS):
- self.assertFalse(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[n].ip4))
- self.assertFalse(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[n].ip6))
+ self.assertFalse(
+ find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[n].ip4)
+ )
+ self.assertFalse(
+ find_nbr(self, self.pg1.sw_if_index, self.pg1.remote_hosts[n].ip6)
+ )
# add the nieghbours back
for n in range(N_HOSTS):
- VppNeighbor(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[n].mac,
- self.pg0.remote_hosts[n].ip4,
- is_static=s).add_vpp_config()
- VppNeighbor(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[n].mac,
- self.pg1.remote_hosts[n].ip6,
- is_static=s).add_vpp_config()
+ VppNeighbor(
+ self,
+ self.pg0.sw_if_index,
+ self.pg0.remote_hosts[n].mac,
+ self.pg0.remote_hosts[n].ip4,
+ is_static=s,
+ ).add_vpp_config()
+ VppNeighbor(
+ self,
+ self.pg1.sw_if_index,
+ self.pg1.remote_hosts[n].mac,
+ self.pg1.remote_hosts[n].ip6,
+ is_static=s,
+ ).add_vpp_config()
self.logger.info(self.vapi.cli("sh ip neighbor"))
# flush both interfaces at the same time
- self.vapi.ip_neighbor_flush(af.ADDRESS_IP6, 0xffffffff)
+ self.vapi.ip_neighbor_flush(af.ADDRESS_IP6, 0xFFFFFFFF)
# check we haven't flushed that which we shouldn't
for n in range(N_HOSTS):
- self.assertTrue(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[n].ip4,
- is_static=s))
+ self.assertTrue(
+ find_nbr(
+ self,
+ self.pg0.sw_if_index,
+ self.pg0.remote_hosts[n].ip4,
+ is_static=s,
+ )
+ )
- self.vapi.ip_neighbor_flush(af.ADDRESS_IP4, 0xffffffff)
+ self.vapi.ip_neighbor_flush(af.ADDRESS_IP4, 0xFFFFFFFF)
for n in range(N_HOSTS):
- self.assertFalse(find_nbr(self,
- self.pg0.sw_if_index,
- self.pg0.remote_hosts[n].ip4))
- self.assertFalse(find_nbr(self,
- self.pg1.sw_if_index,
- self.pg1.remote_hosts[n].ip6))
+ self.assertFalse(
+ find_nbr(self, self.pg0.sw_if_index, self.pg0.remote_hosts[n].ip4)
+ )
+ self.assertFalse(
+ find_nbr(self, self.pg1.sw_if_index, self.pg1.remote_hosts[n].ip6)
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_node_variants.py b/test/test_node_variants.py
index 3632910e3cb..a5c9137f9ba 100644
--- a/test/test_node_variants.py
+++ b/test/test_node_variants.py
@@ -13,15 +13,14 @@ def skipVariant(variant):
with open("/proc/cpuinfo") as f:
cpuinfo = f.read()
- exp = re.compile(
- r'(?:flags\s+:)(?:\s\w+)+(?:\s(' + variant + r'))(?:\s\w+)+')
+ exp = re.compile(r"(?:flags\s+:)(?:\s\w+)+(?:\s(" + variant + r"))(?:\s\w+)+")
match = exp.search(cpuinfo, re.DOTALL | re.MULTILINE)
return checkX86() and match is not None
class TestNodeVariant(VppTestCase):
- """ Test Node Variants """
+ """Test Node Variants"""
@classmethod
def setUpConstants(cls, variant):
@@ -30,9 +29,10 @@ class TestNodeVariant(VppTestCase):
if checkX86():
node_variants = cls.vpp_cmdline.index("node { ") + 1
- cls.vpp_cmdline[node_variants] = ("default { variant default } "
- "ip4-rewrite { variant " +
- variant + " } ")
+ cls.vpp_cmdline[node_variants] = (
+ "default { variant default } "
+ "ip4-rewrite { variant " + variant + " } "
+ )
@classmethod
def setUpClass(cls):
@@ -52,13 +52,14 @@ class TestNodeVariant(VppTestCase):
node_desc = self.vapi.cli("show node " + node)
self.logger.info(node_desc)
- match = re.search(r'\s+(\S+)\s+(\d+)\s+(:?yes)',
- node_desc, re.DOTALL | re.MULTILINE)
+ match = re.search(
+ r"\s+(\S+)\s+(\d+)\s+(:?yes)", node_desc, re.DOTALL | re.MULTILINE
+ )
return match.groups(0)
def checkVariant(self, variant):
- """ Test node variants defaults """
+ """Test node variants defaults"""
variant_info = self.getActiveVariant("ip4-lookup")
self.assertEqual(variant_info[0], "default")
@@ -68,7 +69,7 @@ class TestNodeVariant(VppTestCase):
class TestICLVariant(TestNodeVariant):
- """ Test icl Node Variants """
+ """Test icl Node Variants"""
VARIANT = "icl"
LINUX_VARIANT = "avx512_bitalg"
@@ -85,14 +86,15 @@ class TestICLVariant(TestNodeVariant):
def tearDownClass(cls):
super(TestICLVariant, cls).tearDownClass()
- @unittest.skipUnless(skipVariant(LINUX_VARIANT),
- VARIANT + " not a supported variant, skip.")
+ @unittest.skipUnless(
+ skipVariant(LINUX_VARIANT), VARIANT + " not a supported variant, skip."
+ )
def test_icl(self):
self.checkVariant(self.VARIANT)
class TestSKXVariant(TestNodeVariant):
- """ Test skx Node Variants """
+ """Test skx Node Variants"""
VARIANT = "skx"
LINUX_VARIANT = "avx512f"
@@ -109,14 +111,15 @@ class TestSKXVariant(TestNodeVariant):
def tearDownClass(cls):
super(TestSKXVariant, cls).tearDownClass()
- @unittest.skipUnless(skipVariant(LINUX_VARIANT),
- VARIANT + " not a supported variant, skip.")
+ @unittest.skipUnless(
+ skipVariant(LINUX_VARIANT), VARIANT + " not a supported variant, skip."
+ )
def test_skx(self):
self.checkVariant(self.VARIANT)
class TestHSWVariant(TestNodeVariant):
- """ Test avx2 Node Variants """
+ """Test avx2 Node Variants"""
VARIANT = "hsw"
LINUX_VARIANT = "avx2"
@@ -133,7 +136,8 @@ class TestHSWVariant(TestNodeVariant):
def tearDownClass(cls):
super(TestHSWVariant, cls).tearDownClass()
- @unittest.skipUnless(skipVariant(LINUX_VARIANT),
- VARIANT + " not a supported variant, skip.")
+ @unittest.skipUnless(
+ skipVariant(LINUX_VARIANT), VARIANT + " not a supported variant, skip."
+ )
def test_hsw(self):
self.checkVariant(self.VARIANT)
diff --git a/test/test_offload.py b/test/test_offload.py
index ae5a5b3c6dc..d84f8ba63c0 100644
--- a/test/test_offload.py
+++ b/test/test_offload.py
@@ -7,7 +7,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
class TestOffload(VppTestCase):
- """ Offload Unit Test Cases """
+ """Offload Unit Test Cases"""
@classmethod
def setUpClass(cls):
@@ -24,52 +24,55 @@ class TestOffload(VppTestCase):
super(TestOffload, self).tearDown()
def test_offload_unittest(self):
- """ Checksum Offload Test """
- cmds = ["loop create",
- "set int ip address loop0 11.22.33.1/24",
- "set int state loop0 up",
- "loop create",
- "set int ip address loop1 11.22.34.1/24",
- "set int state loop1 up",
- "set ip neighbor loop1 11.22.34.44 03:00:11:22:34:44",
- "packet-generator new {\n"
- " name s0\n"
- " limit 100\n"
- " size 128-128\n"
- " interface loop0\n"
- " tx-interface loop1\n"
- " node loop1-output\n"
- " buffer-flags ip4 offload\n"
- " buffer-offload-flags offload-ip-cksum offload-udp-cksum\n"
- " data {\n"
- " IP4: 1.2.3 -> dead.0000.0001\n"
- " UDP: 11.22.33.44 -> 11.22.34.44\n"
- " ttl 2 checksum 13\n"
- " UDP: 1234 -> 2345\n"
- " checksum 11\n"
- " incrementing 114\n"
- " }\n"
- "}",
- "trace add pg-input 1",
- "pa en",
- "show error"]
+ """Checksum Offload Test"""
+ cmds = [
+ "loop create",
+ "set int ip address loop0 11.22.33.1/24",
+ "set int state loop0 up",
+ "loop create",
+ "set int ip address loop1 11.22.34.1/24",
+ "set int state loop1 up",
+ "set ip neighbor loop1 11.22.34.44 03:00:11:22:34:44",
+ "packet-generator new {\n"
+ " name s0\n"
+ " limit 100\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " tx-interface loop1\n"
+ " node loop1-output\n"
+ " buffer-flags ip4 offload\n"
+ " buffer-offload-flags offload-ip-cksum offload-udp-cksum\n"
+ " data {\n"
+ " IP4: 1.2.3 -> dead.0000.0001\n"
+ " UDP: 11.22.33.44 -> 11.22.34.44\n"
+ " ttl 2 checksum 13\n"
+ " UDP: 1234 -> 2345\n"
+ " checksum 11\n"
+ " incrementing 114\n"
+ " }\n"
+ "}",
+ "trace add pg-input 1",
+ "pa en",
+ "show error",
+ ]
for cmd in cmds:
r = self.vapi.cli_return_response(cmd)
if r.retval != 0:
- if hasattr(r, 'reply'):
+ if hasattr(r, "reply"):
self.logger.info(cmd + " FAIL reply " + r.reply)
else:
self.logger.info(cmd + " FAIL retval " + str(r.retval))
r = self.vapi.cli_return_response("show trace")
self.assertTrue(r.retval == 0)
- self.assertTrue(hasattr(r, 'reply'))
+ self.assertTrue(hasattr(r, "reply"))
rv = r.reply
- look_here = rv.find('ethernet-input')
+ look_here = rv.find("ethernet-input")
self.assertFalse(look_here == -1)
- bad_checksum_index = rv[look_here:].find('should be')
+ bad_checksum_index = rv[look_here:].find("should be")
self.assertTrue(bad_checksum_index == -1)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_p2p_ethernet.py b/test/test_p2p_ethernet.py
index fb55a365bee..97cd7b4f0bd 100644
--- a/test/test_p2p_ethernet.py
+++ b/test/test_p2p_ethernet.py
@@ -41,8 +41,7 @@ class P2PEthernetAPI(VppTestCase):
self.p2p_sub_ifs.append(p2p)
def delete_p2p_ethernet(self, parent_if, remote_mac):
- self.vapi.p2p_ethernet_del(parent_if.sw_if_index,
- mac_pton(remote_mac))
+ self.vapi.p2p_ethernet_del(parent_if.sw_if_index, mac_pton(remote_mac))
def test_api(self):
"""delete/create p2p subif"""
@@ -52,22 +51,22 @@ class P2PEthernetAPI(VppTestCase):
self.create_p2p_ethernet(self.pg0, 2, "de:ad:00:00:00:02")
intfs = self.vapi.cli("show interface")
- self.assertIn('pg0.1', intfs)
- self.assertIn('pg0.2', intfs)
- self.assertNotIn('pg0.5', intfs)
+ self.assertIn("pg0.1", intfs)
+ self.assertIn("pg0.2", intfs)
+ self.assertNotIn("pg0.5", intfs)
# create pg2.5 subif
self.create_p2p_ethernet(self.pg0, 5, "de:ad:00:00:00:ff")
intfs = self.vapi.cli("show interface")
- self.assertIn('pg0.5', intfs)
+ self.assertIn("pg0.5", intfs)
# delete pg2.5 subif
self.delete_p2p_ethernet(self.pg0, "de:ad:00:00:00:ff")
intfs = self.vapi.cli("show interface")
- self.assertIn('pg0.1', intfs)
- self.assertIn('pg0.2', intfs)
- self.assertNotIn('pg0.5', intfs)
+ self.assertIn("pg0.1", intfs)
+ self.assertIn("pg0.2", intfs)
+ self.assertNotIn("pg0.5", intfs)
self.logger.info("FFP_TEST_FINISH_0000")
@@ -79,22 +78,20 @@ class P2PEthernetAPI(VppTestCase):
clients = 1000
mac = int("dead00000000", 16)
- for i in range(1, clients+1):
+ for i in range(1, clients + 1):
try:
- macs.append(':'.join(re.findall('..', '{:02x}'.format(
- mac+i))))
- self.vapi.p2p_ethernet_add(self.pg2.sw_if_index,
- mac_pton(macs[i-1]),
- i)
+ macs.append(":".join(re.findall("..", "{:02x}".format(mac + i))))
+ self.vapi.p2p_ethernet_add(
+ self.pg2.sw_if_index, mac_pton(macs[i - 1]), i
+ )
except Exception:
- self.logger.info("Failed to create subif %d %s" % (
- i, macs[i-1]))
+ self.logger.info("Failed to create subif %d %s" % (i, macs[i - 1]))
raise
intfs = self.vapi.cli("show interface").split("\n")
count = 0
for intf in intfs:
- if intf.startswith('pg2.'):
+ if intf.startswith("pg2."):
count += 1
self.assertEqual(count, clients)
@@ -138,11 +135,11 @@ class P2PEthernetIPV6(VppTestCase):
for p in self.packets:
self.packets.remove(p)
self.p2p_sub_ifs.append(
- self.create_p2p_ethernet(self.pg0, 1,
- self.pg0._remote_hosts[0].mac))
+ self.create_p2p_ethernet(self.pg0, 1, self.pg0._remote_hosts[0].mac)
+ )
self.p2p_sub_ifs.append(
- self.create_p2p_ethernet(self.pg0, 2,
- self.pg0._remote_hosts[1].mac))
+ self.create_p2p_ethernet(self.pg0, 2, self.pg0._remote_hosts[1].mac)
+ )
self.vapi.cli("trace add p2p-ethernet-input 50")
def tearDown(self):
@@ -162,17 +159,17 @@ class P2PEthernetIPV6(VppTestCase):
def delete_p2p_ethernet(self, p2p):
p2p.unconfig_ip6()
p2p.admin_down()
- self.vapi.p2p_ethernet_del(p2p.parent.sw_if_index,
- p2p.p2p_remote_mac)
+ self.vapi.p2p_ethernet_del(p2p.parent.sw_if_index, p2p.p2p_remote_mac)
- def create_stream(self, src_mac=None, dst_mac=None,
- src_ip=None, dst_ip=None, size=None):
+ def create_stream(
+ self, src_mac=None, dst_mac=None, src_ip=None, dst_ip=None, size=None
+ ):
pkt_size = size
if size is None:
pkt_size = random.choice(self.pg_if_packet_sizes)
p = Ether(src=src_mac, dst=dst_mac)
p /= IPv6(src=src_ip, dst=dst_ip)
- p /= (UDP(sport=1234, dport=4321) / Raw(b'\xa5' * 20))
+ p /= UDP(sport=1234, dport=4321) / Raw(b"\xa5" * 20)
self.extend_packet(p, pkt_size)
return p
@@ -191,16 +188,22 @@ class P2PEthernetIPV6(VppTestCase):
self.logger.info("FFP_TEST_START_0001")
self.pg0.config_ip6()
- route_8000 = VppIpRoute(self, "8000::", 64,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index)])
+ route_8000 = VppIpRoute(
+ self,
+ "8000::",
+ 64,
+ [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)],
+ )
route_8000.add_vpp_config()
- self.packets = [(Ether(dst=self.pg1.local_mac,
- src=self.pg1.remote_mac) /
- IPv6(src="3001::1", dst="8000::100") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
+ self.packets = [
+ (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src="3001::1", dst="8000::100")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ ]
self.send_packets(self.pg1, self.pg0)
self.pg0.unconfig_ip6()
@@ -210,19 +213,25 @@ class P2PEthernetIPV6(VppTestCase):
"""receive ipv6 packet via p2p subinterface"""
self.logger.info("FFP_TEST_START_0002")
- route_9001 = VppIpRoute(self, "9001::", 64,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ route_9001 = VppIpRoute(
+ self,
+ "9001::",
+ 64,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ )
route_9001.add_vpp_config()
self.packets.append(
- self.create_stream(src_mac=self.pg0._remote_hosts[0].mac,
- dst_mac=self.pg0.local_mac,
- src_ip=self.p2p_sub_ifs[0].remote_ip6,
- dst_ip="9001::100"))
+ self.create_stream(
+ src_mac=self.pg0._remote_hosts[0].mac,
+ dst_mac=self.pg0.local_mac,
+ src_ip=self.p2p_sub_ifs[0].remote_ip6,
+ dst_ip="9001::100",
+ )
+ )
self.send_packets(self.pg0, self.pg1, self.packets)
- self.assert_packet_counter_equal('p2p-ethernet-input', 1)
+ self.assert_packet_counter_equal("p2p-ethernet-input", 1)
route_9001.remove_vpp_config()
self.logger.info("FFP_TEST_FINISH_0002")
@@ -233,16 +242,22 @@ class P2PEthernetIPV6(VppTestCase):
self.pg0.config_ip6()
- route_3 = VppIpRoute(self, "9000::", 64,
- [VppRoutePath(self.pg1._remote_hosts[0].ip6,
- self.pg1.sw_if_index)])
+ route_3 = VppIpRoute(
+ self,
+ "9000::",
+ 64,
+ [VppRoutePath(self.pg1._remote_hosts[0].ip6, self.pg1.sw_if_index)],
+ )
route_3.add_vpp_config()
self.packets.append(
- self.create_stream(src_mac="02:03:00:00:ff:ff",
- dst_mac=self.pg0.local_mac,
- src_ip="a000::100",
- dst_ip="9000::100"))
+ self.create_stream(
+ src_mac="02:03:00:00:ff:ff",
+ dst_mac=self.pg0.local_mac,
+ src_ip="a000::100",
+ dst_ip="9000::100",
+ )
+ )
self.send_packets(self.pg0, self.pg1)
@@ -256,16 +271,22 @@ class P2PEthernetIPV6(VppTestCase):
"""drop rx packet not matching p2p subinterface"""
self.logger.info("FFP_TEST_START_0004")
- route_9001 = VppIpRoute(self, "9000::", 64,
- [VppRoutePath(self.pg1._remote_hosts[0].ip6,
- self.pg1.sw_if_index)])
+ route_9001 = VppIpRoute(
+ self,
+ "9000::",
+ 64,
+ [VppRoutePath(self.pg1._remote_hosts[0].ip6, self.pg1.sw_if_index)],
+ )
route_9001.add_vpp_config()
self.packets.append(
- self.create_stream(src_mac="02:03:00:00:ff:ff",
- dst_mac=self.pg0.local_mac,
- src_ip="a000::100",
- dst_ip="9000::100"))
+ self.create_stream(
+ src_mac="02:03:00:00:ff:ff",
+ dst_mac=self.pg0.local_mac,
+ src_ip="a000::100",
+ dst_ip="9000::100",
+ )
+ )
# no packet received
self.send_packets(self.pg0, self.pg1, count=0)
@@ -277,27 +298,45 @@ class P2PEthernetIPV6(VppTestCase):
self.pg0.config_ip6()
- route_8000 = VppIpRoute(self, "8000::", 64,
- [VppRoutePath(self.pg0.remote_hosts[0].ip6,
- self.pg0.sw_if_index)])
+ route_8000 = VppIpRoute(
+ self,
+ "8000::",
+ 64,
+ [VppRoutePath(self.pg0.remote_hosts[0].ip6, self.pg0.sw_if_index)],
+ )
route_8000.add_vpp_config()
- route_8001 = VppIpRoute(self, "8001::", 64,
- [VppRoutePath(
- self.p2p_sub_ifs[0].remote_ip6,
- self.p2p_sub_ifs[0].sw_if_index)])
+ route_8001 = VppIpRoute(
+ self,
+ "8001::",
+ 64,
+ [
+ VppRoutePath(
+ self.p2p_sub_ifs[0].remote_ip6, self.p2p_sub_ifs[0].sw_if_index
+ )
+ ],
+ )
route_8001.add_vpp_config()
- route_8002 = VppIpRoute(self, "8002::", 64,
- [VppRoutePath(
- self.p2p_sub_ifs[1].remote_ip6,
- self.p2p_sub_ifs[1].sw_if_index)])
+ route_8002 = VppIpRoute(
+ self,
+ "8002::",
+ 64,
+ [
+ VppRoutePath(
+ self.p2p_sub_ifs[1].remote_ip6, self.p2p_sub_ifs[1].sw_if_index
+ )
+ ],
+ )
route_8002.add_vpp_config()
for i in range(0, 3):
self.packets.append(
- self.create_stream(src_mac=self.pg1.remote_mac,
- dst_mac=self.pg1.local_mac,
- src_ip=self.pg1.remote_ip6,
- dst_ip="800%d::100" % i))
+ self.create_stream(
+ src_mac=self.pg1.remote_mac,
+ dst_mac=self.pg1.local_mac,
+ src_ip=self.pg1.remote_ip6,
+ dst_ip="800%d::100" % i,
+ )
+ )
self.send_packets(self.pg1, self.pg0, count=3)
@@ -313,10 +352,13 @@ class P2PEthernetIPV6(VppTestCase):
self.logger.info("FFP_TEST_START_0006")
self.packets.append(
- self.create_stream(src_mac="02:03:00:00:ff:ff",
- dst_mac=self.pg0.local_mac,
- src_ip="a000::100",
- dst_ip="9000::100"))
+ self.create_stream(
+ src_mac="02:03:00:00:ff:ff",
+ dst_mac=self.pg0.local_mac,
+ src_ip="a000::100",
+ dst_ip="9000::100",
+ )
+ )
# no packet received
self.send_packets(self.pg0, self.pg1, count=0)
@@ -360,11 +402,11 @@ class P2PEthernetIPV4(VppTestCase):
for p in self.packets:
self.packets.remove(p)
self.p2p_sub_ifs.append(
- self.create_p2p_ethernet(self.pg0, 1,
- self.pg0._remote_hosts[0].mac))
+ self.create_p2p_ethernet(self.pg0, 1, self.pg0._remote_hosts[0].mac)
+ )
self.p2p_sub_ifs.append(
- self.create_p2p_ethernet(self.pg0, 2,
- self.pg0._remote_hosts[1].mac))
+ self.create_p2p_ethernet(self.pg0, 2, self.pg0._remote_hosts[1].mac)
+ )
self.vapi.cli("trace add p2p-ethernet-input 50")
def tearDown(self):
@@ -373,14 +415,15 @@ class P2PEthernetIPV4(VppTestCase):
self.delete_p2p_ethernet(p2p)
super(P2PEthernetIPV4, self).tearDown()
- def create_stream(self, src_mac=None, dst_mac=None,
- src_ip=None, dst_ip=None, size=None):
+ def create_stream(
+ self, src_mac=None, dst_mac=None, src_ip=None, dst_ip=None, size=None
+ ):
pkt_size = size
if size is None:
pkt_size = random.choice(self.pg_if_packet_sizes)
p = Ether(src=src_mac, dst=dst_mac)
p /= IP(src=src_ip, dst=dst_ip)
- p /= (UDP(sport=1234, dport=4321) / Raw(b'\xa5' * 20))
+ p /= UDP(sport=1234, dport=4321) / Raw(b"\xa5" * 20)
self.extend_packet(p, pkt_size)
return p
@@ -403,27 +446,32 @@ class P2PEthernetIPV4(VppTestCase):
def delete_p2p_ethernet(self, p2p):
p2p.unconfig_ip4()
p2p.admin_down()
- self.vapi.p2p_ethernet_del(p2p.parent.sw_if_index,
- p2p.p2p_remote_mac)
+ self.vapi.p2p_ethernet_del(p2p.parent.sw_if_index, p2p.p2p_remote_mac)
def test_ip4_rx_p2p_subif(self):
"""receive ipv4 packet via p2p subinterface"""
self.logger.info("FFP_TEST_START_0002")
- route_9000 = VppIpRoute(self, "9.0.0.0", 16,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_9000 = VppIpRoute(
+ self,
+ "9.0.0.0",
+ 16,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_9000.add_vpp_config()
self.packets.append(
- self.create_stream(src_mac=self.pg0._remote_hosts[0].mac,
- dst_mac=self.pg0.local_mac,
- src_ip=self.p2p_sub_ifs[0].remote_ip4,
- dst_ip="9.0.0.100"))
+ self.create_stream(
+ src_mac=self.pg0._remote_hosts[0].mac,
+ dst_mac=self.pg0.local_mac,
+ src_ip=self.p2p_sub_ifs[0].remote_ip4,
+ dst_ip="9.0.0.100",
+ )
+ )
self.send_packets(self.pg0, self.pg1, self.packets)
- self.assert_packet_counter_equal('p2p-ethernet-input', 1)
+ self.assert_packet_counter_equal("p2p-ethernet-input", 1)
route_9000.remove_vpp_config()
self.logger.info("FFP_TEST_FINISH_0002")
@@ -432,16 +480,22 @@ class P2PEthernetIPV4(VppTestCase):
"""route rx packet not matching p2p subinterface"""
self.logger.info("FFP_TEST_START_0003")
- route_9001 = VppIpRoute(self, "9.0.0.0", 24,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_9001 = VppIpRoute(
+ self,
+ "9.0.0.0",
+ 24,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_9001.add_vpp_config()
self.packets.append(
- self.create_stream(src_mac="02:01:00:00:ff:ff",
- dst_mac=self.pg0.local_mac,
- src_ip="8.0.0.100",
- dst_ip="9.0.0.100"))
+ self.create_stream(
+ src_mac="02:01:00:00:ff:ff",
+ dst_mac=self.pg0.local_mac,
+ src_ip="8.0.0.100",
+ dst_ip="9.0.0.100",
+ )
+ )
self.send_packets(self.pg0, self.pg1)
@@ -453,28 +507,51 @@ class P2PEthernetIPV4(VppTestCase):
"""send ip4 packet via p2p subinterface"""
self.logger.info("FFP_TEST_START_0005")
- route_9100 = VppIpRoute(self, "9.1.0.100", 24,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- )])
+ route_9100 = VppIpRoute(
+ self,
+ "9.1.0.100",
+ 24,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4,
+ self.pg0.sw_if_index,
+ )
+ ],
+ )
route_9100.add_vpp_config()
- route_9200 = VppIpRoute(self, "9.2.0.100", 24,
- [VppRoutePath(self.p2p_sub_ifs[0].remote_ip4,
- self.p2p_sub_ifs[0].sw_if_index,
- )])
+ route_9200 = VppIpRoute(
+ self,
+ "9.2.0.100",
+ 24,
+ [
+ VppRoutePath(
+ self.p2p_sub_ifs[0].remote_ip4,
+ self.p2p_sub_ifs[0].sw_if_index,
+ )
+ ],
+ )
route_9200.add_vpp_config()
- route_9300 = VppIpRoute(self, "9.3.0.100", 24,
- [VppRoutePath(self.p2p_sub_ifs[1].remote_ip4,
- self.p2p_sub_ifs[1].sw_if_index
- )])
+ route_9300 = VppIpRoute(
+ self,
+ "9.3.0.100",
+ 24,
+ [
+ VppRoutePath(
+ self.p2p_sub_ifs[1].remote_ip4, self.p2p_sub_ifs[1].sw_if_index
+ )
+ ],
+ )
route_9300.add_vpp_config()
for i in range(0, 3):
self.packets.append(
- self.create_stream(src_mac=self.pg1.remote_mac,
- dst_mac=self.pg1.local_mac,
- src_ip=self.pg1.remote_ip4,
- dst_ip="9.%d.0.100" % (i+1)))
+ self.create_stream(
+ src_mac=self.pg1.remote_mac,
+ dst_mac=self.pg1.local_mac,
+ src_ip=self.pg1.remote_ip4,
+ dst_ip="9.%d.0.100" % (i + 1),
+ )
+ )
self.send_packets(self.pg1, self.pg0)
@@ -490,15 +567,18 @@ class P2PEthernetIPV4(VppTestCase):
self.logger.info("FFP_TEST_START_0006")
self.packets.append(
- self.create_stream(src_mac="02:01:00:00:ff:ff",
- dst_mac=self.pg0.local_mac,
- src_ip="8.0.0.100",
- dst_ip="9.0.0.100"))
+ self.create_stream(
+ src_mac="02:01:00:00:ff:ff",
+ dst_mac=self.pg0.local_mac,
+ src_ip="8.0.0.100",
+ dst_ip="9.0.0.100",
+ )
+ )
# no packet received
self.send_packets(self.pg0, self.pg1, count=0)
self.logger.info("FFP_TEST_FINISH_0006")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_pcap.py b/test/test_pcap.py
index 5bfac523e43..7405d2e5153 100644
--- a/test/test_pcap.py
+++ b/test/test_pcap.py
@@ -8,7 +8,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
class TestPcap(VppTestCase):
- """ Pcap Unit Test Cases """
+ """Pcap Unit Test Cases"""
@classmethod
def setUpClass(cls):
@@ -24,67 +24,68 @@ class TestPcap(VppTestCase):
def tearDown(self):
super(TestPcap, self).tearDown()
-# This is a code coverage test, but it only runs for 0.3 seconds
-# might as well just run it...
+ # This is a code coverage test, but it only runs for 0.3 seconds
+ # might as well just run it...
def test_pcap_unittest(self):
- """ PCAP Capture Tests """
- cmds = ["loop create",
- "set int ip address loop0 11.22.33.1/24",
- "set int state loop0 up",
- "loop create",
- "set int ip address loop1 11.22.34.1/24",
- "set int state loop1 up",
- "set ip neighbor loop1 11.22.34.44 03:00:11:22:34:44",
- "packet-generator new {\n"
- " name s0\n"
- " limit 10\n"
- " size 128-128\n"
- " interface loop0\n"
- " tx-interface loop1\n"
- " node loop1-output\n"
- " buffer-flags ip4 offload\n"
- " buffer-offload-flags offload-ip-cksum offload-udp-cksum\n"
- " data {\n"
- " IP4: 1.2.3 -> dead.0000.0001\n"
- " UDP: 11.22.33.44 -> 11.22.34.44\n"
- " ttl 2 checksum 13\n"
- " UDP: 1234 -> 2345\n"
- " checksum 11\n"
- " incrementing 114\n"
- " }\n"
- "}",
- "pcap dispatch trace on max 100 buffer-trace pg-input 10",
- "pa en",
- "pcap dispatch trace off",
- "pcap trace rx tx max 1000 intfc any",
- "pa en",
- "pcap trace status",
- "pcap trace rx tx off",
- "classify filter pcap mask l3 ip4 src "
- "match l3 ip4 src 11.22.33.44",
- "pcap trace rx tx max 1000 intfc any file filt.pcap filter",
- "show cla t verbose 2",
- "show cla t verbose",
- "show cla t",
- "pa en",
- "pcap trace rx tx off",
- "classify filter pcap del mask l3 ip4 src"]
+ """PCAP Capture Tests"""
+ cmds = [
+ "loop create",
+ "set int ip address loop0 11.22.33.1/24",
+ "set int state loop0 up",
+ "loop create",
+ "set int ip address loop1 11.22.34.1/24",
+ "set int state loop1 up",
+ "set ip neighbor loop1 11.22.34.44 03:00:11:22:34:44",
+ "packet-generator new {\n"
+ " name s0\n"
+ " limit 10\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " tx-interface loop1\n"
+ " node loop1-output\n"
+ " buffer-flags ip4 offload\n"
+ " buffer-offload-flags offload-ip-cksum offload-udp-cksum\n"
+ " data {\n"
+ " IP4: 1.2.3 -> dead.0000.0001\n"
+ " UDP: 11.22.33.44 -> 11.22.34.44\n"
+ " ttl 2 checksum 13\n"
+ " UDP: 1234 -> 2345\n"
+ " checksum 11\n"
+ " incrementing 114\n"
+ " }\n"
+ "}",
+ "pcap dispatch trace on max 100 buffer-trace pg-input 10",
+ "pa en",
+ "pcap dispatch trace off",
+ "pcap trace rx tx max 1000 intfc any",
+ "pa en",
+ "pcap trace status",
+ "pcap trace rx tx off",
+ "classify filter pcap mask l3 ip4 src match l3 ip4 src 11.22.33.44",
+ "pcap trace rx tx max 1000 intfc any file filt.pcap filter",
+ "show cla t verbose 2",
+ "show cla t verbose",
+ "show cla t",
+ "pa en",
+ "pcap trace rx tx off",
+ "classify filter pcap del mask l3 ip4 src",
+ ]
for cmd in cmds:
r = self.vapi.cli_return_response(cmd)
if r.retval != 0:
- if hasattr(r, 'reply'):
+ if hasattr(r, "reply"):
self.logger.info(cmd + " FAIL reply " + r.reply)
else:
self.logger.info(cmd + " FAIL retval " + str(r.retval))
- self.assertTrue(os.path.exists('/tmp/dispatch.pcap'))
- self.assertTrue(os.path.exists('/tmp/rxtx.pcap'))
- self.assertTrue(os.path.exists('/tmp/filt.pcap'))
- os.remove('/tmp/dispatch.pcap')
- os.remove('/tmp/rxtx.pcap')
- os.remove('/tmp/filt.pcap')
+ self.assertTrue(os.path.exists("/tmp/dispatch.pcap"))
+ self.assertTrue(os.path.exists("/tmp/rxtx.pcap"))
+ self.assertTrue(os.path.exists("/tmp/filt.pcap"))
+ os.remove("/tmp/dispatch.pcap")
+ os.remove("/tmp/rxtx.pcap")
+ os.remove("/tmp/filt.pcap")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_pg.py b/test/test_pg.py
index 76b7fd7f1d9..f2a23e55f23 100644
--- a/test/test_pg.py
+++ b/test/test_pg.py
@@ -12,7 +12,7 @@ from framework import VppTestCase, VppTestRunner
class TestPgTun(VppTestCase):
- """ PG Test Case """
+ """PG Test Case"""
def setUp(self):
super(TestPgTun, self).setUp()
@@ -41,7 +41,7 @@ class TestPgTun(VppTestCase):
super(TestPgTun, self).tearDown()
def test_pg_tun(self):
- """ IP[46] Tunnel Mode PG """
+ """IP[46] Tunnel Mode PG"""
#
# test that we can send and receive IP encap'd packets on the
@@ -50,9 +50,11 @@ class TestPgTun(VppTestCase):
N_PKTS = 31
# v4 tun to ethernet
- p = (IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw('0' * 48))
+ p = (
+ IP(src=self.pg1.remote_ip4, dst=self.pg0.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw("0" * 48)
+ )
rxs = self.send_and_expect(self.pg1, p * N_PKTS, self.pg0)
for rx in rxs:
@@ -60,9 +62,11 @@ class TestPgTun(VppTestCase):
self.assertEqual(rx[IP].dst, self.pg0.remote_ip4)
# v6 tun to ethernet
- p = (IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw('0' * 48))
+ p = (
+ IPv6(src=self.pg2.remote_ip6, dst=self.pg0.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw("0" * 48)
+ )
rxs = self.send_and_expect(self.pg2, p * N_PKTS, self.pg0)
for rx in rxs:
@@ -70,10 +74,12 @@ class TestPgTun(VppTestCase):
self.assertEqual(rx[IPv6].dst, self.pg0.remote_ip6)
# eth to v4 tun
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw('0' * 48))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw("0" * 48)
+ )
rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg1)
for rx in rxs:
@@ -82,10 +88,12 @@ class TestPgTun(VppTestCase):
self.assertEqual(rx[IP].dst, self.pg1.remote_ip4)
# eth to v6 tun
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg2.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw('0' * 48))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg2.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw("0" * 48)
+ )
rxs = self.send_and_expect(self.pg0, p * N_PKTS, self.pg2)
for rx in rxs:
@@ -94,5 +102,5 @@ class TestPgTun(VppTestCase):
self.assertEqual(rx[IPv6].dst, self.pg2.remote_ip6)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_ping.py b/test/test_ping.py
index 8c5c087b0c5..c2eb8b75299 100644
--- a/test/test_ping.py
+++ b/test/test_ping.py
@@ -18,7 +18,7 @@ Basic test for sanity check of the ping.
class TestPing(VppTestCase):
- """ Ping Test Case """
+ """Ping Test Case"""
@classmethod
def setUpClass(cls):
@@ -64,7 +64,7 @@ class TestPing(VppTestCase):
return icmp
def test_ping_basic(self):
- """ basic ping test """
+ """basic ping test"""
try:
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -79,8 +79,9 @@ class TestPing(VppTestCase):
icmp_id = None
icmp_seq = 1
for p in out:
- icmp = self.verify_ping_request(p, self.pg1.local_ip4,
- self.pg1.remote_ip4, icmp_seq)
+ icmp = self.verify_ping_request(
+ p, self.pg1.local_ip4, self.pg1.remote_ip4, icmp_seq
+ )
icmp_seq = icmp_seq + 1
if icmp_id is None:
icmp_id = icmp.id
@@ -90,7 +91,7 @@ class TestPing(VppTestCase):
self.vapi.cli("show error")
def test_ping_burst(self):
- """ burst ping test """
+ """burst ping test"""
try:
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -100,13 +101,14 @@ class TestPing(VppTestCase):
ping_cmd = "ping " + remote_ip4 + " interval 0.01 burst 3"
ret = self.vapi.cli(ping_cmd)
self.logger.info(ret)
- out = self.pg1.get_capture(3*5)
+ out = self.pg1.get_capture(3 * 5)
icmp_id = None
icmp_seq = 1
count = 0
for p in out:
- icmp = self.verify_ping_request(p, self.pg1.local_ip4,
- self.pg1.remote_ip4, icmp_seq)
+ icmp = self.verify_ping_request(
+ p, self.pg1.local_ip4, self.pg1.remote_ip4, icmp_seq
+ )
count = count + 1
if count >= 3:
icmp_seq = icmp_seq + 1
@@ -119,7 +121,7 @@ class TestPing(VppTestCase):
self.vapi.cli("show error")
def test_ping_src(self):
- """ ping with source address set """
+ """ping with source address set"""
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -128,17 +130,18 @@ class TestPing(VppTestCase):
nbr_addr = "10.0.0.2"
VppIpInterfaceAddress(self, self.pg1, "10.0.0.1", 24).add_vpp_config()
- VppNeighbor(self, self.pg1.sw_if_index,
- "00:11:22:33:44:55",
- nbr_addr).add_vpp_config()
+ VppNeighbor(
+ self, self.pg1.sw_if_index, "00:11:22:33:44:55", nbr_addr
+ ).add_vpp_config()
ping_cmd = "ping %s interval 0.01 repeat 3" % self.pg1.remote_ip4
ret = self.vapi.cli(ping_cmd)
out = self.pg1.get_capture(3)
icmp_seq = 1
for p in out:
- icmp = self.verify_ping_request(p, self.pg1.local_ip4,
- self.pg1.remote_ip4, icmp_seq)
+ icmp = self.verify_ping_request(
+ p, self.pg1.local_ip4, self.pg1.remote_ip4, icmp_seq
+ )
icmp_seq = icmp_seq + 1
self.pg_enable_capture(self.pg_interfaces)
@@ -152,7 +155,7 @@ class TestPing(VppTestCase):
icmp_seq = icmp_seq + 1
def test_ping_fib_routed_dst(self):
- """ ping destination routed according to FIB table """
+ """ping destination routed according to FIB table"""
try:
self.pg1.generate_remote_hosts(1)
@@ -160,17 +163,19 @@ class TestPing(VppTestCase):
self.pg_start()
routed_dst = "10.0.2.0"
self.logger.info(self.vapi.cli("show ip4 neighbors"))
- VppIpRoute(self, routed_dst, 24,
- [VppRoutePath(self.pg1.remote_hosts[0].ip4,
- self.pg1.sw_if_index)]).add_vpp_config()
+ VppIpRoute(
+ self,
+ routed_dst,
+ 24,
+ [VppRoutePath(self.pg1.remote_hosts[0].ip4, self.pg1.sw_if_index)],
+ ).add_vpp_config()
ping_cmd = "ping %s interval 0.01 repeat 3" % routed_dst
ret = self.vapi.cli(ping_cmd)
self.logger.info(ret)
out = self.pg1.get_capture(3)
icmp_seq = 1
for p in out:
- self.verify_ping_request(p, self.pg1.local_ip4, routed_dst,
- icmp_seq)
+ self.verify_ping_request(p, self.pg1.local_ip4, routed_dst, icmp_seq)
icmp_seq = icmp_seq + 1
finally:
self.vapi.cli("show error")
diff --git a/test/test_pipe.py b/test/test_pipe.py
index 937a28ef826..30540997ff6 100644
--- a/test/test_pipe.py
+++ b/test/test_pipe.py
@@ -28,20 +28,19 @@ class VppPipe(VppInterface):
def west(self):
return self.result.pipe_sw_if_index[0]
- def __init__(self, test, instance=0xffffffff):
+ def __init__(self, test, instance=0xFFFFFFFF):
super(VppPipe, self).__init__(test)
self._test = test
self.instance = instance
def add_vpp_config(self):
self.result = self._test.vapi.pipe_create(
- 0 if self.instance == 0xffffffff else 1,
- self.instance)
+ 0 if self.instance == 0xFFFFFFFF else 1, self.instance
+ )
self.set_sw_if_index(self.result.sw_if_index)
def remove_vpp_config(self):
- self._test.vapi.pipe_delete(
- self.result.sw_if_index)
+ self._test.vapi.pipe_delete(self.result.sw_if_index)
def object_id(self):
return "pipe-%d" % (self._sw_if_index)
@@ -56,14 +55,16 @@ class VppPipe(VppInterface):
def set_unnumbered(self, ip_sw_if_index, is_east, is_add=True):
if is_east:
res = self._test.vapi.sw_interface_set_unnumbered(
- ip_sw_if_index, self.east, is_add)
+ ip_sw_if_index, self.east, is_add
+ )
else:
res = self._test.vapi.sw_interface_set_unnumbered(
- ip_sw_if_index, self.west, is_add)
+ ip_sw_if_index, self.west, is_add
+ )
class TestPipe(VppTestCase):
- """ Pipes """
+ """Pipes"""
@classmethod
def setUpClass(cls):
@@ -88,7 +89,7 @@ class TestPipe(VppTestCase):
super(TestPipe, self).tearDown()
def test_pipe(self):
- """ Pipes """
+ """Pipes"""
pipes = [VppPipe(self), VppPipe(self, 10)]
@@ -99,26 +100,26 @@ class TestPipe(VppTestCase):
#
# L2 cross-connect pipe0 east with pg0 and west with pg1
#
- self.vapi.sw_interface_set_l2_xconnect(self.pg0.sw_if_index,
- pipes[0].east,
- enable=1)
- self.vapi.sw_interface_set_l2_xconnect(pipes[0].east,
- self.pg0.sw_if_index,
- enable=1)
- self.vapi.sw_interface_set_l2_xconnect(self.pg1.sw_if_index,
- pipes[0].west,
- enable=1)
- self.vapi.sw_interface_set_l2_xconnect(pipes[0].west,
- self.pg1.sw_if_index,
- enable=1)
+ self.vapi.sw_interface_set_l2_xconnect(
+ self.pg0.sw_if_index, pipes[0].east, enable=1
+ )
+ self.vapi.sw_interface_set_l2_xconnect(
+ pipes[0].east, self.pg0.sw_if_index, enable=1
+ )
+ self.vapi.sw_interface_set_l2_xconnect(
+ self.pg1.sw_if_index, pipes[0].west, enable=1
+ )
+ self.vapi.sw_interface_set_l2_xconnect(
+ pipes[0].west, self.pg1.sw_if_index, enable=1
+ )
# test bi-directional L2 flow pg0<->pg1
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg1.remote_mac) /
- IP(src="1.1.1.1",
- dst="1.1.1.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg1.remote_mac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg1)
self.send_and_expect(self.pg1, p * NUM_PKTS, self.pg0)
@@ -126,15 +127,20 @@ class TestPipe(VppTestCase):
#
# Attach ACL to ensure features are run on the pipe
#
- rule_1 = AclRule(is_permit=0, proto=17,
- src_prefix=IPv4Network("1.1.1.1/32"),
- dst_prefix=IPv4Network("1.1.1.2/32"), ports=1234)
+ rule_1 = AclRule(
+ is_permit=0,
+ proto=17,
+ src_prefix=IPv4Network("1.1.1.1/32"),
+ dst_prefix=IPv4Network("1.1.1.2/32"),
+ ports=1234,
+ )
acl = VppAcl(self, rules=[rule_1])
acl.add_vpp_config()
# Apply the ACL on the pipe on output
- acl_if_e = VppAclInterface(self, sw_if_index=pipes[0].east, n_input=0,
- acls=[acl])
+ acl_if_e = VppAclInterface(
+ self, sw_if_index=pipes[0].east, n_input=0, acls=[acl]
+ )
acl_if_e.add_vpp_config()
self.send_and_assert_no_replies(self.pg0, p * NUM_PKTS)
@@ -142,8 +148,9 @@ class TestPipe(VppTestCase):
# remove from output and apply on input
acl_if_e.remove_vpp_config()
- acl_if_w = VppAclInterface(self, sw_if_index=pipes[0].west, n_input=1,
- acls=[acl])
+ acl_if_w = VppAclInterface(
+ self, sw_if_index=pipes[0].west, n_input=1, acls=[acl]
+ )
acl_if_w.add_vpp_config()
self.send_and_assert_no_replies(self.pg0, p * NUM_PKTS)
@@ -172,30 +179,52 @@ class TestPipe(VppTestCase):
self.pg3.resolve_arp()
routes = []
- routes.append(VppIpRoute(self, "1.1.1.1", 32,
- [VppRoutePath(self.pg3.remote_ip4,
- self.pg3.sw_if_index)],
- table_id=2))
- routes.append(VppIpRoute(self, "1.1.1.1", 32,
- [VppRoutePath("0.0.0.0", pipes[1].east)],
- table_id=1))
- routes.append(VppIpRoute(self, "1.1.1.2", 32,
- [VppRoutePath("0.0.0.0", pipes[1].west)],
- table_id=2))
- routes.append(VppIpRoute(self, "1.1.1.2", 32,
- [VppRoutePath(self.pg2.remote_ip4,
- self.pg2.sw_if_index)],
- table_id=1))
+ routes.append(
+ VppIpRoute(
+ self,
+ "1.1.1.1",
+ 32,
+ [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)],
+ table_id=2,
+ )
+ )
+ routes.append(
+ VppIpRoute(
+ self,
+ "1.1.1.1",
+ 32,
+ [VppRoutePath("0.0.0.0", pipes[1].east)],
+ table_id=1,
+ )
+ )
+ routes.append(
+ VppIpRoute(
+ self,
+ "1.1.1.2",
+ 32,
+ [VppRoutePath("0.0.0.0", pipes[1].west)],
+ table_id=2,
+ )
+ )
+ routes.append(
+ VppIpRoute(
+ self,
+ "1.1.1.2",
+ 32,
+ [VppRoutePath(self.pg2.remote_ip4, self.pg2.sw_if_index)],
+ table_id=1,
+ )
+ )
for r in routes:
r.add_vpp_config()
- p_east = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src="1.1.1.2",
- dst="1.1.1.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_east = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src="1.1.1.2", dst="1.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
# bind the pipe ends to the correct tables
self.vapi.sw_interface_set_table(pipes[1].west, 0, 2)
@@ -211,27 +240,29 @@ class TestPipe(VppTestCase):
self.send_and_expect(self.pg2, p_east * NUM_PKTS, self.pg3)
# and the return path
- p_west = (Ether(src=self.pg3.remote_mac,
- dst=self.pg3.local_mac) /
- IP(src="1.1.1.1",
- dst="1.1.1.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_west = (
+ Ether(src=self.pg3.remote_mac, dst=self.pg3.local_mac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect(self.pg3, p_west * NUM_PKTS, self.pg2)
#
# Use ACLs to test features run on the Pipes
#
- acl_if_e1 = VppAclInterface(self, sw_if_index=pipes[1].east, n_input=0,
- acls=[acl])
+ acl_if_e1 = VppAclInterface(
+ self, sw_if_index=pipes[1].east, n_input=0, acls=[acl]
+ )
acl_if_e1.add_vpp_config()
self.send_and_assert_no_replies(self.pg2, p_east * NUM_PKTS)
self.send_and_expect(self.pg3, p_west * NUM_PKTS, self.pg2)
# remove from output and apply on input
acl_if_e1.remove_vpp_config()
- acl_if_w1 = VppAclInterface(self, sw_if_index=pipes[1].west, n_input=1,
- acls=[acl])
+ acl_if_w1 = VppAclInterface(
+ self, sw_if_index=pipes[1].west, n_input=1, acls=[acl]
+ )
acl_if_w1.add_vpp_config()
self.send_and_assert_no_replies(self.pg2, p_east * NUM_PKTS)
self.send_and_expect(self.pg3, p_west * NUM_PKTS, self.pg2)
@@ -249,5 +280,5 @@ class TestPipe(VppTestCase):
self.vapi.sw_interface_set_table(pipes[1].east, 0, 0)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_pnat.py b/test/test_pnat.py
index d5b60050691..faf66e6ed53 100644
--- a/test/test_pnat.py
+++ b/test/test_pnat.py
@@ -8,7 +8,8 @@ from vpp_papi import VppEnum
class TestPNAT(VppTestCase):
- """ PNAT Test Case """
+ """PNAT Test Case"""
+
maxDiff = None
@classmethod
@@ -42,147 +43,187 @@ class TestPNAT(VppTestCase):
self.assertEqual(rx, expected)
def ping_check(self):
- """ Verify non matching traffic works. """
+ """Verify non matching traffic works."""
p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
- icmpecho = (IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- ICMP())
- reply = (IP(src=self.pg0.local_ip4, dst=self.pg0.remote_ip4) /
- ICMP(type='echo-reply'))
- rx = self.send_and_expect(self.pg0, p_ether/icmpecho * 1, self.pg0)
+ icmpecho = IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) / ICMP()
+ reply = IP(src=self.pg0.local_ip4, dst=self.pg0.remote_ip4) / ICMP(
+ type="echo-reply"
+ )
+ rx = self.send_and_expect(self.pg0, p_ether / icmpecho * 1, self.pg0)
for p in rx:
reply[IP].id = p[IP].id
self.validate(p[1], reply)
def test_pnat(self):
- """ PNAT test """
+ """PNAT test"""
PNAT_IP4_INPUT = VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_INPUT
- PNAT_IP4_OUTPUT = \
- VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_OUTPUT
+ PNAT_IP4_OUTPUT = VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_OUTPUT
tests = [
{
- 'input': PNAT_IP4_INPUT,
- 'sw_if_index': self.pg0.sw_if_index,
- 'match': {'mask': 0xa, 'dst': '10.10.10.10', 'proto': 17,
- 'dport': 6871},
- 'rewrite': {'mask': 0x2, 'dst': self.pg1.remote_ip4},
- 'send': (IP(src=self.pg0.remote_ip4, dst='10.10.10.10') /
- UDP(dport=6871)),
- 'reply': (IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(dport=6871))
+ "input": PNAT_IP4_INPUT,
+ "sw_if_index": self.pg0.sw_if_index,
+ "match": {
+ "mask": 0xA,
+ "dst": "10.10.10.10",
+ "proto": 17,
+ "dport": 6871,
+ },
+ "rewrite": {"mask": 0x2, "dst": self.pg1.remote_ip4},
+ "send": (
+ IP(src=self.pg0.remote_ip4, dst="10.10.10.10") / UDP(dport=6871)
+ ),
+ "reply": (
+ IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(dport=6871)
+ ),
},
{
- 'input': PNAT_IP4_OUTPUT,
- 'sw_if_index': self.pg1.sw_if_index,
- 'match': {'mask': 0x9, 'src': self.pg0.remote_ip4, 'proto': 17,
- 'dport': 6871},
- 'rewrite': {'mask': 0x1, 'src': '11.11.11.11'},
- 'send': (IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP(dport=6871)),
- 'reply': (IP(src='11.11.11.11', dst=self.pg1.remote_ip4) /
- UDP(dport=6871))
+ "input": PNAT_IP4_OUTPUT,
+ "sw_if_index": self.pg1.sw_if_index,
+ "match": {
+ "mask": 0x9,
+ "src": self.pg0.remote_ip4,
+ "proto": 17,
+ "dport": 6871,
+ },
+ "rewrite": {"mask": 0x1, "src": "11.11.11.11"},
+ "send": (
+ IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(dport=6871)
+ ),
+ "reply": (
+ IP(src="11.11.11.11", dst=self.pg1.remote_ip4) / UDP(dport=6871)
+ ),
},
{
- 'input': PNAT_IP4_INPUT,
- 'sw_if_index': self.pg0.sw_if_index,
- 'match': {'mask': 0xa, 'dst': '10.10.10.10', 'proto': 17,
- 'dport': 6871},
- 'rewrite': {'mask': 0xa, 'dst': self.pg1.remote_ip4,
- 'dport': 5555},
- 'send': (IP(src=self.pg0.remote_ip4, dst='10.10.10.10') /
- UDP(sport=65530, dport=6871)),
- 'reply': (IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=65530, dport=5555))
+ "input": PNAT_IP4_INPUT,
+ "sw_if_index": self.pg0.sw_if_index,
+ "match": {
+ "mask": 0xA,
+ "dst": "10.10.10.10",
+ "proto": 17,
+ "dport": 6871,
+ },
+ "rewrite": {"mask": 0xA, "dst": self.pg1.remote_ip4, "dport": 5555},
+ "send": (
+ IP(src=self.pg0.remote_ip4, dst="10.10.10.10")
+ / UDP(sport=65530, dport=6871)
+ ),
+ "reply": (
+ IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=65530, dport=5555)
+ ),
},
{
- 'input': PNAT_IP4_INPUT,
- 'sw_if_index': self.pg0.sw_if_index,
- 'match': {'mask': 0xa, 'dst': self.pg1.remote_ip4, 'proto': 17,
- 'dport': 6871},
- 'rewrite': {'mask': 0x8, 'dport': 5555},
- 'send': (IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP(dport=6871, chksum=0)),
- 'reply': (IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(dport=5555, chksum=0))
+ "input": PNAT_IP4_INPUT,
+ "sw_if_index": self.pg0.sw_if_index,
+ "match": {
+ "mask": 0xA,
+ "dst": self.pg1.remote_ip4,
+ "proto": 17,
+ "dport": 6871,
+ },
+ "rewrite": {"mask": 0x8, "dport": 5555},
+ "send": (
+ IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(dport=6871, chksum=0)
+ ),
+ "reply": (
+ IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(dport=5555, chksum=0)
+ ),
},
{
- 'input': PNAT_IP4_INPUT,
- 'sw_if_index': self.pg0.sw_if_index,
- 'match': {'mask': 0x2, 'dst': self.pg1.remote_ip4, 'proto': 1},
- 'rewrite': {'mask': 0x1, 'src': '8.8.8.8'},
- 'send': (IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- ICMP()),
- 'reply': IP(src='8.8.8.8', dst=self.pg1.remote_ip4)/ICMP(),
+ "input": PNAT_IP4_INPUT,
+ "sw_if_index": self.pg0.sw_if_index,
+ "match": {"mask": 0x2, "dst": self.pg1.remote_ip4, "proto": 1},
+ "rewrite": {"mask": 0x1, "src": "8.8.8.8"},
+ "send": (IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) / ICMP()),
+ "reply": IP(src="8.8.8.8", dst=self.pg1.remote_ip4) / ICMP(),
},
]
p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
for t in tests:
- rv = self.vapi.pnat_binding_add(match=t['match'],
- rewrite=t['rewrite'])
- self.vapi.pnat_binding_attach(sw_if_index=t['sw_if_index'],
- attachment=t['input'],
- binding_index=rv.binding_index)
-
- reply = t['reply']
+ rv = self.vapi.pnat_binding_add(match=t["match"], rewrite=t["rewrite"])
+ self.vapi.pnat_binding_attach(
+ sw_if_index=t["sw_if_index"],
+ attachment=t["input"],
+ binding_index=rv.binding_index,
+ )
+
+ reply = t["reply"]
reply[IP].ttl -= 1
- rx = self.send_and_expect(self.pg0, p_ether/t['send']*1, self.pg1)
+ rx = self.send_and_expect(self.pg0, p_ether / t["send"] * 1, self.pg1)
for p in rx:
# p.show2()
self.validate(p[1], reply)
self.ping_check()
- self.vapi.pnat_binding_detach(sw_if_index=t['sw_if_index'],
- attachment=t['input'],
- binding_index=rv.binding_index)
+ self.vapi.pnat_binding_detach(
+ sw_if_index=t["sw_if_index"],
+ attachment=t["input"],
+ binding_index=rv.binding_index,
+ )
self.vapi.pnat_binding_del(binding_index=rv.binding_index)
def test_pnat_show(self):
- """ PNAT show tests """
+ """PNAT show tests"""
PNAT_IP4_INPUT = VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_INPUT
- PNAT_IP4_OUTPUT = \
- VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_OUTPUT
+ PNAT_IP4_OUTPUT = VppEnum.vl_api_pnat_attachment_point_t.PNAT_IP4_OUTPUT
tests = [
{
- 'input': PNAT_IP4_INPUT,
- 'sw_if_index': self.pg0.sw_if_index,
- 'match': {'mask': 0xa, 'dst': '10.10.10.10', 'proto': 17,
- 'dport': 6871},
- 'rewrite': {'mask': 0x2, 'dst': self.pg1.remote_ip4},
- 'send': (IP(src=self.pg0.remote_ip4, dst='10.10.10.10') /
- UDP(dport=6871)),
- 'reply': (IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(dport=6871))
+ "input": PNAT_IP4_INPUT,
+ "sw_if_index": self.pg0.sw_if_index,
+ "match": {
+ "mask": 0xA,
+ "dst": "10.10.10.10",
+ "proto": 17,
+ "dport": 6871,
+ },
+ "rewrite": {"mask": 0x2, "dst": self.pg1.remote_ip4},
+ "send": (
+ IP(src=self.pg0.remote_ip4, dst="10.10.10.10") / UDP(dport=6871)
+ ),
+ "reply": (
+ IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(dport=6871)
+ ),
},
{
- 'input': PNAT_IP4_OUTPUT,
- 'sw_if_index': self.pg1.sw_if_index,
- 'match': {'mask': 0x9, 'src': self.pg0.remote_ip4, 'proto': 17,
- 'dport': 6871},
- 'rewrite': {'mask': 0x1, 'src': '11.11.11.11'},
- 'send': (IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP(dport=6871)),
- 'reply': (IP(src='11.11.11.11', dst=self.pg1.remote_ip4) /
- UDP(dport=6871))
+ "input": PNAT_IP4_OUTPUT,
+ "sw_if_index": self.pg1.sw_if_index,
+ "match": {
+ "mask": 0x9,
+ "src": self.pg0.remote_ip4,
+ "proto": 17,
+ "dport": 6871,
+ },
+ "rewrite": {"mask": 0x1, "src": "11.11.11.11"},
+ "send": (
+ IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(dport=6871)
+ ),
+ "reply": (
+ IP(src="11.11.11.11", dst=self.pg1.remote_ip4) / UDP(dport=6871)
+ ),
},
]
binding_index = []
for t in tests:
- rv = self.vapi.pnat_binding_add(match=t['match'],
- rewrite=t['rewrite'])
+ rv = self.vapi.pnat_binding_add(match=t["match"], rewrite=t["rewrite"])
binding_index.append(rv.binding_index)
- self.vapi.pnat_binding_attach(sw_if_index=t['sw_if_index'],
- attachment=t['input'],
- binding_index=rv.binding_index)
+ self.vapi.pnat_binding_attach(
+ sw_if_index=t["sw_if_index"],
+ attachment=t["input"],
+ binding_index=rv.binding_index,
+ )
rv, l = self.vapi.pnat_bindings_get()
self.assertEqual(len(l), len(tests))
@@ -194,10 +235,13 @@ class TestPNAT(VppTestCase):
self.logger.info(self.vapi.cli("show pnat interfaces"))
for i, t in enumerate(tests):
- self.vapi.pnat_binding_detach(sw_if_index=t['sw_if_index'],
- attachment=t['input'],
- binding_index=binding_index[i])
+ self.vapi.pnat_binding_detach(
+ sw_if_index=t["sw_if_index"],
+ attachment=t["input"],
+ binding_index=binding_index[i],
+ )
self.vapi.pnat_binding_del(binding_index=binding_index[i])
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_policer.py b/test/test_policer.py
index 6b15a0234a3..01ee2b750bc 100644
--- a/test/test_policer.py
+++ b/test/test_policer.py
@@ -9,42 +9,53 @@ from vpp_policer import VppPolicer, PolicerAction
# Default for the tests is 10s of "Green" packets at 8Mbps, ie. 10M bytes.
# The policer helper CLI "sends" 500 byte packets, so default is 20000.
-TEST_RATE = 8000 # kbps
+TEST_RATE = 8000 # kbps
TEST_BURST = 10000 # ms
-CIR_OK = 8500 # CIR in kbps, above test rate
-CIR_LOW = 7000 # CIR in kbps, below test rate
-EIR_OK = 9000 # EIR in kbps, above test rate
-EIR_LOW = 7500 # EIR in kbps, below test rate
+CIR_OK = 8500 # CIR in kbps, above test rate
+CIR_LOW = 7000 # CIR in kbps, below test rate
+EIR_OK = 9000 # EIR in kbps, above test rate
+EIR_LOW = 7500 # EIR in kbps, below test rate
NUM_PKTS = 20000
-CBURST = 100000 # Committed burst in bytes
-EBURST = 200000 # Excess burst in bytes
+CBURST = 100000 # Committed burst in bytes
+EBURST = 200000 # Excess burst in bytes
class TestPolicer(VppTestCase):
- """ Policer Test Case """
+ """Policer Test Case"""
- def run_policer_test(self, type, cir, cb, eir, eb, rate=8000, burst=10000,
- colour=0):
+ def run_policer_test(
+ self, type, cir, cb, eir, eb, rate=8000, burst=10000, colour=0
+ ):
"""
Configure a Policer and push traffic through it.
"""
types = {
- '1R2C': 0,
- '1R3C': 1,
- '2R3C': 3,
+ "1R2C": 0,
+ "1R3C": 1,
+ "2R3C": 3,
}
pol_type = types.get(type)
- policer = VppPolicer(self, "pol1", cir, eir, cb, eb, rate_type=0,
- type=pol_type, color_aware=colour)
+ policer = VppPolicer(
+ self,
+ "pol1",
+ cir,
+ eir,
+ cb,
+ eb,
+ rate_type=0,
+ type=pol_type,
+ color_aware=colour,
+ )
policer.add_vpp_config()
error = self.vapi.cli(
f"test policing index {policer.policer_index} rate {rate} "
- f"burst {burst} colour {colour}")
+ f"burst {burst} colour {colour}"
+ )
stats = policer.get_stats()
policer.remove_vpp_config()
@@ -52,66 +63,64 @@ class TestPolicer(VppTestCase):
return stats
def test_policer_1r2c(self):
- """ Single rate, 2 colour policer """
+ """Single rate, 2 colour policer"""
stats = self.run_policer_test("1R2C", CIR_OK, CBURST, 0, 0)
- self.assertEqual(stats['conform_packets'], NUM_PKTS)
+ self.assertEqual(stats["conform_packets"], NUM_PKTS)
stats = self.run_policer_test("1R2C", CIR_LOW, CBURST, 0, 0)
- self.assertLess(stats['conform_packets'], NUM_PKTS)
- self.assertEqual(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ self.assertLess(stats["conform_packets"], NUM_PKTS)
+ self.assertEqual(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
stats = self.run_policer_test("1R2C", CIR_LOW, CBURST, 0, 0, colour=2)
- self.assertEqual(stats['violate_packets'], NUM_PKTS)
+ self.assertEqual(stats["violate_packets"], NUM_PKTS)
def test_policer_1r3c(self):
- """ Single rate, 3 colour policer """
+ """Single rate, 3 colour policer"""
stats = self.run_policer_test("1R3C", CIR_OK, CBURST, 0, 0)
- self.assertEqual(stats['conform_packets'], NUM_PKTS)
+ self.assertEqual(stats["conform_packets"], NUM_PKTS)
stats = self.run_policer_test("1R3C", CIR_LOW, CBURST, 0, EBURST)
- self.assertLess(stats['conform_packets'], NUM_PKTS)
- self.assertGreater(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ self.assertLess(stats["conform_packets"], NUM_PKTS)
+ self.assertGreater(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
- stats = self.run_policer_test("1R3C", CIR_LOW, CBURST, 0, EBURST,
- colour=1)
- self.assertEqual(stats['conform_packets'], 0)
- self.assertGreater(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ stats = self.run_policer_test("1R3C", CIR_LOW, CBURST, 0, EBURST, colour=1)
+ self.assertEqual(stats["conform_packets"], 0)
+ self.assertGreater(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
- stats = self.run_policer_test("1R3C", CIR_LOW, CBURST, 0, EBURST,
- colour=2)
- self.assertEqual(stats['violate_packets'], NUM_PKTS)
+ stats = self.run_policer_test("1R3C", CIR_LOW, CBURST, 0, EBURST, colour=2)
+ self.assertEqual(stats["violate_packets"], NUM_PKTS)
def test_policer_2r3c(self):
- """ Dual rate, 3 colour policer """
+ """Dual rate, 3 colour policer"""
stats = self.run_policer_test("2R3C", CIR_OK, CBURST, EIR_OK, EBURST)
- self.assertEqual(stats['conform_packets'], NUM_PKTS)
+ self.assertEqual(stats["conform_packets"], NUM_PKTS)
stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_OK, EBURST)
- self.assertLess(stats['conform_packets'], NUM_PKTS)
- self.assertGreater(stats['exceed_packets'], 0)
- self.assertEqual(stats['violate_packets'], 0)
+ self.assertLess(stats["conform_packets"], NUM_PKTS)
+ self.assertGreater(stats["exceed_packets"], 0)
+ self.assertEqual(stats["violate_packets"], 0)
stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_LOW, EBURST)
- self.assertLess(stats['conform_packets'], NUM_PKTS)
- self.assertGreater(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ self.assertLess(stats["conform_packets"], NUM_PKTS)
+ self.assertGreater(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
- stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_OK, EBURST,
- colour=1)
- self.assertEqual(stats['exceed_packets'], NUM_PKTS)
+ stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_OK, EBURST, colour=1)
+ self.assertEqual(stats["exceed_packets"], NUM_PKTS)
- stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_LOW, EBURST,
- colour=1)
- self.assertEqual(stats['conform_packets'], 0)
- self.assertGreater(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ stats = self.run_policer_test(
+ "2R3C", CIR_LOW, CBURST, EIR_LOW, EBURST, colour=1
+ )
+ self.assertEqual(stats["conform_packets"], 0)
+ self.assertGreater(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
- stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_OK, EBURST,
- colour=2)
- self.assertEqual(stats['violate_packets'], NUM_PKTS)
+ stats = self.run_policer_test("2R3C", CIR_LOW, CBURST, EIR_OK, EBURST, colour=2)
+ self.assertEqual(stats["violate_packets"], NUM_PKTS)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_policer_input.py b/test/test_policer_input.py
index 9a4266ceb12..9d44fc1a21c 100644
--- a/test/test_policer_input.py
+++ b/test/test_policer_input.py
@@ -14,7 +14,8 @@ NUM_PKTS = 67
class TestPolicerInput(VppTestCase):
- """ Policer on an interface """
+ """Policer on an interface"""
+
vpp_worker_count = 2
def setUp(self):
@@ -26,11 +27,12 @@ class TestPolicerInput(VppTestCase):
i.config_ip4()
i.resolve_arp()
- self.pkt = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ self.pkt = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
def tearDown(self):
for i in self.pg_interfaces:
@@ -42,17 +44,22 @@ class TestPolicerInput(VppTestCase):
pkts = self.pkt * NUM_PKTS
action_tx = PolicerAction(
- VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT,
- 0)
- policer = VppPolicer(self, "pol1", 80, 0, 1000, 0,
- conform_action=action_tx,
- exceed_action=action_tx,
- violate_action=action_tx)
+ VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0
+ )
+ policer = VppPolicer(
+ self,
+ "pol1",
+ 80,
+ 0,
+ 1000,
+ 0,
+ conform_action=action_tx,
+ exceed_action=action_tx,
+ violate_action=action_tx,
+ )
policer.add_vpp_config()
- sw_if_index = (self.pg0.sw_if_index
- if dir == Dir.RX
- else self.pg1.sw_if_index)
+ sw_if_index = self.pg0.sw_if_index if dir == Dir.RX else self.pg1.sw_if_index
# Start policing on pg0
policer.apply_vpp_config(sw_if_index, dir, True)
@@ -61,9 +68,9 @@ class TestPolicerInput(VppTestCase):
stats = policer.get_stats()
# Single rate, 2 colour policer - expect conform, violate but no exceed
- self.assertGreater(stats['conform_packets'], 0)
- self.assertEqual(stats['exceed_packets'], 0)
- self.assertGreater(stats['violate_packets'], 0)
+ self.assertGreater(stats["conform_packets"], 0)
+ self.assertEqual(stats["exceed_packets"], 0)
+ self.assertGreater(stats["violate_packets"], 0)
# Stop policing on pg0
policer.apply_vpp_config(sw_if_index, dir, False)
@@ -78,28 +85,33 @@ class TestPolicerInput(VppTestCase):
policer.remove_vpp_config()
def test_policer_input(self):
- """ Input Policing """
+ """Input Policing"""
self.policer_interface_test(Dir.RX)
def test_policer_output(self):
- """ Output Policing """
+ """Output Policing"""
self.policer_interface_test(Dir.TX)
def policer_handoff_test(self, dir: Dir):
pkts = self.pkt * NUM_PKTS
action_tx = PolicerAction(
- VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT,
- 0)
- policer = VppPolicer(self, "pol2", 80, 0, 1000, 0,
- conform_action=action_tx,
- exceed_action=action_tx,
- violate_action=action_tx)
+ VppEnum.vl_api_sse2_qos_action_type_t.SSE2_QOS_ACTION_API_TRANSMIT, 0
+ )
+ policer = VppPolicer(
+ self,
+ "pol2",
+ 80,
+ 0,
+ 1000,
+ 0,
+ conform_action=action_tx,
+ exceed_action=action_tx,
+ violate_action=action_tx,
+ )
policer.add_vpp_config()
- sw_if_index = (self.pg0.sw_if_index
- if dir == Dir.RX
- else self.pg1.sw_if_index)
+ sw_if_index = self.pg0.sw_if_index if dir == Dir.RX else self.pg1.sw_if_index
# Bind the policer to worker 1
policer.bind_vpp_config(1, True)
@@ -119,9 +131,9 @@ class TestPolicerInput(VppTestCase):
self.assertEqual(stats, stats1)
# Worker 0, should have handed everything off
- self.assertEqual(stats0['conform_packets'], 0)
- self.assertEqual(stats0['exceed_packets'], 0)
- self.assertEqual(stats0['violate_packets'], 0)
+ self.assertEqual(stats0["conform_packets"], 0)
+ self.assertEqual(stats0["exceed_packets"], 0)
+ self.assertEqual(stats0["violate_packets"], 0)
# Unbind the policer from worker 1 and repeat
policer.bind_vpp_config(1, False)
@@ -137,19 +149,23 @@ class TestPolicerInput(VppTestCase):
stats0 = policer.get_stats(worker=0)
stats1 = policer.get_stats(worker=1)
- self.assertGreater(stats0['conform_packets'], 0)
- self.assertEqual(stats0['exceed_packets'], 0)
- self.assertGreater(stats0['violate_packets'], 0)
+ self.assertGreater(stats0["conform_packets"], 0)
+ self.assertEqual(stats0["exceed_packets"], 0)
+ self.assertGreater(stats0["violate_packets"], 0)
- self.assertGreater(stats1['conform_packets'], 0)
- self.assertEqual(stats1['exceed_packets'], 0)
- self.assertGreater(stats1['violate_packets'], 0)
+ self.assertGreater(stats1["conform_packets"], 0)
+ self.assertEqual(stats1["exceed_packets"], 0)
+ self.assertGreater(stats1["violate_packets"], 0)
- self.assertEqual(stats0['conform_packets'] + stats1['conform_packets'],
- stats['conform_packets'])
+ self.assertEqual(
+ stats0["conform_packets"] + stats1["conform_packets"],
+ stats["conform_packets"],
+ )
- self.assertEqual(stats0['violate_packets'] + stats1['violate_packets'],
- stats['violate_packets'])
+ self.assertEqual(
+ stats0["violate_packets"] + stats1["violate_packets"],
+ stats["violate_packets"],
+ )
# Stop policing on pg0
policer.apply_vpp_config(sw_if_index, dir, False)
@@ -157,13 +173,13 @@ class TestPolicerInput(VppTestCase):
policer.remove_vpp_config()
def test_policer_handoff_input(self):
- """ Worker thread handoff policer input"""
+ """Worker thread handoff policer input"""
self.policer_handoff_test(Dir.RX)
def test_policer_handoff_output(self):
- """ Worker thread handoff policer output"""
+ """Worker thread handoff policer output"""
self.policer_handoff_test(Dir.TX)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_pppoe.py b/test/test_pppoe.py
index 99dba01cdc9..c83d7d5f874 100644
--- a/test/test_pppoe.py
+++ b/test/test_pppoe.py
@@ -15,7 +15,7 @@ from util import ppp, ppc
class TestPPPoE(VppTestCase):
- """ PPPoE Test Case """
+ """PPPoE Test Case"""
@classmethod
def setUpClass(cls):
@@ -54,8 +54,7 @@ class TestPPPoE(VppTestCase):
self.logger.info(self.vapi.cli("show ip fib"))
self.logger.info(self.vapi.cli("show trace"))
- def create_stream_pppoe_discovery(self, src_if, dst_if,
- client_mac, count=1):
+ def create_stream_pppoe_discovery(self, src_if, dst_if, client_mac, count=1):
packets = []
for i in range(count):
# create packet info stored in the test case instance
@@ -63,9 +62,11 @@ class TestPPPoE(VppTestCase):
# convert the info into packet payload
payload = self.info_to_payload(info)
# create the packet itself
- p = (Ether(dst=src_if.local_mac, src=client_mac) /
- PPPoED(sessionid=0) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=client_mac)
+ / PPPoED(sessionid=0)
+ / Raw(payload)
+ )
# store a copy of the packet in the packet info
info.data = p.copy()
# append the packet to the list
@@ -74,8 +75,7 @@ class TestPPPoE(VppTestCase):
# return the created packet list
return packets
- def create_stream_pppoe_lcp(self, src_if, dst_if,
- client_mac, session_id, count=1):
+ def create_stream_pppoe_lcp(self, src_if, dst_if, client_mac, session_id, count=1):
packets = []
for i in range(count):
# create packet info stored in the test case instance
@@ -83,10 +83,12 @@ class TestPPPoE(VppTestCase):
# convert the info into packet payload
payload = self.info_to_payload(info)
# create the packet itself
- p = (Ether(dst=src_if.local_mac, src=client_mac) /
- PPPoE(sessionid=session_id) /
- PPP(proto=0xc021) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=client_mac)
+ / PPPoE(sessionid=session_id)
+ / PPP(proto=0xC021)
+ / Raw(payload)
+ )
# store a copy of the packet in the packet info
info.data = p.copy()
# append the packet to the list
@@ -95,8 +97,9 @@ class TestPPPoE(VppTestCase):
# return the created packet list
return packets
- def create_stream_pppoe_ip4(self, src_if, dst_if,
- client_mac, session_id, client_ip, count=1):
+ def create_stream_pppoe_ip4(
+ self, src_if, dst_if, client_mac, session_id, client_ip, count=1
+ ):
packets = []
for i in range(count):
# create packet info stored in the test case instance
@@ -104,11 +107,13 @@ class TestPPPoE(VppTestCase):
# convert the info into packet payload
payload = self.info_to_payload(info)
# create the packet itself
- p = (Ether(dst=src_if.local_mac, src=client_mac) /
- PPPoE(sessionid=session_id) /
- PPP(proto=0x0021) /
- IP(src=client_ip, dst=self.dst_ip) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=client_mac)
+ / PPPoE(sessionid=session_id)
+ / PPP(proto=0x0021)
+ / IP(src=client_ip, dst=self.dst_ip)
+ / Raw(payload)
+ )
# store a copy of the packet in the packet info
info.data = p.copy()
# append the packet to the list
@@ -125,9 +130,11 @@ class TestPPPoE(VppTestCase):
# convert the info into packet payload
payload = self.info_to_payload(info)
# create the packet itself
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=dst_ip, dst=client_ip) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=dst_ip, dst=client_ip)
+ / Raw(payload)
+ )
# store a copy of the packet in the packet info
info.data = p.copy()
# append the packet to the list
@@ -180,36 +187,39 @@ class TestPPPoE(VppTestCase):
raise
def test_PPPoE_Decap(self):
- """ PPPoE Decap Test """
+ """PPPoE Decap Test"""
self.vapi.cli("clear trace")
#
# Add a route that resolves the server's destination
#
- route_sever_dst = VppIpRoute(self, "100.1.1.100", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_sever_dst = VppIpRoute(
+ self,
+ "100.1.1.100",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_sever_dst.add_vpp_config()
# Send PPPoE Discovery
- tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1,
- self.pg0.remote_mac)
+ tx0 = self.create_stream_pppoe_discovery(
+ self.pg0, self.pg1, self.pg0.remote_mac
+ )
self.pg0.add_stream(tx0)
self.pg_start()
# Send PPPoE PPP LCP
- tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1,
- self.pg0.remote_mac,
- self.session_id)
+ tx1 = self.create_stream_pppoe_lcp(
+ self.pg0, self.pg1, self.pg0.remote_mac, self.session_id
+ )
self.pg0.add_stream(tx1)
self.pg_start()
# Create PPPoE session
- pppoe_if = VppPppoeInterface(self,
- self.pg0.remote_ip4,
- self.pg0.remote_mac,
- self.session_id)
+ pppoe_if = VppPppoeInterface(
+ self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id
+ )
pppoe_if.add_vpp_config()
pppoe_if.set_unnumbered(self.pg0.sw_if_index)
@@ -217,10 +227,13 @@ class TestPPPoE(VppTestCase):
# Send tunneled packets that match the created tunnel and
# are decapped and forwarded
#
- tx2 = self.create_stream_pppoe_ip4(self.pg0, self.pg1,
- self.pg0.remote_mac,
- self.session_id,
- self.pg0.remote_ip4)
+ tx2 = self.create_stream_pppoe_ip4(
+ self.pg0,
+ self.pg1,
+ self.pg0.remote_mac,
+ self.session_id,
+ self.pg0.remote_ip4,
+ )
self.pg0.add_stream(tx2)
self.pg_enable_capture(self.pg_interfaces)
@@ -244,36 +257,39 @@ class TestPPPoE(VppTestCase):
route_sever_dst.remove_vpp_config()
def test_PPPoE_Encap(self):
- """ PPPoE Encap Test """
+ """PPPoE Encap Test"""
self.vapi.cli("clear trace")
#
# Add a route that resolves the server's destination
#
- route_sever_dst = VppIpRoute(self, "100.1.1.100", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_sever_dst = VppIpRoute(
+ self,
+ "100.1.1.100",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_sever_dst.add_vpp_config()
# Send PPPoE Discovery
- tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1,
- self.pg0.remote_mac)
+ tx0 = self.create_stream_pppoe_discovery(
+ self.pg0, self.pg1, self.pg0.remote_mac
+ )
self.pg0.add_stream(tx0)
self.pg_start()
# Send PPPoE PPP LCP
- tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1,
- self.pg0.remote_mac,
- self.session_id)
+ tx1 = self.create_stream_pppoe_lcp(
+ self.pg0, self.pg1, self.pg0.remote_mac, self.session_id
+ )
self.pg0.add_stream(tx1)
self.pg_start()
# Create PPPoE session
- pppoe_if = VppPppoeInterface(self,
- self.pg0.remote_ip4,
- self.pg0.remote_mac,
- self.session_id)
+ pppoe_if = VppPppoeInterface(
+ self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id
+ )
pppoe_if.add_vpp_config()
pppoe_if.set_unnumbered(self.pg0.sw_if_index)
@@ -282,8 +298,9 @@ class TestPPPoE(VppTestCase):
# - packets are PPPoE encapped
#
self.vapi.cli("clear trace")
- tx2 = self.create_stream_ip4(self.pg1, self.pg0,
- self.pg0.remote_ip4, self.dst_ip, 65)
+ tx2 = self.create_stream_ip4(
+ self.pg1, self.pg0, self.pg0.remote_ip4, self.dst_ip, 65
+ )
self.pg1.add_stream(tx2)
self.pg_enable_capture(self.pg_interfaces)
@@ -308,36 +325,39 @@ class TestPPPoE(VppTestCase):
route_sever_dst.remove_vpp_config()
def test_PPPoE_Add_Twice(self):
- """ PPPoE Add Same Session Twice Test """
+ """PPPoE Add Same Session Twice Test"""
self.vapi.cli("clear trace")
#
# Add a route that resolves the server's destination
#
- route_sever_dst = VppIpRoute(self, "100.1.1.100", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_sever_dst = VppIpRoute(
+ self,
+ "100.1.1.100",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_sever_dst.add_vpp_config()
# Send PPPoE Discovery
- tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1,
- self.pg0.remote_mac)
+ tx0 = self.create_stream_pppoe_discovery(
+ self.pg0, self.pg1, self.pg0.remote_mac
+ )
self.pg0.add_stream(tx0)
self.pg_start()
# Send PPPoE PPP LCP
- tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1,
- self.pg0.remote_mac,
- self.session_id)
+ tx1 = self.create_stream_pppoe_lcp(
+ self.pg0, self.pg1, self.pg0.remote_mac, self.session_id
+ )
self.pg0.add_stream(tx1)
self.pg_start()
# Create PPPoE session
- pppoe_if = VppPppoeInterface(self,
- self.pg0.remote_ip4,
- self.pg0.remote_mac,
- self.session_id)
+ pppoe_if = VppPppoeInterface(
+ self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id
+ )
pppoe_if.add_vpp_config()
pppoe_if.set_unnumbered(self.pg0.sw_if_index)
@@ -363,36 +383,39 @@ class TestPPPoE(VppTestCase):
route_sever_dst.remove_vpp_config()
def test_PPPoE_Del_Twice(self):
- """ PPPoE Delete Same Session Twice Test """
+ """PPPoE Delete Same Session Twice Test"""
self.vapi.cli("clear trace")
#
# Add a route that resolves the server's destination
#
- route_sever_dst = VppIpRoute(self, "100.1.1.100", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_sever_dst = VppIpRoute(
+ self,
+ "100.1.1.100",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_sever_dst.add_vpp_config()
# Send PPPoE Discovery
- tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1,
- self.pg0.remote_mac)
+ tx0 = self.create_stream_pppoe_discovery(
+ self.pg0, self.pg1, self.pg0.remote_mac
+ )
self.pg0.add_stream(tx0)
self.pg_start()
# Send PPPoE PPP LCP
- tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1,
- self.pg0.remote_mac,
- self.session_id)
+ tx1 = self.create_stream_pppoe_lcp(
+ self.pg0, self.pg1, self.pg0.remote_mac, self.session_id
+ )
self.pg0.add_stream(tx1)
self.pg_start()
# Create PPPoE session
- pppoe_if = VppPppoeInterface(self,
- self.pg0.remote_ip4,
- self.pg0.remote_mac,
- self.session_id)
+ pppoe_if = VppPppoeInterface(
+ self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id
+ )
pppoe_if.add_vpp_config()
# Delete PPPoE session
@@ -417,57 +440,60 @@ class TestPPPoE(VppTestCase):
route_sever_dst.remove_vpp_config()
def test_PPPoE_Decap_Multiple(self):
- """ PPPoE Decap Multiple Sessions Test """
+ """PPPoE Decap Multiple Sessions Test"""
self.vapi.cli("clear trace")
#
# Add a route that resolves the server's destination
#
- route_sever_dst = VppIpRoute(self, "100.1.1.100", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_sever_dst = VppIpRoute(
+ self,
+ "100.1.1.100",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_sever_dst.add_vpp_config()
# Send PPPoE Discovery 1
- tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1,
- self.pg0.remote_mac)
+ tx0 = self.create_stream_pppoe_discovery(
+ self.pg0, self.pg1, self.pg0.remote_mac
+ )
self.pg0.add_stream(tx0)
self.pg_start()
# Send PPPoE PPP LCP 1
- tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1,
- self.pg0.remote_mac,
- self.session_id)
+ tx1 = self.create_stream_pppoe_lcp(
+ self.pg0, self.pg1, self.pg0.remote_mac, self.session_id
+ )
self.pg0.add_stream(tx1)
self.pg_start()
# Create PPPoE session 1
- pppoe_if1 = VppPppoeInterface(self,
- self.pg0.remote_ip4,
- self.pg0.remote_mac,
- self.session_id)
+ pppoe_if1 = VppPppoeInterface(
+ self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id
+ )
pppoe_if1.add_vpp_config()
pppoe_if1.set_unnumbered(self.pg0.sw_if_index)
# Send PPPoE Discovery 2
- tx3 = self.create_stream_pppoe_discovery(self.pg2, self.pg1,
- self.pg2.remote_mac)
+ tx3 = self.create_stream_pppoe_discovery(
+ self.pg2, self.pg1, self.pg2.remote_mac
+ )
self.pg2.add_stream(tx3)
self.pg_start()
# Send PPPoE PPP LCP 2
- tx4 = self.create_stream_pppoe_lcp(self.pg2, self.pg1,
- self.pg2.remote_mac,
- self.session_id + 1)
+ tx4 = self.create_stream_pppoe_lcp(
+ self.pg2, self.pg1, self.pg2.remote_mac, self.session_id + 1
+ )
self.pg2.add_stream(tx4)
self.pg_start()
# Create PPPoE session 2
- pppoe_if2 = VppPppoeInterface(self,
- self.pg2.remote_ip4,
- self.pg2.remote_mac,
- self.session_id + 1)
+ pppoe_if2 = VppPppoeInterface(
+ self, self.pg2.remote_ip4, self.pg2.remote_mac, self.session_id + 1
+ )
pppoe_if2.add_vpp_config()
pppoe_if2.set_unnumbered(self.pg0.sw_if_index)
@@ -475,10 +501,13 @@ class TestPPPoE(VppTestCase):
# Send tunneled packets that match the created tunnel and
# are decapped and forwarded
#
- tx2 = self.create_stream_pppoe_ip4(self.pg0, self.pg1,
- self.pg0.remote_mac,
- self.session_id,
- self.pg0.remote_ip4)
+ tx2 = self.create_stream_pppoe_ip4(
+ self.pg0,
+ self.pg1,
+ self.pg0.remote_mac,
+ self.session_id,
+ self.pg0.remote_ip4,
+ )
self.pg0.add_stream(tx2)
self.pg_enable_capture(self.pg_interfaces)
@@ -487,10 +516,13 @@ class TestPPPoE(VppTestCase):
rx2 = self.pg1.get_capture(len(tx2))
self.verify_decapped_pppoe(self.pg0, rx2, tx2)
- tx5 = self.create_stream_pppoe_ip4(self.pg2, self.pg1,
- self.pg2.remote_mac,
- self.session_id + 1,
- self.pg2.remote_ip4)
+ tx5 = self.create_stream_pppoe_ip4(
+ self.pg2,
+ self.pg1,
+ self.pg2.remote_mac,
+ self.session_id + 1,
+ self.pg2.remote_ip4,
+ )
self.pg2.add_stream(tx5)
self.pg_enable_capture(self.pg_interfaces)
@@ -515,56 +547,59 @@ class TestPPPoE(VppTestCase):
route_sever_dst.remove_vpp_config()
def test_PPPoE_Encap_Multiple(self):
- """ PPPoE Encap Multiple Sessions Test """
+ """PPPoE Encap Multiple Sessions Test"""
self.vapi.cli("clear trace")
#
# Add a route that resolves the server's destination
#
- route_sever_dst = VppIpRoute(self, "100.1.1.100", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_sever_dst = VppIpRoute(
+ self,
+ "100.1.1.100",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_sever_dst.add_vpp_config()
# Send PPPoE Discovery 1
- tx0 = self.create_stream_pppoe_discovery(self.pg0, self.pg1,
- self.pg0.remote_mac)
+ tx0 = self.create_stream_pppoe_discovery(
+ self.pg0, self.pg1, self.pg0.remote_mac
+ )
self.pg0.add_stream(tx0)
self.pg_start()
# Send PPPoE PPP LCP 1
- tx1 = self.create_stream_pppoe_lcp(self.pg0, self.pg1,
- self.pg0.remote_mac,
- self.session_id)
+ tx1 = self.create_stream_pppoe_lcp(
+ self.pg0, self.pg1, self.pg0.remote_mac, self.session_id
+ )
self.pg0.add_stream(tx1)
self.pg_start()
# Create PPPoE session 1
- pppoe_if1 = VppPppoeInterface(self,
- self.pg0.remote_ip4,
- self.pg0.remote_mac,
- self.session_id)
+ pppoe_if1 = VppPppoeInterface(
+ self, self.pg0.remote_ip4, self.pg0.remote_mac, self.session_id
+ )
pppoe_if1.add_vpp_config()
# Send PPPoE Discovery 2
- tx3 = self.create_stream_pppoe_discovery(self.pg2, self.pg1,
- self.pg2.remote_mac)
+ tx3 = self.create_stream_pppoe_discovery(
+ self.pg2, self.pg1, self.pg2.remote_mac
+ )
self.pg2.add_stream(tx3)
self.pg_start()
# Send PPPoE PPP LCP 2
- tx4 = self.create_stream_pppoe_lcp(self.pg2, self.pg1,
- self.pg2.remote_mac,
- self.session_id + 1)
+ tx4 = self.create_stream_pppoe_lcp(
+ self.pg2, self.pg1, self.pg2.remote_mac, self.session_id + 1
+ )
self.pg2.add_stream(tx4)
self.pg_start()
# Create PPPoE session 2
- pppoe_if2 = VppPppoeInterface(self,
- self.pg2.remote_ip4,
- self.pg2.remote_mac,
- self.session_id + 1)
+ pppoe_if2 = VppPppoeInterface(
+ self, self.pg2.remote_ip4, self.pg2.remote_mac, self.session_id + 1
+ )
pppoe_if2.add_vpp_config()
#
@@ -572,8 +607,9 @@ class TestPPPoE(VppTestCase):
# - packets are PPPoE encapped
#
self.vapi.cli("clear trace")
- tx2 = self.create_stream_ip4(self.pg1, self.pg0,
- self.pg0.remote_ip4, self.dst_ip)
+ tx2 = self.create_stream_ip4(
+ self.pg1, self.pg0, self.pg0.remote_ip4, self.dst_ip
+ )
self.pg1.add_stream(tx2)
self.pg_enable_capture(self.pg_interfaces)
@@ -582,8 +618,9 @@ class TestPPPoE(VppTestCase):
rx2 = self.pg0.get_capture(len(tx2))
self.verify_encaped_pppoe(self.pg1, rx2, tx2, self.session_id)
- tx5 = self.create_stream_ip4(self.pg1, self.pg2,
- self.pg2.remote_ip4, self.dst_ip)
+ tx5 = self.create_stream_ip4(
+ self.pg1, self.pg2, self.pg2.remote_ip4, self.dst_ip
+ )
self.pg1.add_stream(tx5)
self.pg_enable_capture(self.pg_interfaces)
@@ -607,5 +644,6 @@ class TestPPPoE(VppTestCase):
# Delete a route that resolves the server's destination
route_sever_dst.remove_vpp_config()
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_punt.py b/test/test_punt.py
index ac059e904bd..f33ab4ce3d5 100644
--- a/test/test_punt.py
+++ b/test/test_punt.py
@@ -38,7 +38,7 @@ NUM_PKTS = 67
class serverSocketThread(threading.Thread):
- """ Socket server thread"""
+ """Socket server thread"""
def __init__(self, threadID, sockName):
threading.Thread.__init__(self)
@@ -90,7 +90,7 @@ class serverSocketThread(threading.Thread):
class TestPuntSocket(VppTestCase):
- """ Punt Socket """
+ """Punt Socket"""
ports = [1111, 2222, 3333, 4444]
sock_servers = list()
@@ -109,7 +109,12 @@ class TestPuntSocket(VppTestCase):
@classmethod
def setUpConstants(cls):
cls.extra_vpp_punt_config = [
- "punt", "{", "socket", cls.tempdir+"/socket_punt", "}"]
+ "punt",
+ "{",
+ "socket",
+ cls.tempdir + "/socket_punt",
+ "}",
+ ]
super(TestPuntSocket, cls).setUpConstants()
def setUp(self):
@@ -137,25 +142,21 @@ class TestPuntSocket(VppTestCase):
return rx_pkts
def verify_port(self, pr, vpr):
- self.assertEqual(vpr.punt.type, pr['type'])
- self.assertEqual(vpr.punt.punt.l4.port,
- pr['punt']['l4']['port'])
- self.assertEqual(vpr.punt.punt.l4.protocol,
- pr['punt']['l4']['protocol'])
- self.assertEqual(vpr.punt.punt.l4.af,
- pr['punt']['l4']['af'])
+ self.assertEqual(vpr.punt.type, pr["type"])
+ self.assertEqual(vpr.punt.punt.l4.port, pr["punt"]["l4"]["port"])
+ self.assertEqual(vpr.punt.punt.l4.protocol, pr["punt"]["l4"]["protocol"])
+ self.assertEqual(vpr.punt.punt.l4.af, pr["punt"]["l4"]["af"])
def verify_exception(self, pr, vpr):
- self.assertEqual(vpr.punt.type, pr['type'])
- self.assertEqual(vpr.punt.punt.exception.id,
- pr['punt']['exception']['id'])
+ self.assertEqual(vpr.punt.type, pr["type"])
+ self.assertEqual(vpr.punt.punt.exception.id, pr["punt"]["exception"]["id"])
def verify_ip_proto(self, pr, vpr):
- self.assertEqual(vpr.punt.type, pr['type'])
- self.assertEqual(vpr.punt.punt.ip_proto.af,
- pr['punt']['ip_proto']['af'])
- self.assertEqual(vpr.punt.punt.ip_proto.protocol,
- pr['punt']['ip_proto']['protocol'])
+ self.assertEqual(vpr.punt.type, pr["type"])
+ self.assertEqual(vpr.punt.punt.ip_proto.af, pr["punt"]["ip_proto"]["af"])
+ self.assertEqual(
+ vpr.punt.punt.ip_proto.protocol, pr["punt"]["ip_proto"]["protocol"]
+ )
def verify_udp_pkts(self, rxs, n_rx, port):
n_match = 0
@@ -167,12 +168,12 @@ class TestPuntSocket(VppTestCase):
def set_port(pr, port):
- pr['punt']['l4']['port'] = port
+ pr["punt"]["l4"]["port"] = port
return pr
def set_reason(pr, reason):
- pr['punt']['exception']['id'] = reason
+ pr["punt"]["exception"]["id"] = reason
return pr
@@ -180,15 +181,7 @@ def mk_vpp_cfg4():
pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4
af_ip4 = VppEnum.vl_api_address_family_t.ADDRESS_IP4
udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP
- punt_l4 = {
- 'type': pt_l4,
- 'punt': {
- 'l4': {
- 'af': af_ip4,
- 'protocol': udp_proto
- }
- }
- }
+ punt_l4 = {"type": pt_l4, "punt": {"l4": {"af": af_ip4, "protocol": udp_proto}}}
return punt_l4
@@ -196,20 +189,12 @@ def mk_vpp_cfg6():
pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4
af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6
udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP
- punt_l4 = {
- 'type': pt_l4,
- 'punt': {
- 'l4': {
- 'af': af_ip6,
- 'protocol': udp_proto
- }
- }
- }
+ punt_l4 = {"type": pt_l4, "punt": {"l4": {"af": af_ip6, "protocol": udp_proto}}}
return punt_l4
class TestIP4PuntSocket(TestPuntSocket):
- """ Punt Socket for IPv4 UDP """
+ """Punt Socket for IPv4 UDP"""
@classmethod
def setUpClass(cls):
@@ -233,7 +218,7 @@ class TestIP4PuntSocket(TestPuntSocket):
i.admin_down()
def test_punt_socket_dump(self):
- """ Punt socket registration/deregistration"""
+ """Punt socket registration/deregistration"""
pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4
af_ip4 = VppEnum.vl_api_address_family_t.ADDRESS_IP4
@@ -247,10 +232,12 @@ class TestIP4PuntSocket(TestPuntSocket):
#
punt_l4 = mk_vpp_cfg4()
- self.vapi.punt_socket_register(set_port(punt_l4, 1111),
- "%s/socket_punt_1111" % self.tempdir)
- self.vapi.punt_socket_register(set_port(punt_l4, 2222),
- "%s/socket_punt_2222" % self.tempdir)
+ self.vapi.punt_socket_register(
+ set_port(punt_l4, 1111), "%s/socket_punt_1111" % self.tempdir
+ )
+ self.vapi.punt_socket_register(
+ set_port(punt_l4, 2222), "%s/socket_punt_2222" % self.tempdir
+ )
punts = self.vapi.punt_socket_dump(type=pt_l4)
self.assertEqual(len(punts), 2)
self.verify_port(set_port(punt_l4, 1111), punts[0])
@@ -266,10 +253,12 @@ class TestIP4PuntSocket(TestPuntSocket):
#
# configure a punt socket again
#
- self.vapi.punt_socket_register(set_port(punt_l4, 1111),
- "%s/socket_punt_1111" % self.tempdir)
- self.vapi.punt_socket_register(set_port(punt_l4, 3333),
- "%s/socket_punt_3333" % self.tempdir)
+ self.vapi.punt_socket_register(
+ set_port(punt_l4, 1111), "%s/socket_punt_1111" % self.tempdir
+ )
+ self.vapi.punt_socket_register(
+ set_port(punt_l4, 3333), "%s/socket_punt_3333" % self.tempdir
+ )
punts = self.vapi.punt_socket_dump(type=pt_l4)
self.assertEqual(len(punts), 3)
@@ -285,17 +274,18 @@ class TestIP4PuntSocket(TestPuntSocket):
self.assertEqual(len(punts), 0)
def test_punt_socket_traffic_single_port_single_socket(self):
- """ Punt socket traffic single port single socket"""
+ """Punt socket traffic single port single socket"""
port = self.ports[0]
pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4
punt_l4 = set_port(mk_vpp_cfg4(), port)
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=9876, dport=port) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=9876, dport=port)
+ / Raw(b"\xa5" * 100)
+ )
pkts = p * self.nr_packets
@@ -308,15 +298,14 @@ class TestIP4PuntSocket(TestPuntSocket):
rx = self.send_and_expect_some(self.pg0, pkts, self.pg0)
for p in rx:
- self.assertEqual(int(p[IP].proto), 1) # ICMP
+ self.assertEqual(int(p[IP].proto), 1) # ICMP
self.assertEqual(int(p[ICMP].code), 3) # unreachable
#
# configure a punt socket
#
self.socket_client_create("%s/socket_%d" % (self.tempdir, port))
- self.vapi.punt_socket_register(punt_l4, "%s/socket_%d" %
- (self.tempdir, port))
+ self.vapi.punt_socket_register(punt_l4, "%s/socket_%d" % (self.tempdir, port))
punts = self.vapi.punt_socket_dump(type=pt_l4)
self.assertEqual(len(punts), 1)
@@ -336,11 +325,11 @@ class TestIP4PuntSocket(TestPuntSocket):
rx = self.send_and_expect_some(self.pg0, pkts, self.pg0)
for p in rx:
- self.assertEqual(int(p[IP].proto), 1) # ICMP
+ self.assertEqual(int(p[IP].proto), 1) # ICMP
self.assertEqual(int(p[ICMP].code), 3) # unreachable
def test_punt_socket_traffic_multi_ports_multi_sockets(self):
- """ Punt socket traffic multi ports and multi sockets"""
+ """Punt socket traffic multi ports and multi sockets"""
punt_l4 = mk_vpp_cfg4()
@@ -354,38 +343,40 @@ class TestIP4PuntSocket(TestPuntSocket):
# choose port from port list
cfgs[port] = {}
- pkt = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=9876, dport=port) /
- Raw(b'\xa5' * 100))
- cfgs[port]['pkts'] = pkt * self.nr_packets
- cfgs[port]['port'] = port
- cfgs[port]['vpp'] = copy.deepcopy(set_port(punt_l4, port))
+ pkt = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=9876, dport=port)
+ / Raw(b"\xa5" * 100)
+ )
+ cfgs[port]["pkts"] = pkt * self.nr_packets
+ cfgs[port]["port"] = port
+ cfgs[port]["vpp"] = copy.deepcopy(set_port(punt_l4, port))
# configure punt sockets
- cfgs[port]['sock'] = self.socket_client_create(
- "%s/socket_%d" % (self.tempdir, port))
+ cfgs[port]["sock"] = self.socket_client_create(
+ "%s/socket_%d" % (self.tempdir, port)
+ )
self.vapi.punt_socket_register(
- cfgs[port]['vpp'],
- "%s/socket_%d" % (self.tempdir, port))
+ cfgs[port]["vpp"], "%s/socket_%d" % (self.tempdir, port)
+ )
#
# send the packets that get punted
#
for cfg in cfgs.values():
- self.send_and_assert_no_replies(self.pg0, cfg['pkts'])
+ self.send_and_assert_no_replies(self.pg0, cfg["pkts"])
#
# test that we got the excepted packets on the expected socket
#
for cfg in cfgs.values():
- rx = cfg['sock'].close()
- self.verify_udp_pkts(rx, len(cfg['pkts']), cfg['port'])
- self.vapi.punt_socket_deregister(cfg['vpp'])
+ rx = cfg["sock"].close()
+ self.verify_udp_pkts(rx, len(cfg["pkts"]), cfg["port"])
+ self.vapi.punt_socket_deregister(cfg["vpp"])
def test_punt_socket_traffic_multi_ports_single_socket(self):
- """ Punt socket traffic multi ports and single socket"""
+ """Punt socket traffic multi ports and single socket"""
pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4
punt_l4 = mk_vpp_cfg4()
@@ -396,11 +387,12 @@ class TestIP4PuntSocket(TestPuntSocket):
pkts = []
for port in self.ports:
# choose port from port list
- pkt = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=9876, dport=port) /
- Raw(b'\xa5' * 100))
+ pkt = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=9876, dport=port)
+ / Raw(b"\xa5" * 100)
+ )
pkts += pkt * self.nr_packets
#
@@ -408,8 +400,9 @@ class TestIP4PuntSocket(TestPuntSocket):
#
self.socket_client_create("%s/socket_multi" % self.tempdir)
for p in self.ports:
- self.vapi.punt_socket_register(set_port(punt_l4, p),
- "%s/socket_multi" % self.tempdir)
+ self.vapi.punt_socket_register(
+ set_port(punt_l4, p), "%s/socket_multi" % self.tempdir
+ )
punts = self.vapi.punt_socket_dump(type=pt_l4)
self.assertEqual(len(punts), len(self.ports))
@@ -428,7 +421,7 @@ class TestIP4PuntSocket(TestPuntSocket):
class TestIP6PuntSocket(TestPuntSocket):
- """ Punt Socket for IPv6 UDP """
+ """Punt Socket for IPv6 UDP"""
@classmethod
def setUpClass(cls):
@@ -452,7 +445,7 @@ class TestIP6PuntSocket(TestPuntSocket):
i.admin_down()
def test_punt_socket_dump(self):
- """ Punt socket registration """
+ """Punt socket registration"""
pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4
af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6
@@ -460,15 +453,7 @@ class TestIP6PuntSocket(TestPuntSocket):
#
# configure a punt socket
#
- punt_l4 = {
- 'type': pt_l4,
- 'punt': {
- 'l4': {
- 'af': af_ip6,
- 'protocol': udp_proto
- }
- }
- }
+ punt_l4 = {"type": pt_l4, "punt": {"l4": {"af": af_ip6, "protocol": udp_proto}}}
punts = self.vapi.punt_socket_dump(type=pt_l4)
self.assertEqual(len(punts), 0)
@@ -476,10 +461,12 @@ class TestIP6PuntSocket(TestPuntSocket):
#
# configure a punt socket
#
- self.vapi.punt_socket_register(set_port(punt_l4, 1111),
- "%s/socket_1111" % self.tempdir)
- self.vapi.punt_socket_register(set_port(punt_l4, 2222),
- "%s/socket_2222" % self.tempdir)
+ self.vapi.punt_socket_register(
+ set_port(punt_l4, 1111), "%s/socket_1111" % self.tempdir
+ )
+ self.vapi.punt_socket_register(
+ set_port(punt_l4, 2222), "%s/socket_2222" % self.tempdir
+ )
punts = self.vapi.punt_socket_dump(type=pt_l4)
self.assertEqual(len(punts), 2)
self.verify_port(set_port(punt_l4, 1111), punts[0])
@@ -495,8 +482,9 @@ class TestIP6PuntSocket(TestPuntSocket):
#
# configure a punt socket again
#
- self.vapi.punt_socket_register(set_port(punt_l4, 1111),
- "%s/socket_1111" % self.tempdir)
+ self.vapi.punt_socket_register(
+ set_port(punt_l4, 1111), "%s/socket_1111" % self.tempdir
+ )
punts = self.vapi.punt_socket_dump(type=pt_l4)
self.assertEqual(len(punts), 2)
@@ -510,28 +498,29 @@ class TestIP6PuntSocket(TestPuntSocket):
self.assertEqual(len(punts), 0)
def test_punt_socket_traffic_single_port_single_socket(self):
- """ Punt socket traffic single port single socket"""
+ """Punt socket traffic single port single socket"""
port = self.ports[0]
pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4
af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6
udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP
punt_l4 = {
- 'type': pt_l4,
- 'punt': {
- 'l4': {
- 'af': af_ip6,
- 'protocol': udp_proto,
- 'port': port,
+ "type": pt_l4,
+ "punt": {
+ "l4": {
+ "af": af_ip6,
+ "protocol": udp_proto,
+ "port": port,
}
- }
+ },
}
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- inet6.UDP(sport=9876, dport=port) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / inet6.UDP(sport=9876, dport=port)
+ / Raw(b"\xa5" * 100)
+ )
pkts = p * self.nr_packets
@@ -555,8 +544,7 @@ class TestIP6PuntSocket(TestPuntSocket):
# configure a punt socket
#
self.socket_client_create("%s/socket_%d" % (self.tempdir, port))
- self.vapi.punt_socket_register(punt_l4, "%s/socket_%d" %
- (self.tempdir, port))
+ self.vapi.punt_socket_register(punt_l4, "%s/socket_%d" % (self.tempdir, port))
punts = self.vapi.punt_socket_dump(type=pt_l4)
self.assertEqual(len(punts), 1)
@@ -586,7 +574,7 @@ class TestIP6PuntSocket(TestPuntSocket):
# self.pg0.get_capture(nr_packets)
def test_punt_socket_traffic_multi_ports_multi_sockets(self):
- """ Punt socket traffic multi ports and multi sockets"""
+ """Punt socket traffic multi ports and multi sockets"""
punt_l4 = mk_vpp_cfg6()
@@ -600,50 +588,52 @@ class TestIP6PuntSocket(TestPuntSocket):
# choose port from port list
cfgs[port] = {}
- pkt = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- UDP(sport=9876, dport=port) /
- Raw(b'\xa5' * 100))
- cfgs[port]['pkts'] = pkt * self.nr_packets
- cfgs[port]['port'] = port
- cfgs[port]['vpp'] = copy.deepcopy(set_port(punt_l4, port))
+ pkt = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / UDP(sport=9876, dport=port)
+ / Raw(b"\xa5" * 100)
+ )
+ cfgs[port]["pkts"] = pkt * self.nr_packets
+ cfgs[port]["port"] = port
+ cfgs[port]["vpp"] = copy.deepcopy(set_port(punt_l4, port))
# configure punt sockets
- cfgs[port]['sock'] = self.socket_client_create(
- "%s/socket_%d" % (self.tempdir, port))
+ cfgs[port]["sock"] = self.socket_client_create(
+ "%s/socket_%d" % (self.tempdir, port)
+ )
self.vapi.punt_socket_register(
- cfgs[port]['vpp'],
- "%s/socket_%d" % (self.tempdir, port))
+ cfgs[port]["vpp"], "%s/socket_%d" % (self.tempdir, port)
+ )
#
# send the packets that get punted
#
for cfg in cfgs.values():
- self.send_and_assert_no_replies(self.pg0, cfg['pkts'])
+ self.send_and_assert_no_replies(self.pg0, cfg["pkts"])
#
# test that we got the excepted packets on the expected socket
#
for cfg in cfgs.values():
- rx = cfg['sock'].close()
- self.verify_udp_pkts(rx, len(cfg['pkts']), cfg['port'])
- self.vapi.punt_socket_deregister(cfg['vpp'])
+ rx = cfg["sock"].close()
+ self.verify_udp_pkts(rx, len(cfg["pkts"]), cfg["port"])
+ self.vapi.punt_socket_deregister(cfg["vpp"])
def test_punt_socket_traffic_multi_ports_single_socket(self):
- """ Punt socket traffic multi ports and single socket"""
+ """Punt socket traffic multi ports and single socket"""
pt_l4 = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_L4
af_ip6 = VppEnum.vl_api_address_family_t.ADDRESS_IP6
udp_proto = VppEnum.vl_api_ip_proto_t.IP_API_PROTO_UDP
punt_l4 = {
- 'type': pt_l4,
- 'punt': {
- 'l4': {
- 'af': af_ip6,
- 'protocol': udp_proto,
+ "type": pt_l4,
+ "punt": {
+ "l4": {
+ "af": af_ip6,
+ "protocol": udp_proto,
}
- }
+ },
}
#
@@ -652,11 +642,12 @@ class TestIP6PuntSocket(TestPuntSocket):
pkts = []
for port in self.ports:
# choose port from port list
- pkt = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- UDP(sport=9876, dport=port) /
- Raw(b'\xa5' * 100))
+ pkt = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / UDP(sport=9876, dport=port)
+ / Raw(b"\xa5" * 100)
+ )
pkts += pkt * self.nr_packets
#
@@ -670,8 +661,9 @@ class TestIP6PuntSocket(TestPuntSocket):
#
self.socket_client_create("%s/socket_multi" % self.tempdir)
for p in self.ports:
- self.vapi.punt_socket_register(set_port(punt_l4, p),
- "%s/socket_multi" % self.tempdir)
+ self.vapi.punt_socket_register(
+ set_port(punt_l4, p), "%s/socket_multi" % self.tempdir
+ )
punts = self.vapi.punt_socket_dump(type=pt_l4)
self.assertEqual(len(punts), len(self.ports))
@@ -696,7 +688,7 @@ class TestIP6PuntSocket(TestPuntSocket):
class TestExceptionPuntSocket(TestPuntSocket):
- """ Punt Socket for Exceptions """
+ """Punt Socket for Exceptions"""
@classmethod
def setUpClass(cls):
@@ -721,7 +713,7 @@ class TestExceptionPuntSocket(TestPuntSocket):
i.admin_down()
def test_registration(self):
- """ Punt socket registration/deregistration"""
+ """Punt socket registration/deregistration"""
pt_ex = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_EXCEPTION
@@ -731,17 +723,14 @@ class TestExceptionPuntSocket(TestPuntSocket):
#
# configure a punt socket
#
- punt_ex = {
- 'type': pt_ex,
- 'punt': {
- 'exception': {}
- }
- }
+ punt_ex = {"type": pt_ex, "punt": {"exception": {}}}
- self.vapi.punt_socket_register(set_reason(punt_ex, 1),
- "%s/socket_punt_1" % self.tempdir)
- self.vapi.punt_socket_register(set_reason(punt_ex, 2),
- "%s/socket_punt_2" % self.tempdir)
+ self.vapi.punt_socket_register(
+ set_reason(punt_ex, 1), "%s/socket_punt_1" % self.tempdir
+ )
+ self.vapi.punt_socket_register(
+ set_reason(punt_ex, 2), "%s/socket_punt_2" % self.tempdir
+ )
punts = self.vapi.punt_socket_dump(type=pt_ex)
self.assertEqual(len(punts), 2)
self.verify_exception(set_reason(punt_ex, 1), punts[0])
@@ -757,10 +746,12 @@ class TestExceptionPuntSocket(TestPuntSocket):
#
# configure a punt socket again
#
- self.vapi.punt_socket_register(set_reason(punt_ex, 1),
- "%s/socket_punt_1" % self.tempdir)
- self.vapi.punt_socket_register(set_reason(punt_ex, 3),
- "%s/socket_punt_3" % self.tempdir)
+ self.vapi.punt_socket_register(
+ set_reason(punt_ex, 1), "%s/socket_punt_1" % self.tempdir
+ )
+ self.vapi.punt_socket_register(
+ set_reason(punt_ex, 3), "%s/socket_punt_3" % self.tempdir
+ )
punts = self.vapi.punt_socket_dump(type=pt_ex)
self.assertEqual(len(punts), 3)
@@ -785,25 +776,18 @@ class TestExceptionPuntSocket(TestPuntSocket):
self.assertTrue(rx.haslayer(UDP))
def test_traffic(self):
- """ Punt socket traffic """
+ """Punt socket traffic"""
port = self.ports[0]
pt_ex = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_EXCEPTION
- punt_ex = {
- 'type': pt_ex,
- 'punt': {
- 'exception': {}
- }
- }
+ punt_ex = {"type": pt_ex, "punt": {"exception": {}}}
#
# we're dealing with IPSec tunnels punting for no-such-tunnel
# (SPI=0 goes to ikev2)
#
cfgs = dict()
- cfgs['ipsec4-no-such-tunnel'] = {'spi': 99,
- 'udp': False,
- 'itf': self.pg0}
+ cfgs["ipsec4-no-such-tunnel"] = {"spi": 99, "udp": False, "itf": self.pg0}
#
# find the VPP ID for these punt exception reasin
@@ -814,99 +798,99 @@ class TestExceptionPuntSocket(TestPuntSocket):
print(r.reason.name)
print(key)
if r.reason.name == key:
- cfgs[key]['id'] = r.reason.id
- cfgs[key]['vpp'] = copy.deepcopy(
- set_reason(punt_ex,
- cfgs[key]['id']))
+ cfgs[key]["id"] = r.reason.id
+ cfgs[key]["vpp"] = copy.deepcopy(
+ set_reason(punt_ex, cfgs[key]["id"])
+ )
break
#
# configure punt sockets
#
for cfg in cfgs.values():
- cfg['sock'] = self.socket_client_create("%s/socket_%d" %
- (self.tempdir, cfg['id']))
+ cfg["sock"] = self.socket_client_create(
+ "%s/socket_%d" % (self.tempdir, cfg["id"])
+ )
self.vapi.punt_socket_register(
- cfg['vpp'], "%s/socket_%d" % (self.tempdir, cfg['id']))
+ cfg["vpp"], "%s/socket_%d" % (self.tempdir, cfg["id"])
+ )
#
# create packet streams for 'no-such-tunnel' exception
#
for cfg in cfgs.values():
- pkt = (Ether(src=cfg['itf'].remote_mac,
- dst=cfg['itf'].local_mac) /
- IP(src=cfg['itf'].remote_ip4,
- dst=cfg['itf'].local_ip4))
- if (cfg['udp']):
+ pkt = Ether(src=cfg["itf"].remote_mac, dst=cfg["itf"].local_mac) / IP(
+ src=cfg["itf"].remote_ip4, dst=cfg["itf"].local_ip4
+ )
+ if cfg["udp"]:
pkt = pkt / UDP(sport=666, dport=4500)
- pkt = (pkt / ESP(spi=cfg['spi'], seq=3) /
- Raw(b'\xa5' * 100))
- cfg['pkts'] = [pkt]
+ pkt = pkt / ESP(spi=cfg["spi"], seq=3) / Raw(b"\xa5" * 100)
+ cfg["pkts"] = [pkt]
#
# send packets for each SPI we expect to be punted
#
for cfg in cfgs.values():
- self.send_and_assert_no_replies(cfg['itf'], cfg['pkts'])
+ self.send_and_assert_no_replies(cfg["itf"], cfg["pkts"])
#
# verify the punted packets arrived on the associated socket
#
for cfg in cfgs.values():
- rx = cfg['sock'].close()
- self.verify_esp_pkts(rx, len(cfg['pkts']),
- cfg['spi'], cfg['udp'])
+ rx = cfg["sock"].close()
+ self.verify_esp_pkts(rx, len(cfg["pkts"]), cfg["spi"], cfg["udp"])
#
# add some tunnels, make sure it still punts
#
tun = VppIpsecInterface(self).add_vpp_config()
- sa_in = VppIpsecSA(self, 11, 11,
- (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96),
- b"0123456701234567",
- (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CBC_128),
- b"0123456701234567",
- 50,
- self.pg0.local_ip4,
- self.pg0.remote_ip4).add_vpp_config()
- sa_out = VppIpsecSA(self, 22, 22,
- (VppEnum.vl_api_ipsec_integ_alg_t.
- IPSEC_API_INTEG_ALG_SHA1_96),
- b"0123456701234567",
- (VppEnum.vl_api_ipsec_crypto_alg_t.
- IPSEC_API_CRYPTO_ALG_AES_CBC_128),
- b"0123456701234567",
- 50,
- self.pg0.local_ip4,
- self.pg0.remote_ip4).add_vpp_config()
- protect = VppIpsecTunProtect(self, tun,
- sa_out,
- [sa_in]).add_vpp_config()
+ sa_in = VppIpsecSA(
+ self,
+ 11,
+ 11,
+ (VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96),
+ b"0123456701234567",
+ (VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128),
+ b"0123456701234567",
+ 50,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ ).add_vpp_config()
+ sa_out = VppIpsecSA(
+ self,
+ 22,
+ 22,
+ (VppEnum.vl_api_ipsec_integ_alg_t.IPSEC_API_INTEG_ALG_SHA1_96),
+ b"0123456701234567",
+ (VppEnum.vl_api_ipsec_crypto_alg_t.IPSEC_API_CRYPTO_ALG_AES_CBC_128),
+ b"0123456701234567",
+ 50,
+ self.pg0.local_ip4,
+ self.pg0.remote_ip4,
+ ).add_vpp_config()
+ protect = VppIpsecTunProtect(self, tun, sa_out, [sa_in]).add_vpp_config()
#
# send packets for each SPI we expect to be punted
#
for cfg in cfgs.values():
- self.send_and_assert_no_replies(cfg['itf'], cfg['pkts'])
+ self.send_and_assert_no_replies(cfg["itf"], cfg["pkts"])
#
# verify the punted packets arrived on the associated socket
#
for cfg in cfgs.values():
- rx = cfg['sock'].close()
- self.verify_esp_pkts(rx, len(cfg['pkts']),
- cfg['spi'], cfg['udp'])
+ rx = cfg["sock"].close()
+ self.verify_esp_pkts(rx, len(cfg["pkts"]), cfg["spi"], cfg["udp"])
#
# socket deregister
#
for cfg in cfgs.values():
- self.vapi.punt_socket_deregister(cfg['vpp'])
+ self.vapi.punt_socket_deregister(cfg["vpp"])
class TestIpProtoPuntSocket(TestPuntSocket):
- """ Punt Socket for IP packets """
+ """Punt Socket for IP packets"""
@classmethod
def setUpClass(cls):
@@ -930,7 +914,7 @@ class TestIpProtoPuntSocket(TestPuntSocket):
i.admin_down()
def test_registration(self):
- """ Punt socket registration/deregistration"""
+ """Punt socket registration/deregistration"""
af_ip4 = VppEnum.vl_api_address_family_t.ADDRESS_IP4
pt_ip = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_IP_PROTO
@@ -944,28 +928,16 @@ class TestIpProtoPuntSocket(TestPuntSocket):
# configure a punt socket
#
punt_ospf = {
- 'type': pt_ip,
- 'punt': {
- 'ip_proto': {
- 'af': af_ip4,
- 'protocol': proto_ospf
- }
- }
+ "type": pt_ip,
+ "punt": {"ip_proto": {"af": af_ip4, "protocol": proto_ospf}},
}
punt_eigrp = {
- 'type': pt_ip,
- 'punt': {
- 'ip_proto': {
- 'af': af_ip4,
- 'protocol': proto_eigrp
- }
- }
+ "type": pt_ip,
+ "punt": {"ip_proto": {"af": af_ip4, "protocol": proto_eigrp}},
}
- self.vapi.punt_socket_register(punt_ospf,
- "%s/socket_punt_1" % self.tempdir)
- self.vapi.punt_socket_register(punt_eigrp,
- "%s/socket_punt_2" % self.tempdir)
+ self.vapi.punt_socket_register(punt_ospf, "%s/socket_punt_1" % self.tempdir)
+ self.vapi.punt_socket_register(punt_eigrp, "%s/socket_punt_2" % self.tempdir)
self.logger.info(self.vapi.cli("sh punt sock reg ip"))
punts = self.vapi.punt_socket_dump(type=pt_ip)
self.assertEqual(len(punts), 2)
@@ -982,8 +954,7 @@ class TestIpProtoPuntSocket(TestPuntSocket):
#
# configure a punt socket again
#
- self.vapi.punt_socket_register(punt_ospf,
- "%s/socket_punt_3" % self.tempdir)
+ self.vapi.punt_socket_register(punt_ospf, "%s/socket_punt_3" % self.tempdir)
punts = self.vapi.punt_socket_dump(type=pt_ip)
self.assertEqual(len(punts), 2)
@@ -1003,7 +974,7 @@ class TestIpProtoPuntSocket(TestPuntSocket):
self.assertTrue(rx.haslayer(OSPF_Hdr))
def test_traffic(self):
- """ Punt socket traffic """
+ """Punt socket traffic"""
af_ip4 = VppEnum.vl_api_address_family_t.ADDRESS_IP4
pt_ip = VppEnum.vl_api_punt_type_t.PUNT_API_TYPE_IP_PROTO
@@ -1013,28 +984,23 @@ class TestIpProtoPuntSocket(TestPuntSocket):
# configure a punt socket to capture OSPF packets
#
punt_ospf = {
- 'type': pt_ip,
- 'punt': {
- 'ip_proto': {
- 'af': af_ip4,
- 'protocol': proto_ospf
- }
- }
+ "type": pt_ip,
+ "punt": {"ip_proto": {"af": af_ip4, "protocol": proto_ospf}},
}
#
# create packet streams and configure a punt sockets
#
- pkt = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- OSPF_Hdr() /
- OSPFv3_Hello())
+ pkt = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / OSPF_Hdr()
+ / OSPFv3_Hello()
+ )
pkts = pkt * 7
sock = self.socket_client_create("%s/socket_1" % self.tempdir)
- self.vapi.punt_socket_register(
- punt_ospf, "%s/socket_1" % self.tempdir)
+ self.vapi.punt_socket_register(punt_ospf, "%s/socket_1" % self.tempdir)
#
# send packets for each SPI we expect to be punted
@@ -1051,7 +1017,7 @@ class TestIpProtoPuntSocket(TestPuntSocket):
@tag_fixme_vpp_workers
class TestPunt(VppTestCase):
- """ Exception Punt Test Case """
+ """Exception Punt Test Case"""
@classmethod
def setUpClass(cls):
@@ -1081,7 +1047,7 @@ class TestPunt(VppTestCase):
super(TestPunt, self).tearDown()
def test_punt(self):
- """ Exception Path testing """
+ """Exception Path testing"""
#
# dump the punt registered reasons
@@ -1089,9 +1055,11 @@ class TestPunt(VppTestCase):
#
rs = self.vapi.punt_reason_dump()
- reasons = ["ipsec6-no-such-tunnel",
- "ipsec4-no-such-tunnel",
- "ipsec4-spi-o-udp-0"]
+ reasons = [
+ "ipsec6-no-such-tunnel",
+ "ipsec4-no-such-tunnel",
+ "ipsec4-spi-o-udp-0",
+ ]
for reason in reasons:
found = False
@@ -1106,28 +1074,41 @@ class TestPunt(VppTestCase):
# send ACL deny packets out of pg0 and pg1.
# the ACL is src,dst = 1.1.1.1,1.1.1.2
#
- ip_1_1_1_2 = VppIpRoute(self, "1.1.1.2", 32,
- [VppRoutePath(self.pg3.remote_ip4,
- self.pg3.sw_if_index)])
+ ip_1_1_1_2 = VppIpRoute(
+ self,
+ "1.1.1.2",
+ 32,
+ [VppRoutePath(self.pg3.remote_ip4, self.pg3.sw_if_index)],
+ )
ip_1_1_1_2.add_vpp_config()
- ip_1_2 = VppIpRoute(self, "1::2", 128,
- [VppRoutePath(self.pg3.remote_ip6,
- self.pg3.sw_if_index,
- proto=DpoProto.DPO_PROTO_IP6)])
+ ip_1_2 = VppIpRoute(
+ self,
+ "1::2",
+ 128,
+ [
+ VppRoutePath(
+ self.pg3.remote_ip6,
+ self.pg3.sw_if_index,
+ proto=DpoProto.DPO_PROTO_IP6,
+ )
+ ],
+ )
ip_1_2.add_vpp_config()
- p4 = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src="1.1.1.1", dst="1.1.1.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- p6 = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IPv6(src="1::1", dst="1::2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- self.send_and_expect(self.pg2, p4*1, self.pg3)
- self.send_and_expect(self.pg2, p6*1, self.pg3)
+ p4 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src="1.1.1.1", dst="1.1.1.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ p6 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IPv6(src="1::1", dst="1::2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ self.send_and_expect(self.pg2, p4 * 1, self.pg3)
+ self.send_and_expect(self.pg2, p6 * 1, self.pg3)
#
# apply the punting features
@@ -1137,16 +1118,16 @@ class TestPunt(VppTestCase):
#
# dump the punt reasons to learn the IDs assigned
#
- rs = self.vapi.punt_reason_dump(reason={'name': "reason-v4"})
+ rs = self.vapi.punt_reason_dump(reason={"name": "reason-v4"})
r4 = rs[0].reason.id
- rs = self.vapi.punt_reason_dump(reason={'name': "reason-v6"})
+ rs = self.vapi.punt_reason_dump(reason={"name": "reason-v6"})
r6 = rs[0].reason.id
#
# pkts now dropped
#
- self.send_and_assert_no_replies(self.pg2, p4*NUM_PKTS)
- self.send_and_assert_no_replies(self.pg2, p6*NUM_PKTS)
+ self.send_and_assert_no_replies(self.pg2, p4 * NUM_PKTS)
+ self.send_and_assert_no_replies(self.pg2, p6 * NUM_PKTS)
#
# Check state:
@@ -1154,13 +1135,12 @@ class TestPunt(VppTestCase):
# 2 - per-reason counters
# 2, 3 are the index of the assigned punt reason
#
- stats = self.statistics.get_err_counter(
- "/err/punt-dispatch/No registrations")
- self.assertEqual(stats, 2*NUM_PKTS)
+ stats = self.statistics.get_err_counter("/err/punt-dispatch/No registrations")
+ self.assertEqual(stats, 2 * NUM_PKTS)
stats = self.statistics.get_counter("/net/punt")
- self.assertEqual(stats[0][r4]['packets'], NUM_PKTS)
- self.assertEqual(stats[0][r6]['packets'], NUM_PKTS)
+ self.assertEqual(stats[0][r4]["packets"], NUM_PKTS)
+ self.assertEqual(stats[0][r6]["packets"], NUM_PKTS)
#
# use the test CLI to test a client that punts exception
@@ -1169,8 +1149,8 @@ class TestPunt(VppTestCase):
self.vapi.cli("test punt pg0 %s" % self.pg0.remote_ip4)
self.vapi.cli("test punt pg0 %s" % self.pg0.remote_ip6)
- rx4s = self.send_and_expect(self.pg2, p4*NUM_PKTS, self.pg0)
- rx6s = self.send_and_expect(self.pg2, p6*NUM_PKTS, self.pg0)
+ rx4s = self.send_and_expect(self.pg2, p4 * NUM_PKTS, self.pg0)
+ rx6s = self.send_and_expect(self.pg2, p6 * NUM_PKTS, self.pg0)
#
# check the packets come out IP unmodified but destined to pg0 host
@@ -1187,8 +1167,8 @@ class TestPunt(VppTestCase):
self.assertEqual(p6[IPv6].hlim, rx[IPv6].hlim)
stats = self.statistics.get_counter("/net/punt")
- self.assertEqual(stats[0][r4]['packets'], 2*NUM_PKTS)
- self.assertEqual(stats[0][r6]['packets'], 2*NUM_PKTS)
+ self.assertEqual(stats[0][r4]["packets"], 2 * NUM_PKTS)
+ self.assertEqual(stats[0][r6]["packets"], 2 * NUM_PKTS)
#
# add another registration for the same reason to send packets
@@ -1234,8 +1214,8 @@ class TestPunt(VppTestCase):
self.assertEqual(p6[IPv6].hlim, rx[IPv6].hlim)
stats = self.statistics.get_counter("/net/punt")
- self.assertEqual(stats[0][r4]['packets'], 3*NUM_PKTS)
- self.assertEqual(stats[0][r6]['packets'], 3*NUM_PKTS)
+ self.assertEqual(stats[0][r4]["packets"], 3 * NUM_PKTS)
+ self.assertEqual(stats[0][r6]["packets"], 3 * NUM_PKTS)
self.logger.info(self.vapi.cli("show vlib graph punt-dispatch"))
self.logger.info(self.vapi.cli("show punt client"))
@@ -1244,5 +1224,5 @@ class TestPunt(VppTestCase):
self.logger.info(self.vapi.cli("show punt db"))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_qos.py b/test/test_qos.py
index 02941a163b4..40a3ddea4f5 100644
--- a/test/test_qos.py
+++ b/test/test_qos.py
@@ -5,8 +5,14 @@ import unittest
from framework import VppTestCase, VppTestRunner
from vpp_sub_interface import VppDot1QSubint
from vpp_ip import DpoProto
-from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsRoute, \
- VppMplsLabel, VppMplsTable, FibPathProto
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ VppMplsRoute,
+ VppMplsLabel,
+ VppMplsTable,
+ FibPathProto,
+)
import scapy.compat
from scapy.packet import Raw
@@ -21,7 +27,7 @@ NUM_PKTS = 67
class TestQOS(VppTestCase):
- """ QOS Test Case """
+ """QOS Test Case"""
# Note: Since the enums aren't created dynamically until after
# the papi client attaches to VPP, we put it in a property to
@@ -63,7 +69,7 @@ class TestQOS(VppTestCase):
super(TestQOS, self).tearDown()
def test_qos_ip(self):
- """ QoS Mark/Record/Store IP """
+ """QoS Mark/Record/Store IP"""
#
# for table 1 map the n=0xff possible values of input QoS mark,
@@ -72,11 +78,8 @@ class TestQOS(VppTestCase):
output = [scapy.compat.chb(0)] * 256
for i in range(0, 255):
output[i] = scapy.compat.chb(255 - i)
- os = b''.join(output)
- rows = [{'outputs': os},
- {'outputs': os},
- {'outputs': os},
- {'outputs': os}]
+ os = b"".join(output)
+ rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}]
qem1 = VppQosEgressMap(self, 1, rows).add_vpp_config()
@@ -84,29 +87,20 @@ class TestQOS(VppTestCase):
# For table 2 (and up) use the value n for everything
#
output = [scapy.compat.chb(2)] * 256
- os = b''.join(output)
- rows = [{'outputs': os},
- {'outputs': os},
- {'outputs': os},
- {'outputs': os}]
+ os = b"".join(output)
+ rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}]
qem2 = VppQosEgressMap(self, 2, rows).add_vpp_config()
output = [scapy.compat.chb(3)] * 256
- os = b''.join(output)
- rows = [{'outputs': os},
- {'outputs': os},
- {'outputs': os},
- {'outputs': os}]
+ os = b"".join(output)
+ rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}]
qem3 = VppQosEgressMap(self, 3, rows).add_vpp_config()
output = [scapy.compat.chb(4)] * 256
- os = b''.join(output)
- rows = [{'outputs': os},
- {'outputs': os},
- {'outputs': os},
- {'outputs': os}]
+ os = b"".join(output)
+ rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}]
qem4 = VppQosEgressMap(self, 4, rows).add_vpp_config()
qem5 = VppQosEgressMap(self, 5, rows).add_vpp_config()
@@ -119,14 +113,18 @@ class TestQOS(VppTestCase):
#
# Bind interface pgN to table n
#
- qm1 = VppQosMark(self, self.pg1, qem1,
- self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config()
- qm2 = VppQosMark(self, self.pg2, qem2,
- self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config()
- qm3 = VppQosMark(self, self.pg3, qem3,
- self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config()
- qm4 = VppQosMark(self, self.pg4, qem4,
- self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config()
+ qm1 = VppQosMark(
+ self, self.pg1, qem1, self.QOS_SOURCE.QOS_API_SOURCE_IP
+ ).add_vpp_config()
+ qm2 = VppQosMark(
+ self, self.pg2, qem2, self.QOS_SOURCE.QOS_API_SOURCE_IP
+ ).add_vpp_config()
+ qm3 = VppQosMark(
+ self, self.pg3, qem3, self.QOS_SOURCE.QOS_API_SOURCE_IP
+ ).add_vpp_config()
+ qm4 = VppQosMark(
+ self, self.pg4, qem4, self.QOS_SOURCE.QOS_API_SOURCE_IP
+ ).add_vpp_config()
self.assertTrue(qm3.query_vpp_config())
self.logger.info(self.vapi.cli("sh qos mark"))
@@ -134,15 +132,18 @@ class TestQOS(VppTestCase):
#
# packets ingress on Pg0
#
- p_v4 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, tos=1) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(100) * NUM_PKTS))
- p_v6 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6,
- tc=1) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(100) * NUM_PKTS))
+ p_v4 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4, tos=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(100) * NUM_PKTS)
+ )
+ p_v6 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6, tc=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(100) * NUM_PKTS)
+ )
#
# Since we have not yet enabled the recording of the input QoS
@@ -158,8 +159,7 @@ class TestQOS(VppTestCase):
#
# Enable QoS recording on IP input for pg0
#
- qr1 = VppQosRecord(self, self.pg0,
- self.QOS_SOURCE.QOS_API_SOURCE_IP)
+ qr1 = VppQosRecord(self, self.pg0, self.QOS_SOURCE.QOS_API_SOURCE_IP)
qr1.add_vpp_config()
self.logger.info(self.vapi.cli("sh qos record"))
@@ -258,9 +258,9 @@ class TestQOS(VppTestCase):
#
# enable QoS stroe instead of record
#
- qst1 = VppQosStore(self, self.pg0,
- self.QOS_SOURCE.QOS_API_SOURCE_IP,
- 5).add_vpp_config()
+ qst1 = VppQosStore(
+ self, self.pg0, self.QOS_SOURCE.QOS_API_SOURCE_IP, 5
+ ).add_vpp_config()
self.logger.info(self.vapi.cli("sh qos store"))
p_v4[IP].dst = self.pg1.remote_ip4
@@ -295,7 +295,7 @@ class TestQOS(VppTestCase):
self.assertEqual(p[IP].tos, 254)
def test_qos_mpls(self):
- """ QoS Mark/Record MPLS """
+ """QoS Mark/Record MPLS"""
#
# 255 QoS for all input values
@@ -305,58 +305,69 @@ class TestQOS(VppTestCase):
from_mpls = 5
from_vlan = 4
output = [scapy.compat.chb(from_ext)] * 256
- os1 = b''.join(output)
+ os1 = b"".join(output)
output = [scapy.compat.chb(from_vlan)] * 256
- os2 = b''.join(output)
+ os2 = b"".join(output)
output = [scapy.compat.chb(from_mpls)] * 256
- os3 = b''.join(output)
+ os3 = b"".join(output)
output = [scapy.compat.chb(from_ip)] * 256
- os4 = b''.join(output)
- rows = [{'outputs': os1},
- {'outputs': os2},
- {'outputs': os3},
- {'outputs': os4}]
+ os4 = b"".join(output)
+ rows = [{"outputs": os1}, {"outputs": os2}, {"outputs": os3}, {"outputs": os4}]
qem1 = VppQosEgressMap(self, 1, rows).add_vpp_config()
#
# a route with 1 MPLS label
#
- route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index,
- labels=[32])])
+ route_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index, labels=[32])],
+ )
route_10_0_0_1.add_vpp_config()
#
# a route with 3 MPLS labels
#
- route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index,
- labels=[63, 33, 34])])
+ route_10_0_0_3 = VppIpRoute(
+ self,
+ "10.0.0.3",
+ 32,
+ [
+ VppRoutePath(
+ self.pg1.remote_ip4, self.pg1.sw_if_index, labels=[63, 33, 34]
+ )
+ ],
+ )
route_10_0_0_3.add_vpp_config()
#
# enable IP QoS recording on the input Pg0 and MPLS egress marking
# on Pg1
#
- qr1 = VppQosRecord(self, self.pg0,
- self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config()
- qm1 = VppQosMark(self, self.pg1, qem1,
- self.QOS_SOURCE.QOS_API_SOURCE_MPLS).add_vpp_config()
+ qr1 = VppQosRecord(
+ self, self.pg0, self.QOS_SOURCE.QOS_API_SOURCE_IP
+ ).add_vpp_config()
+ qm1 = VppQosMark(
+ self, self.pg1, qem1, self.QOS_SOURCE.QOS_API_SOURCE_MPLS
+ ).add_vpp_config()
#
# packet that will get one label added and 3 labels added resp.
#
- p_1 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.0.0.1", tos=1) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(100) * NUM_PKTS))
- p_3 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.0.0.3", tos=1) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(100) * NUM_PKTS))
+ p_1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.0.0.1", tos=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(100) * NUM_PKTS)
+ )
+ p_3 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.0.0.3", tos=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(100) * NUM_PKTS)
+ )
rx = self.send_and_expect(self.pg0, p_1 * NUM_PKTS, self.pg1)
@@ -387,26 +398,34 @@ class TestQOS(VppTestCase):
# on Pg1
#
qr2 = VppQosRecord(
- self, self.pg0,
- self.QOS_SOURCE.QOS_API_SOURCE_MPLS).add_vpp_config()
+ self, self.pg0, self.QOS_SOURCE.QOS_API_SOURCE_MPLS
+ ).add_vpp_config()
qm2 = VppQosMark(
- self, self.pg1, qem1,
- self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config()
+ self, self.pg1, qem1, self.QOS_SOURCE.QOS_API_SOURCE_IP
+ ).add_vpp_config()
#
# MPLS x-connect - COS according to pg1 map
#
- route_32_eos = VppMplsRoute(self, 32, 1,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index,
- labels=[VppMplsLabel(33)])])
+ route_32_eos = VppMplsRoute(
+ self,
+ 32,
+ 1,
+ [
+ VppRoutePath(
+ self.pg1.remote_ip4, self.pg1.sw_if_index, labels=[VppMplsLabel(33)]
+ )
+ ],
+ )
route_32_eos.add_vpp_config()
- p_m1 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- MPLS(label=32, cos=3, ttl=2) /
- IP(src=self.pg0.remote_ip4, dst="10.0.0.1", tos=1) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(100) * NUM_PKTS))
+ p_m1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / MPLS(label=32, cos=3, ttl=2)
+ / IP(src=self.pg0.remote_ip4, dst="10.0.0.1", tos=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(100) * NUM_PKTS)
+ )
rx = self.send_and_expect(self.pg0, p_m1 * NUM_PKTS, self.pg1)
for p in rx:
@@ -417,22 +436,26 @@ class TestQOS(VppTestCase):
#
# MPLS deag - COS is copied from MPLS to IP
#
- route_33_eos = VppMplsRoute(self, 33, 1,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=0)])
+ route_33_eos = VppMplsRoute(
+ self, 33, 1, [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)]
+ )
route_33_eos.add_vpp_config()
- route_10_0_0_4 = VppIpRoute(self, "10.0.0.4", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_10_0_0_4 = VppIpRoute(
+ self,
+ "10.0.0.4",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_10_0_0_4.add_vpp_config()
- p_m2 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- MPLS(label=33, ttl=2, cos=3) /
- IP(src=self.pg0.remote_ip4, dst="10.0.0.4", tos=1) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(100) * NUM_PKTS))
+ p_m2 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / MPLS(label=33, ttl=2, cos=3)
+ / IP(src=self.pg0.remote_ip4, dst="10.0.0.4", tos=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(100) * NUM_PKTS)
+ )
rx = self.send_and_expect(self.pg0, p_m2 * NUM_PKTS, self.pg1)
@@ -440,7 +463,7 @@ class TestQOS(VppTestCase):
self.assertEqual(p[IP].tos, from_mpls)
def test_qos_vlan(self):
- """QoS mark/record VLAN """
+ """QoS mark/record VLAN"""
#
# QoS for all input values
@@ -448,11 +471,8 @@ class TestQOS(VppTestCase):
output = [scapy.compat.chb(0)] * 256
for i in range(0, 255):
output[i] = scapy.compat.chb(255 - i)
- os = b''.join(output)
- rows = [{'outputs': os},
- {'outputs': os},
- {'outputs': os},
- {'outputs': os}]
+ os = b"".join(output)
+ rows = [{"outputs": os}, {"outputs": os}, {"outputs": os}, {"outputs": os}]
qem1 = VppQosEgressMap(self, 1, rows).add_vpp_config()
@@ -468,58 +488,70 @@ class TestQOS(VppTestCase):
# enable VLAN QoS recording/marking on the input Pg0 subinterface and
#
qr_v = VppQosRecord(
- self, sub_if,
- self.QOS_SOURCE.QOS_API_SOURCE_VLAN).add_vpp_config()
+ self, sub_if, self.QOS_SOURCE.QOS_API_SOURCE_VLAN
+ ).add_vpp_config()
qm_v = VppQosMark(
- self, sub_if, qem1,
- self.QOS_SOURCE.QOS_API_SOURCE_VLAN).add_vpp_config()
+ self, sub_if, qem1, self.QOS_SOURCE.QOS_API_SOURCE_VLAN
+ ).add_vpp_config()
#
# IP marking/recording on pg1
#
qr_ip = VppQosRecord(
- self, self.pg1,
- self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config()
+ self, self.pg1, self.QOS_SOURCE.QOS_API_SOURCE_IP
+ ).add_vpp_config()
qm_ip = VppQosMark(
- self, self.pg1, qem1,
- self.QOS_SOURCE.QOS_API_SOURCE_IP).add_vpp_config()
+ self, self.pg1, qem1, self.QOS_SOURCE.QOS_API_SOURCE_IP
+ ).add_vpp_config()
#
# a routes to/from sub-interface
#
- route_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- [VppRoutePath(sub_if.remote_ip4,
- sub_if.sw_if_index)])
+ route_10_0_0_1 = VppIpRoute(
+ self, "10.0.0.1", 32, [VppRoutePath(sub_if.remote_ip4, sub_if.sw_if_index)]
+ )
route_10_0_0_1.add_vpp_config()
- route_10_0_0_2 = VppIpRoute(self, "10.0.0.2", 32,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index)])
+ route_10_0_0_2 = VppIpRoute(
+ self,
+ "10.0.0.2",
+ 32,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index)],
+ )
route_10_0_0_2.add_vpp_config()
- route_2001_1 = VppIpRoute(self, "2001::1", 128,
- [VppRoutePath(sub_if.remote_ip6,
- sub_if.sw_if_index)])
+ route_2001_1 = VppIpRoute(
+ self, "2001::1", 128, [VppRoutePath(sub_if.remote_ip6, sub_if.sw_if_index)]
+ )
route_2001_1.add_vpp_config()
- route_2001_2 = VppIpRoute(self, "2001::2", 128,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ route_2001_2 = VppIpRoute(
+ self,
+ "2001::2",
+ 128,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)],
+ )
route_2001_2.add_vpp_config()
- p_v1 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- Dot1Q(vlan=11, prio=1) /
- IP(src="1.1.1.1", dst="10.0.0.2", tos=1) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(100) * NUM_PKTS))
-
- p_v2 = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IP(src="1.1.1.1", dst="10.0.0.1", tos=1) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(100) * NUM_PKTS))
-
- p_v3 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- Dot1Q(vlan=11, prio=1, id=1) /
- IP(src="1.1.1.1", dst="10.0.0.2", tos=2) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(100) * NUM_PKTS))
+ p_v1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / Dot1Q(vlan=11, prio=1)
+ / IP(src="1.1.1.1", dst="10.0.0.2", tos=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(100) * NUM_PKTS)
+ )
+
+ p_v2 = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src="1.1.1.1", dst="10.0.0.1", tos=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(100) * NUM_PKTS)
+ )
+
+ p_v3 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / Dot1Q(vlan=11, prio=1, id=1)
+ / IP(src="1.1.1.1", dst="10.0.0.2", tos=2)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(100) * NUM_PKTS)
+ )
rx = self.send_and_expect(self.pg1, p_v2 * NUM_PKTS, self.pg0)
@@ -537,16 +569,20 @@ class TestQOS(VppTestCase):
for p in rx:
self.assertEqual(p[IP].tos, 253)
- p_v1 = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- Dot1Q(vlan=11, prio=2) /
- IPv6(src="2001::1", dst="2001::2", tc=1) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(100) * NUM_PKTS))
-
- p_v2 = (Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac) /
- IPv6(src="3001::1", dst="2001::1", tc=1) /
- UDP(sport=1234, dport=1234) /
- Raw(scapy.compat.chb(100) * NUM_PKTS))
+ p_v1 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / Dot1Q(vlan=11, prio=2)
+ / IPv6(src="2001::1", dst="2001::2", tc=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(100) * NUM_PKTS)
+ )
+
+ p_v2 = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IPv6(src="3001::1", dst="2001::1", tc=1)
+ / UDP(sport=1234, dport=1234)
+ / Raw(scapy.compat.chb(100) * NUM_PKTS)
+ )
rx = self.send_and_expect(self.pg1, p_v2 * NUM_PKTS, self.pg0)
@@ -566,5 +602,5 @@ class TestQOS(VppTestCase):
sub_if.unconfig_ip6()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_quic.py b/test/test_quic.py
index 339557d4419..fde781c4f4a 100644
--- a/test/test_quic.py
+++ b/test/test_quic.py
@@ -12,20 +12,29 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
class QUICAppWorker(Worker):
- """ QUIC Test Application Worker """
+ """QUIC Test Application Worker"""
+
process = None
- def __init__(self, appname, executable_args, logger, role,
- testcase, env=None, *args, **kwargs):
+ def __init__(
+ self,
+ appname,
+ executable_args,
+ logger,
+ role,
+ testcase,
+ env=None,
+ *args,
+ **kwargs,
+ ):
if env is None:
env = {}
app = f"{config.vpp_build_dir}/vpp/bin/{appname}"
self.args = [app] + executable_args
self.role = role
- self.wait_for_gdb = 'wait-for-gdb'
+ self.wait_for_gdb = "wait-for-gdb"
self.testcase = testcase
- super(QUICAppWorker, self).__init__(self.args, logger, env,
- *args, **kwargs)
+ super(QUICAppWorker, self).__init__(self.args, logger, env, *args, **kwargs)
def run(self):
super(QUICAppWorker, self).run()
@@ -44,7 +53,7 @@ class QUICAppWorker(Worker):
class QUICTestCase(VppTestCase):
- """ QUIC Test Case """
+ """QUIC Test Case"""
timeout = 20
pre_test_sleep = 0.3
@@ -57,7 +66,7 @@ class QUICTestCase(VppTestCase):
def setUp(self):
super(QUICTestCase, self).setUp()
- self.vppDebug = 'vpp_debug' in config.vpp_build_dir
+ self.vppDebug = "vpp_debug" in config.vpp_build_dir
self.create_loopback_interfaces(2)
self.uri = "quic://%s/1234" % self.loop0.local_ip4
@@ -74,20 +83,28 @@ class QUICTestCase(VppTestCase):
table_id += 1
# Configure namespaces
- self.vapi.app_namespace_add_del(namespace_id="server",
- sw_if_index=self.loop0.sw_if_index)
- self.vapi.app_namespace_add_del(namespace_id="client",
- sw_if_index=self.loop1.sw_if_index)
+ self.vapi.app_namespace_add_del(
+ namespace_id="server", sw_if_index=self.loop0.sw_if_index
+ )
+ self.vapi.app_namespace_add_del(
+ namespace_id="client", sw_if_index=self.loop1.sw_if_index
+ )
# Add inter-table routes
- self.ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=2)], table_id=1)
- self.ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=1)], table_id=2)
+ self.ip_t01 = VppIpRoute(
+ self,
+ self.loop1.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=2)],
+ table_id=1,
+ )
+ self.ip_t10 = VppIpRoute(
+ self,
+ self.loop0.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)],
+ table_id=2,
+ )
self.ip_t01.add_vpp_config()
self.ip_t10.add_vpp_config()
self.logger.debug(self.vapi.cli("show ip fib"))
@@ -106,13 +123,15 @@ class QUICTestCase(VppTestCase):
class QUICEchoIntTestCase(QUICTestCase):
"""QUIC Echo Internal Test Case"""
- test_bytes = ' test-bytes'
+
+ test_bytes = " test-bytes"
extra_vpp_punt_config = ["session", "{", "enable", "poll-main", "}"]
def setUp(self):
super(QUICEchoIntTestCase, self).setUp()
- self.client_args = 'uri {uri} fifo-size 64{testbytes} appns client' \
- .format(uri=self.uri, testbytes=self.test_bytes)
+ self.client_args = "uri {uri} fifo-size 64{testbytes} appns client".format(
+ uri=self.uri, testbytes=self.test_bytes
+ )
self.server_args = "uri %s fifo-size 64 appns server" % self.uri
def tearDown(self):
@@ -120,16 +139,16 @@ class QUICEchoIntTestCase(QUICTestCase):
def server(self, *args):
error = self.vapi.cli(
- "test echo server %s %s" %
- (self.server_args, ' '.join(args)))
+ "test echo server %s %s" % (self.server_args, " ".join(args))
+ )
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
def client(self, *args):
error = self.vapi.cli(
- "test echo client %s %s" %
- (self.client_args, ' '.join(args)))
+ "test echo client %s %s" % (self.client_args, " ".join(args))
+ )
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
@@ -138,6 +157,7 @@ class QUICEchoIntTestCase(QUICTestCase):
@tag_fixme_vpp_workers
class QUICEchoIntTransferTestCase(QUICEchoIntTestCase):
"""QUIC Echo Internal Transfer Test Case"""
+
def test_quic_int_transfer(self):
"""QUIC internal transfer"""
self.server()
@@ -147,6 +167,7 @@ class QUICEchoIntTransferTestCase(QUICEchoIntTestCase):
@tag_fixme_vpp_workers
class QUICEchoIntSerialTestCase(QUICEchoIntTestCase):
"""QUIC Echo Internal Serial Transfer Test Case"""
+
def test_quic_serial_int_transfer(self):
"""QUIC serial internal transfer"""
self.server()
@@ -160,6 +181,7 @@ class QUICEchoIntSerialTestCase(QUICEchoIntTestCase):
@tag_fixme_vpp_workers
class QUICEchoIntMStreamTestCase(QUICEchoIntTestCase):
"""QUIC Echo Internal MultiStream Test Case"""
+
def test_quic_int_multistream_transfer(self):
"""QUIC internal multi-stream transfer"""
self.server()
@@ -176,36 +198,63 @@ class QUICEchoExtTestCase(QUICTestCase):
vpp_worker_count = 1
server_fifo_size = "1M"
client_fifo_size = "4M"
- extra_vpp_punt_config = ["session", "{",
- "enable", "poll-main", "evt_qs_memfd_seg",
- "evt_qs_seg_size", "64M",
- "event-queue-length", f"{evt_q_len}",
- "preallocated-sessions", "1024",
- "v4-session-table-buckets", "20000",
- "v4-session-table-memory", "64M",
- "v4-halfopen-table-buckets", "20000",
- "v4-halfopen-table-memory", "64M",
- "local-endpoints-table-buckets", "250000",
- "local-endpoints-table-memory", "512M",
- "}"]
+ extra_vpp_punt_config = [
+ "session",
+ "{",
+ "enable",
+ "poll-main",
+ "evt_qs_memfd_seg",
+ "evt_qs_seg_size",
+ "64M",
+ "event-queue-length",
+ f"{evt_q_len}",
+ "preallocated-sessions",
+ "1024",
+ "v4-session-table-buckets",
+ "20000",
+ "v4-session-table-memory",
+ "64M",
+ "v4-halfopen-table-buckets",
+ "20000",
+ "v4-halfopen-table-memory",
+ "64M",
+ "local-endpoints-table-buckets",
+ "250000",
+ "local-endpoints-table-memory",
+ "512M",
+ "}",
+ ]
def setUp(self):
super(QUICEchoExtTestCase, self).setUp()
common_args = [
- "uri", self.uri,
+ "uri",
+ self.uri,
"json",
self.test_bytes,
- "socket-name", self.get_api_sock_path(),
- "quic-setup", self.quic_setup,
- "nthreads", "1",
- "mq-size", f"{self.evt_q_len}"
+ "socket-name",
+ self.get_api_sock_path(),
+ "quic-setup",
+ self.quic_setup,
+ "nthreads",
+ "1",
+ "mq-size",
+ f"{self.evt_q_len}",
+ ]
+ self.server_echo_test_args = common_args + [
+ "server",
+ "appns",
+ "server",
+ "fifo-size",
+ f"{self.server_fifo_size}",
+ ]
+ self.client_echo_test_args = common_args + [
+ "client",
+ "appns",
+ "client",
+ "fifo-size",
+ f"{self.client_fifo_size}",
]
- self.server_echo_test_args = common_args + \
- ["server", "appns", "server", "fifo-size",
- f"{self.server_fifo_size}"]
- self.client_echo_test_args = common_args + \
- ["client", "appns", "client", "fifo-size",
- f"{self.client_fifo_size}"]
error = self.vapi.cli("quic set fifo-size 2M")
if error:
self.logger.critical(error)
@@ -213,23 +262,13 @@ class QUICEchoExtTestCase(QUICTestCase):
def server(self, *args):
_args = self.server_echo_test_args + list(args)
- self.worker_server = QUICAppWorker(
- self.app,
- _args,
- self.logger,
- 'server',
- self)
+ self.worker_server = QUICAppWorker(self.app, _args, self.logger, "server", self)
self.worker_server.start()
self.sleep(self.pre_test_sleep)
def client(self, *args):
_args = self.client_echo_test_args + list(args)
- self.worker_client = QUICAppWorker(
- self.app,
- _args,
- self.logger,
- 'client',
- self)
+ self.worker_client = QUICAppWorker(self.app, _args, self.logger, "client", self)
self.worker_client.start()
timeout = None if self.debug_all else self.timeout
self.worker_client.join(timeout)
@@ -246,22 +285,18 @@ class QUICEchoExtTestCase(QUICTestCase):
def validate_ext_test_results(self):
server_result = self.worker_server.result
client_result = self.worker_client.result
- self.logger.info("Server worker result is `%s'" %
- server_result)
- self.logger.info("Client worker result is `%s'" %
- client_result)
+ self.logger.info("Server worker result is `%s'" % server_result)
+ self.logger.info("Client worker result is `%s'" % client_result)
server_kill_error = False
if self.worker_server.result is None:
- server_kill_error = self.worker_server.teardown(
- self.logger, self.timeout)
+ server_kill_error = self.worker_server.teardown(self.logger, self.timeout)
if self.worker_client.result is None:
self.worker_client.teardown(self.logger, self.timeout)
err_msg = "Wrong server worker return code (%s)" % server_result
self.assertEqual(server_result, 0, err_msg)
self.assertIsNotNone(
- client_result,
- "Timeout! Client worker did not finish in %ss" %
- self.timeout)
+ client_result, "Timeout! Client worker did not finish in %ss" % self.timeout
+ )
err_msg = "Wrong client worker return code (%s)" % client_result
self.assertEqual(client_result, 0, err_msg)
self.assertFalse(server_kill_error, "Server kill errored")
@@ -269,6 +304,7 @@ class QUICEchoExtTestCase(QUICTestCase):
class QUICEchoExtTransferTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Test Case"""
+
timeout = 60
def test_quic_ext_transfer(self):
@@ -280,9 +316,10 @@ class QUICEchoExtTransferTestCase(QUICEchoExtTestCase):
class QUICEchoExtTransferBigTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Big Test Case"""
- server_fifo_size = '4M'
- client_fifo_size = '4M'
- test_bytes = ''
+
+ server_fifo_size = "4M"
+ client_fifo_size = "4M"
+ test_bytes = ""
timeout = 60
@unittest.skipUnless(config.extended, "part of extended tests")
@@ -312,8 +349,7 @@ class QUICEchoExtQcloseTxTestCase(QUICEchoExtTestCase):
@unittest.skip("testcase under development")
def test_quic_ext_qclose_tx(self):
"""QUIC external transfer, tx close"""
- self.server("TX=0", "RX=10M", "qclose=W", "sclose=W",
- "rx-results-diff")
+ self.server("TX=0", "RX=10M", "qclose=W", "sclose=W", "rx-results-diff")
self.client("TX=10M", "RX=0", "qclose=Y", "sclose=N")
self.validate_ext_test_results()
@@ -326,8 +362,7 @@ class QUICEchoExtEarlyQcloseRxTestCase(QUICEchoExtTestCase):
def test_quic_ext_early_qclose_rx(self):
"""QUIC external transfer, early rx close"""
self.server("TX=0", "RX=10M", "qclose=Y", "sclose=N")
- self.client("TX=20M", "RX=0", "qclose=W", "sclose=W",
- "tx-results-diff")
+ self.client("TX=20M", "RX=0", "qclose=W", "sclose=W", "tx-results-diff")
self.validate_ext_test_results()
@@ -338,8 +373,7 @@ class QUICEchoExtEarlyQcloseTxTestCase(QUICEchoExtTestCase):
@unittest.skip("testcase under development")
def test_quic_ext_early_qclose_tx(self):
"""QUIC external transfer, early tx close"""
- self.server("TX=0", "RX=20M", "qclose=W", "sclose=W",
- "rx-results-diff")
+ self.server("TX=0", "RX=20M", "qclose=W", "sclose=W", "rx-results-diff")
self.client("TX=10M", "RX=0", "qclose=Y", "sclose=N")
self.validate_ext_test_results()
@@ -376,8 +410,7 @@ class QUICEchoExtEarlyScloseRxTestCase(QUICEchoExtTestCase):
def test_quic_ext_early_sclose_rx(self):
"""QUIC external transfer, early rx stream close"""
self.server("TX=0", "RX=10M", "qclose=N", "sclose=Y")
- self.client("TX=20M", "RX=0", "qclose=W", "sclose=W",
- "tx-results-diff")
+ self.client("TX=20M", "RX=0", "qclose=W", "sclose=W", "tx-results-diff")
self.validate_ext_test_results()
@@ -388,14 +421,14 @@ class QUICEchoExtEarlyScloseTxTestCase(QUICEchoExtTestCase):
@unittest.skip("testcase under development")
def test_quic_ext_early_sclose_tx(self):
"""QUIC external transfer, early tx stream close"""
- self.server("TX=0", "RX=20M", "qclose=W", "sclose=W",
- "rx-results-diff")
+ self.server("TX=0", "RX=20M", "qclose=W", "sclose=W", "rx-results-diff")
self.client("TX=10M", "RX=0", "qclose=Y", "sclose=Y")
self.validate_ext_test_results()
class QUICEchoExtServerStreamTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Server Stream Test Case"""
+
quic_setup = "serverstream"
timeout = 60
@@ -408,10 +441,11 @@ class QUICEchoExtServerStreamTestCase(QUICEchoExtTestCase):
class QUICEchoExtServerStreamBigTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Server Stream Big Test Case"""
+
quic_setup = "serverstream"
- server_fifo_size = '4M'
- client_fifo_size = '4M'
- test_bytes = ''
+ server_fifo_size = "4M"
+ client_fifo_size = "4M"
+ test_bytes = ""
timeout = 60
@unittest.skipUnless(config.extended, "part of extended tests")
@@ -424,6 +458,7 @@ class QUICEchoExtServerStreamBigTestCase(QUICEchoExtTestCase):
class QUICEchoExtServerStreamQcloseRxTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Server Stream Qclose Rx Test Case"""
+
quic_setup = "serverstream"
@unittest.skipUnless(config.extended, "part of extended tests")
@@ -437,6 +472,7 @@ class QUICEchoExtServerStreamQcloseRxTestCase(QUICEchoExtTestCase):
class QUICEchoExtServerStreamQcloseTxTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Server Stream Qclose Tx Test Case"""
+
quic_setup = "serverstream"
@unittest.skipUnless(config.extended, "part of extended tests")
@@ -444,27 +480,27 @@ class QUICEchoExtServerStreamQcloseTxTestCase(QUICEchoExtTestCase):
def test_quic_ext_server_stream_qclose_tx(self):
"""QUIC external server transfer, tx close"""
self.server("TX=10M", "RX=0", "qclose=Y", "sclose=N")
- self.client("TX=0", "RX=10M", "qclose=W", "sclose=W",
- "rx-results-diff")
+ self.client("TX=0", "RX=10M", "qclose=W", "sclose=W", "rx-results-diff")
self.validate_ext_test_results()
class QUICEchoExtServerStreamEarlyQcloseRxTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Server Stream Early Qclose Rx Test Case"""
+
quic_setup = "serverstream"
@unittest.skipUnless(config.extended, "part of extended tests")
@unittest.skip("testcase under development")
def test_quic_ext_server_stream_early_qclose_rx(self):
"""QUIC external server transfer, early rx close"""
- self.server("TX=20M", "RX=0", "qclose=W", "sclose=W",
- "tx-results-diff")
+ self.server("TX=20M", "RX=0", "qclose=W", "sclose=W", "tx-results-diff")
self.client("TX=0", "RX=10M", "qclose=Y", "sclose=N")
self.validate_ext_test_results()
class QUICEchoExtServerStreamEarlyQcloseTxTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Server Stream Early Qclose Tx Test Case"""
+
quic_setup = "serverstream"
@unittest.skipUnless(config.extended, "part of extended tests")
@@ -472,13 +508,13 @@ class QUICEchoExtServerStreamEarlyQcloseTxTestCase(QUICEchoExtTestCase):
def test_quic_ext_server_stream_early_qclose_tx(self):
"""QUIC external server transfer, early tx close"""
self.server("TX=10M", "RX=0", "qclose=Y", "sclose=N")
- self.client("TX=0", "RX=20M", "qclose=W", "sclose=W",
- "rx-results-diff")
+ self.client("TX=0", "RX=20M", "qclose=W", "sclose=W", "rx-results-diff")
self.validate_ext_test_results()
class QUICEchoExtServerStreamScloseRxTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Server Stream Sclose Rx Test Case"""
+
quic_setup = "serverstream"
@unittest.skipUnless(config.extended, "part of extended tests")
@@ -492,6 +528,7 @@ class QUICEchoExtServerStreamScloseRxTestCase(QUICEchoExtTestCase):
class QUICEchoExtServerStreamScloseTxTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Server Stream Sclose Tx Test Case"""
+
quic_setup = "serverstream"
@unittest.skipUnless(config.extended, "part of extended tests")
@@ -505,20 +542,21 @@ class QUICEchoExtServerStreamScloseTxTestCase(QUICEchoExtTestCase):
class QUICEchoExtServerStreamEarlyScloseRxTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Server Stream Early Sclose Rx Test Case"""
+
quic_setup = "serverstream"
@unittest.skipUnless(config.extended, "part of extended tests")
@unittest.skip("testcase under development")
def test_quic_ext_server_stream_early_sclose_rx(self):
"""QUIC external server transfer, early rx stream close"""
- self.server("TX=20M", "RX=0", "qclose=W", "sclose=W",
- "tx-results-diff")
+ self.server("TX=20M", "RX=0", "qclose=W", "sclose=W", "tx-results-diff")
self.client("TX=0", "RX=10M", "qclose=N", "sclose=Y")
self.validate_ext_test_results()
class QUICEchoExtServerStreamEarlyScloseTxTestCase(QUICEchoExtTestCase):
"""QUIC Echo Ext Transfer Server Stream Early Sclose Tx Test Case"""
+
quic_setup = "serverstream"
@unittest.skipUnless(config.extended, "part of extended tests")
@@ -526,13 +564,13 @@ class QUICEchoExtServerStreamEarlyScloseTxTestCase(QUICEchoExtTestCase):
def test_quic_ext_server_stream_early_sclose_tx(self):
"""QUIC external server transfer, early tx stream close"""
self.server("TX=10M", "RX=0", "qclose=Y", "sclose=Y")
- self.client("TX=0", "RX=20M", "qclose=W", "sclose=W",
- "rx-results-diff")
+ self.client("TX=0", "RX=20M", "qclose=W", "sclose=W", "rx-results-diff")
self.validate_ext_test_results()
class QUICEchoExtServerStreamWorkersTestCase(QUICEchoExtTestCase):
"""QUIC Echo External Transfer Server Stream MultiWorker Test Case"""
+
quic_setup = "serverstream"
@unittest.skipUnless(config.extended, "part of extended tests")
@@ -544,5 +582,5 @@ class QUICEchoExtServerStreamWorkersTestCase(QUICEchoExtTestCase):
self.validate_ext_test_results()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_reassembly.py b/test/test_reassembly.py
index 4c7a7cd320b..cebe5837763 100644
--- a/test/test_reassembly.py
+++ b/test/test_reassembly.py
@@ -9,10 +9,18 @@ import scapy.compat
from scapy.packet import Raw
from scapy.layers.l2 import Ether, GRE
from scapy.layers.inet import IP, UDP, ICMP, icmptypes
-from scapy.layers.inet6 import HBHOptUnknown, ICMPv6ParamProblem,\
- ICMPv6TimeExceeded, IPv6, IPv6ExtHdrFragment,\
- IPv6ExtHdrHopByHop, IPv6ExtHdrDestOpt, PadN, ICMPv6EchoRequest,\
- ICMPv6EchoReply
+from scapy.layers.inet6 import (
+ HBHOptUnknown,
+ ICMPv6ParamProblem,
+ ICMPv6TimeExceeded,
+ IPv6,
+ IPv6ExtHdrFragment,
+ IPv6ExtHdrHopByHop,
+ IPv6ExtHdrDestOpt,
+ PadN,
+ ICMPv6EchoRequest,
+ ICMPv6EchoReply,
+)
from framework import VppTestCase, VppTestRunner
from util import ppp, ppc, fragment_rfc791, fragment_rfc8200
from vpp_gre_interface import VppGreInterface
@@ -25,7 +33,7 @@ test_packet_count = 35
class TestIPv4Reassembly(VppTestCase):
- """ IPv4 Reassembly """
+ """IPv4 Reassembly"""
@classmethod
def setUpClass(cls):
@@ -52,21 +60,29 @@ class TestIPv4Reassembly(VppTestCase):
super().tearDownClass()
def setUp(self):
- """ Test setup - force timeout on existing reassemblies """
+ """Test setup - force timeout on existing reassemblies"""
super().setUp()
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.src_if.sw_if_index, enable_ip4=True)
- self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10)
- self.virtual_sleep(.25)
- self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10000)
+ sw_if_index=self.src_if.sw_if_index, enable_ip4=True
+ )
+ self.vapi.ip_reassembly_set(
+ timeout_ms=0,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10,
+ )
+ self.virtual_sleep(0.25)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=1000000,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10000,
+ )
def tearDown(self):
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.src_if.sw_if_index, enable_ip4=False)
+ sw_if_index=self.src_if.sw_if_index, enable_ip4=False
+ )
super().tearDown()
def show_commands_at_teardown(self):
@@ -82,11 +98,14 @@ class TestIPv4Reassembly(VppTestCase):
for i in range(0, packet_count):
info = cls.create_packet_info(cls.src_if, cls.src_if)
payload = cls.info_to_payload(info)
- p = (Ether(dst=cls.src_if.local_mac, src=cls.src_if.remote_mac) /
- IP(id=info.index, src=cls.src_if.remote_ip4,
- dst=cls.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
+ p = (
+ Ether(dst=cls.src_if.local_mac, src=cls.src_if.remote_mac)
+ / IP(
+ id=info.index, src=cls.src_if.remote_ip4, dst=cls.dst_if.remote_ip4
+ )
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
size = packet_sizes[(i // 2) % len(packet_sizes)]
cls.extend_packet(p, size, cls.padding)
info.data = p
@@ -101,20 +120,21 @@ class TestIPv4Reassembly(VppTestCase):
# p.__class__(scapy.compat.raw(p))))
fragments_400 = fragment_rfc791(p, 400)
fragments_300 = fragment_rfc791(p, 300)
- fragments_200 = [
- x for f in fragments_400 for x in fragment_rfc791(f, 200)]
- cls.pkt_infos.append(
- (index, fragments_400, fragments_300, fragments_200))
- cls.fragments_400 = [
- x for (_, frags, _, _) in cls.pkt_infos for x in frags]
- cls.fragments_300 = [
- x for (_, _, frags, _) in cls.pkt_infos for x in frags]
- cls.fragments_200 = [
- x for (_, _, _, frags) in cls.pkt_infos for x in frags]
- cls.logger.debug("Fragmented %s packets into %s 400-byte fragments, "
- "%s 300-byte fragments and %s 200-byte fragments" %
- (len(infos), len(cls.fragments_400),
- len(cls.fragments_300), len(cls.fragments_200)))
+ fragments_200 = [x for f in fragments_400 for x in fragment_rfc791(f, 200)]
+ cls.pkt_infos.append((index, fragments_400, fragments_300, fragments_200))
+ cls.fragments_400 = [x for (_, frags, _, _) in cls.pkt_infos for x in frags]
+ cls.fragments_300 = [x for (_, _, frags, _) in cls.pkt_infos for x in frags]
+ cls.fragments_200 = [x for (_, _, _, frags) in cls.pkt_infos for x in frags]
+ cls.logger.debug(
+ "Fragmented %s packets into %s 400-byte fragments, "
+ "%s 300-byte fragments and %s 200-byte fragments"
+ % (
+ len(infos),
+ len(cls.fragments_400),
+ len(cls.fragments_300),
+ len(cls.fragments_200),
+ )
+ )
def verify_capture(self, capture, dropped_packet_indexes=[]):
"""Verify captured packet stream.
@@ -132,7 +152,8 @@ class TestIPv4Reassembly(VppTestCase):
packet_index = payload_info.index
self.assertTrue(
packet_index not in dropped_packet_indexes,
- ppp("Packet received, but should be dropped:", packet))
+ ppp("Packet received, but should be dropped:", packet),
+ )
if packet_index in seen:
raise Exception(ppp("Duplicate packet received", packet))
seen.add(packet_index)
@@ -148,11 +169,13 @@ class TestIPv4Reassembly(VppTestCase):
self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
for index in self._packet_infos:
- self.assertTrue(index in seen or index in dropped_packet_indexes,
- "Packet with packet_index %d not received" % index)
+ self.assertTrue(
+ index in seen or index in dropped_packet_indexes,
+ "Packet with packet_index %d not received" % index,
+ )
def test_reassembly(self):
- """ basic reassembly """
+ """basic reassembly"""
self.pg_enable_capture()
self.src_if.add_stream(self.fragments_200)
@@ -172,7 +195,7 @@ class TestIPv4Reassembly(VppTestCase):
self.src_if.assert_nothing_captured()
def test_verify_clear_trace_mid_reassembly(self):
- """ verify clear trace works mid-reassembly """
+ """verify clear trace works mid-reassembly"""
self.pg_enable_capture()
self.src_if.add_stream(self.fragments_200[0:-1])
@@ -187,7 +210,7 @@ class TestIPv4Reassembly(VppTestCase):
self.verify_capture(packets)
def test_reversed(self):
- """ reverse order reassembly """
+ """reverse order reassembly"""
fragments = list(self.fragments_200)
fragments.reverse()
@@ -210,27 +233,33 @@ class TestIPv4Reassembly(VppTestCase):
self.src_if.assert_nothing_captured()
def test_long_fragment_chain(self):
- """ long fragment chain """
+ """long fragment chain"""
- error_cnt_str = \
+ error_cnt_str = (
"/err/ip4-full-reassembly-feature/fragment chain too long (drop)"
+ )
error_cnt = self.statistics.get_err_counter(error_cnt_str)
- self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000,
- max_reassembly_length=3,
- expire_walk_interval_ms=50)
-
- p1 = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IP(id=1000, src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(b"X" * 1000))
- p2 = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IP(id=1001, src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(b"X" * 1000))
+ self.vapi.ip_reassembly_set(
+ timeout_ms=100,
+ max_reassemblies=1000,
+ max_reassembly_length=3,
+ expire_walk_interval_ms=50,
+ )
+
+ p1 = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(id=1000, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"X" * 1000)
+ )
+ p2 = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(id=1001, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"X" * 1000)
+ )
frags = fragment_rfc791(p1, 200) + fragment_rfc791(p2, 500)
self.pg_enable_capture()
@@ -241,19 +270,20 @@ class TestIPv4Reassembly(VppTestCase):
self.assert_error_counter_equal(error_cnt_str, error_cnt + 1)
def test_5737(self):
- """ fragment length + ip header size > 65535 """
+ """fragment length + ip header size > 65535"""
self.vapi.cli("clear errors")
- raw = b'''E\x00\x00\x88,\xf8\x1f\xfe@\x01\x98\x00\xc0\xa8\n-\xc0\xa8\n\
+ raw = b"""E\x00\x00\x88,\xf8\x1f\xfe@\x01\x98\x00\xc0\xa8\n-\xc0\xa8\n\
\x01\x08\x00\xf0J\xed\xcb\xf1\xf5Test-group: IPv4.IPv4.ipv4-message.\
-Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737'''
- malformed_packet = (Ether(dst=self.src_if.local_mac,
- src=self.src_if.remote_mac) /
- IP(raw))
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IP(id=1000, src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(b"X" * 1000))
+Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737"""
+ malformed_packet = Ether(
+ dst=self.src_if.local_mac, src=self.src_if.remote_mac
+ ) / IP(raw)
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(id=1000, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"X" * 1000)
+ )
valid_fragments = fragment_rfc791(p, 400)
counter = "/err/ip4-full-reassembly-feature/malformed packets"
@@ -264,33 +294,50 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737'''
self.dst_if.get_capture(1)
self.logger.debug(self.vapi.ppcli("show error"))
- self.assertEqual(self.statistics.get_err_counter(counter),
- error_counter + 1)
+ self.assertEqual(self.statistics.get_err_counter(counter), error_counter + 1)
def test_44924(self):
- """ compress tiny fragments """
- packets = [(Ether(dst=self.src_if.local_mac,
- src=self.src_if.remote_mac) /
- IP(id=24339, flags="MF", frag=0, ttl=64,
- src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- ICMP(type="echo-request", code=0, id=0x1fe6, seq=0x2407) /
- Raw(load='Test-group: IPv4')),
- (Ether(dst=self.src_if.local_mac,
- src=self.src_if.remote_mac) /
- IP(id=24339, flags="MF", frag=3, ttl=64,
- src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- ICMP(type="echo-request", code=0, id=0x1fe6, seq=0x2407) /
- Raw(load='.IPv4.Fragmentation.vali')),
- (Ether(dst=self.src_if.local_mac,
- src=self.src_if.remote_mac) /
- IP(id=24339, frag=6, ttl=64,
- src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- ICMP(type="echo-request", code=0, id=0x1fe6, seq=0x2407) /
- Raw(load='d; Test-case: 44924'))
- ]
+ """compress tiny fragments"""
+ packets = [
+ (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(
+ id=24339,
+ flags="MF",
+ frag=0,
+ ttl=64,
+ src=self.src_if.remote_ip4,
+ dst=self.dst_if.remote_ip4,
+ )
+ / ICMP(type="echo-request", code=0, id=0x1FE6, seq=0x2407)
+ / Raw(load="Test-group: IPv4")
+ ),
+ (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(
+ id=24339,
+ flags="MF",
+ frag=3,
+ ttl=64,
+ src=self.src_if.remote_ip4,
+ dst=self.dst_if.remote_ip4,
+ )
+ / ICMP(type="echo-request", code=0, id=0x1FE6, seq=0x2407)
+ / Raw(load=".IPv4.Fragmentation.vali")
+ ),
+ (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(
+ id=24339,
+ frag=6,
+ ttl=64,
+ src=self.src_if.remote_ip4,
+ dst=self.dst_if.remote_ip4,
+ )
+ / ICMP(type="echo-request", code=0, id=0x1FE6, seq=0x2407)
+ / Raw(load="d; Test-case: 44924")
+ ),
+ ]
self.pg_enable_capture()
self.src_if.add_stream(packets)
@@ -299,27 +346,42 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737'''
self.dst_if.get_capture(1)
def test_frag_1(self):
- """ fragment of size 1 """
+ """fragment of size 1"""
self.vapi.cli("clear errors")
- malformed_packets = [(Ether(dst=self.src_if.local_mac,
- src=self.src_if.remote_mac) /
- IP(id=7, len=21, flags="MF", frag=0, ttl=64,
- src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- ICMP(type="echo-request")),
- (Ether(dst=self.src_if.local_mac,
- src=self.src_if.remote_mac) /
- IP(id=7, len=21, frag=1, ttl=64,
- src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- Raw(load=b'\x08')),
- ]
-
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IP(id=1000, src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(b"X" * 1000))
+ malformed_packets = [
+ (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(
+ id=7,
+ len=21,
+ flags="MF",
+ frag=0,
+ ttl=64,
+ src=self.src_if.remote_ip4,
+ dst=self.dst_if.remote_ip4,
+ )
+ / ICMP(type="echo-request")
+ ),
+ (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(
+ id=7,
+ len=21,
+ frag=1,
+ ttl=64,
+ src=self.src_if.remote_ip4,
+ dst=self.dst_if.remote_ip4,
+ )
+ / Raw(load=b"\x08")
+ ),
+ ]
+
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(id=1000, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"X" * 1000)
+ )
valid_fragments = fragment_rfc791(p, 400)
self.pg_enable_capture()
@@ -335,7 +397,7 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737'''
# "/err/ip4-full-reassembly-feature/malformed packets", 1)
def test_random(self):
- """ random order reassembly """
+ """random order reassembly"""
fragments = list(self.fragments_200)
shuffle(fragments)
@@ -358,10 +420,11 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737'''
self.src_if.assert_nothing_captured()
def test_duplicates(self):
- """ duplicate fragments """
+ """duplicate fragments"""
fragments = [
- x for (_, frags, _, _) in self.pkt_infos
+ x
+ for (_, frags, _, _) in self.pkt_infos
for x in frags
for _ in range(0, min(2, len(frags)))
]
@@ -375,7 +438,7 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737'''
self.src_if.assert_nothing_captured()
def test_overlap1(self):
- """ overlapping fragments case #1 """
+ """overlapping fragments case #1"""
fragments = []
for _, _, frags_300, frags_200 in self.pkt_infos:
@@ -404,7 +467,7 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737'''
self.src_if.assert_nothing_captured()
def test_overlap2(self):
- """ overlapping fragments case #2 """
+ """overlapping fragments case #2"""
fragments = []
for _, _, frags_300, frags_200 in self.pkt_infos:
@@ -439,94 +502,112 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737'''
self.src_if.assert_nothing_captured()
def test_timeout_inline(self):
- """ timeout (inline) """
+ """timeout (inline)"""
dropped_packet_indexes = set(
index for (index, frags, _, _) in self.pkt_infos if len(frags) > 1
)
- self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000,
- max_reassembly_length=3,
- expire_walk_interval_ms=10000)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=0,
+ max_reassemblies=1000,
+ max_reassembly_length=3,
+ expire_walk_interval_ms=10000,
+ )
self.pg_enable_capture()
self.src_if.add_stream(self.fragments_400)
self.pg_start()
packets = self.dst_if.get_capture(
- len(self.pkt_infos) - len(dropped_packet_indexes))
+ len(self.pkt_infos) - len(dropped_packet_indexes)
+ )
self.verify_capture(packets, dropped_packet_indexes)
self.src_if.assert_nothing_captured()
def test_timeout_cleanup(self):
- """ timeout (cleanup) """
+ """timeout (cleanup)"""
# whole packets + fragmented packets sans last fragment
fragments = [
- x for (_, frags_400, _, _) in self.pkt_infos
- for x in frags_400[:-1 if len(frags_400) > 1 else None]
+ x
+ for (_, frags_400, _, _) in self.pkt_infos
+ for x in frags_400[: -1 if len(frags_400) > 1 else None]
]
# last fragments for fragmented packets
- fragments2 = [frags_400[-1]
- for (_, frags_400, _, _) in self.pkt_infos
- if len(frags_400) > 1]
+ fragments2 = [
+ frags_400[-1]
+ for (_, frags_400, _, _) in self.pkt_infos
+ if len(frags_400) > 1
+ ]
dropped_packet_indexes = set(
- index for (index, frags_400, _, _) in self.pkt_infos
- if len(frags_400) > 1)
+ index for (index, frags_400, _, _) in self.pkt_infos if len(frags_400) > 1
+ )
- self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=50)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=100,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=50,
+ )
self.pg_enable_capture()
self.src_if.add_stream(fragments)
self.pg_start()
- self.virtual_sleep(.25, "wait before sending rest of fragments")
+ self.virtual_sleep(0.25, "wait before sending rest of fragments")
self.src_if.add_stream(fragments2)
self.pg_start()
packets = self.dst_if.get_capture(
- len(self.pkt_infos) - len(dropped_packet_indexes))
+ len(self.pkt_infos) - len(dropped_packet_indexes)
+ )
self.verify_capture(packets, dropped_packet_indexes)
self.src_if.assert_nothing_captured()
def test_disabled(self):
- """ reassembly disabled """
+ """reassembly disabled"""
dropped_packet_indexes = set(
- index for (index, frags_400, _, _) in self.pkt_infos
- if len(frags_400) > 1)
+ index for (index, frags_400, _, _) in self.pkt_infos if len(frags_400) > 1
+ )
- self.vapi.ip_reassembly_set(timeout_ms=1000, max_reassemblies=0,
- max_reassembly_length=3,
- expire_walk_interval_ms=10000)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=1000,
+ max_reassemblies=0,
+ max_reassembly_length=3,
+ expire_walk_interval_ms=10000,
+ )
self.pg_enable_capture()
self.src_if.add_stream(self.fragments_400)
self.pg_start()
packets = self.dst_if.get_capture(
- len(self.pkt_infos) - len(dropped_packet_indexes))
+ len(self.pkt_infos) - len(dropped_packet_indexes)
+ )
self.verify_capture(packets, dropped_packet_indexes)
self.src_if.assert_nothing_captured()
def test_local_enable_disable(self):
- """ local reassembly enabled/disable """
+ """local reassembly enabled/disable"""
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.src_if.sw_if_index, enable_ip4=False)
+ sw_if_index=self.src_if.sw_if_index, enable_ip4=False
+ )
self.vapi.ip_local_reass_enable_disable(enable_ip4=True)
- p = (Ether(src=self.src_if.remote_mac, dst=self.src_if.local_mac) /
- IP(src=self.src_if.remote_ip4, dst=self.src_if.local_ip4) /
- ICMP(id=1234, type='echo-request') /
- Raw('x' * 1000))
+ p = (
+ Ether(src=self.src_if.remote_mac, dst=self.src_if.local_mac)
+ / IP(src=self.src_if.remote_ip4, dst=self.src_if.local_ip4)
+ / ICMP(id=1234, type="echo-request")
+ / Raw("x" * 1000)
+ )
frags = fragment_rfc791(p, 400)
r = self.send_and_expect(self.src_if, frags, self.src_if, n_rx=1)[0]
self.assertEqual(1234, r[ICMP].id)
- self.assertEqual(icmptypes[r[ICMP].type], 'echo-reply')
+ self.assertEqual(icmptypes[r[ICMP].type], "echo-reply")
self.vapi.ip_local_reass_enable_disable()
self.send_and_assert_no_replies(self.src_if, frags)
@@ -534,7 +615,7 @@ Ethernet-Payload.IPv4-Packet.IPv4-Header.Fragment-Offset; Test-case: 5737'''
class TestIPv4SVReassembly(VppTestCase):
- """ IPv4 Shallow Virtual Reassembly """
+ """IPv4 Shallow Virtual Reassembly"""
@classmethod
def setUpClass(cls):
@@ -551,22 +632,28 @@ class TestIPv4SVReassembly(VppTestCase):
i.resolve_arp()
def setUp(self):
- """ Test setup - force timeout on existing reassemblies """
+ """Test setup - force timeout on existing reassemblies"""
super().setUp()
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.src_if.sw_if_index, enable_ip4=True,
- type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL)
+ sw_if_index=self.src_if.sw_if_index,
+ enable_ip4=True,
+ type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL,
+ )
self.vapi.ip_reassembly_set(
- timeout_ms=0, max_reassemblies=1000,
+ timeout_ms=0,
+ max_reassemblies=1000,
max_reassembly_length=1000,
type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL,
- expire_walk_interval_ms=10)
- self.virtual_sleep(.25)
+ expire_walk_interval_ms=10,
+ )
+ self.virtual_sleep(0.25)
self.vapi.ip_reassembly_set(
- timeout_ms=1000000, max_reassemblies=1000,
+ timeout_ms=1000000,
+ max_reassemblies=1000,
max_reassembly_length=1000,
type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL,
- expire_walk_interval_ms=10000)
+ expire_walk_interval_ms=10000,
+ )
def tearDown(self):
super().tearDown()
@@ -574,7 +661,7 @@ class TestIPv4SVReassembly(VppTestCase):
self.logger.debug(self.vapi.ppcli("show buffers"))
def test_basic(self):
- """ basic reassembly """
+ """basic reassembly"""
payload_len = 1000
payload = ""
counter = 0
@@ -582,12 +669,13 @@ class TestIPv4SVReassembly(VppTestCase):
payload += "%u " % counter
counter += 1
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IP(id=1, src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
- fragments = fragment_rfc791(p, payload_len/4)
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(id=1, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
+ fragments = fragment_rfc791(p, payload_len / 4)
# send fragment #2 - should be cached inside reassembly
self.pg_enable_capture()
@@ -623,7 +711,7 @@ class TestIPv4SVReassembly(VppTestCase):
self.assertEqual(sent[Raw].payload, recvd[Raw].payload)
def test_verify_clear_trace_mid_reassembly(self):
- """ verify clear trace works mid-reassembly """
+ """verify clear trace works mid-reassembly"""
payload_len = 1000
payload = ""
counter = 0
@@ -631,12 +719,13 @@ class TestIPv4SVReassembly(VppTestCase):
payload += "%u " % counter
counter += 1
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IP(id=1, src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
- fragments = fragment_rfc791(p, payload_len/4)
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(id=1, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
+ fragments = fragment_rfc791(p, payload_len / 4)
self.pg_enable_capture()
self.src_if.add_stream(fragments[1])
@@ -659,7 +748,7 @@ class TestIPv4SVReassembly(VppTestCase):
self.dst_if.get_capture(len(fragments[2:]))
def test_timeout(self):
- """ reassembly timeout """
+ """reassembly timeout"""
payload_len = 1000
payload = ""
counter = 0
@@ -667,18 +756,21 @@ class TestIPv4SVReassembly(VppTestCase):
payload += "%u " % counter
counter += 1
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IP(id=1, src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
- fragments = fragment_rfc791(p, payload_len/4)
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(id=1, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
+ fragments = fragment_rfc791(p, payload_len / 4)
self.vapi.ip_reassembly_set(
- timeout_ms=100, max_reassemblies=1000,
+ timeout_ms=100,
+ max_reassemblies=1000,
max_reassembly_length=1000,
expire_walk_interval_ms=50,
- type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL)
+ type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL,
+ )
# send fragments #2 and #1 - should be forwarded
self.pg_enable_capture()
@@ -694,7 +786,7 @@ class TestIPv4SVReassembly(VppTestCase):
self.assertEqual(sent[Raw].payload, recvd[Raw].payload)
# wait for cleanup
- self.virtual_sleep(.25, "wait before sending rest of fragments")
+ self.virtual_sleep(0.25, "wait before sending rest of fragments")
# send rest of fragments - shouldn't be forwarded
self.pg_enable_capture()
@@ -703,13 +795,15 @@ class TestIPv4SVReassembly(VppTestCase):
self.dst_if.assert_nothing_captured()
def test_lru(self):
- """ reassembly reuses LRU element """
+ """reassembly reuses LRU element"""
self.vapi.ip_reassembly_set(
- timeout_ms=1000000, max_reassemblies=1,
+ timeout_ms=1000000,
+ max_reassemblies=1,
max_reassembly_length=1000,
type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL,
- expire_walk_interval_ms=10000)
+ expire_walk_interval_ms=10000,
+ )
payload_len = 1000
payload = ""
@@ -720,15 +814,17 @@ class TestIPv4SVReassembly(VppTestCase):
packet_count = 10
- fragments = [f
- for i in range(packet_count)
- for p in (Ether(dst=self.src_if.local_mac,
- src=self.src_if.remote_mac) /
- IP(id=i, src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
- for f in fragment_rfc791(p, payload_len/4)]
+ fragments = [
+ f
+ for i in range(packet_count)
+ for p in (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(id=i, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
+ for f in fragment_rfc791(p, payload_len / 4)
+ ]
self.pg_enable_capture()
self.src_if.add_stream(fragments)
@@ -742,16 +838,20 @@ class TestIPv4SVReassembly(VppTestCase):
def send_mixed_and_verify_capture(self, traffic):
stream = []
for t in traffic:
- for c in range(t['count']):
+ for c in range(t["count"]):
stream.append(
- (Ether(dst=self.src_if.local_mac,
- src=self.src_if.remote_mac) /
- IP(id=self.counter,
- flags=t['flags'],
- src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw("abcdef")))
+ (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(
+ id=self.counter,
+ flags=t["flags"],
+ src=self.src_if.remote_ip4,
+ dst=self.dst_if.remote_ip4,
+ )
+ / UDP(sport=1234, dport=5678)
+ / Raw("abcdef")
+ )
+ )
self.counter = self.counter + 1
self.pg_enable_capture()
@@ -763,58 +863,89 @@ class TestIPv4SVReassembly(VppTestCase):
self.dst_if.get_capture(len(stream))
def test_mixed(self):
- """ mixed traffic correctly passes through SVR """
+ """mixed traffic correctly passes through SVR"""
self.counter = 1
- self.send_mixed_and_verify_capture([{'count': 1, 'flags': ''}])
- self.send_mixed_and_verify_capture([{'count': 2, 'flags': ''}])
- self.send_mixed_and_verify_capture([{'count': 3, 'flags': ''}])
- self.send_mixed_and_verify_capture([{'count': 8, 'flags': ''}])
- self.send_mixed_and_verify_capture([{'count': 257, 'flags': ''}])
+ self.send_mixed_and_verify_capture([{"count": 1, "flags": ""}])
+ self.send_mixed_and_verify_capture([{"count": 2, "flags": ""}])
+ self.send_mixed_and_verify_capture([{"count": 3, "flags": ""}])
+ self.send_mixed_and_verify_capture([{"count": 8, "flags": ""}])
+ self.send_mixed_and_verify_capture([{"count": 257, "flags": ""}])
- self.send_mixed_and_verify_capture([{'count': 1, 'flags': 'MF'}])
- self.send_mixed_and_verify_capture([{'count': 2, 'flags': 'MF'}])
- self.send_mixed_and_verify_capture([{'count': 3, 'flags': 'MF'}])
- self.send_mixed_and_verify_capture([{'count': 8, 'flags': 'MF'}])
- self.send_mixed_and_verify_capture([{'count': 257, 'flags': 'MF'}])
+ self.send_mixed_and_verify_capture([{"count": 1, "flags": "MF"}])
+ self.send_mixed_and_verify_capture([{"count": 2, "flags": "MF"}])
+ self.send_mixed_and_verify_capture([{"count": 3, "flags": "MF"}])
+ self.send_mixed_and_verify_capture([{"count": 8, "flags": "MF"}])
+ self.send_mixed_and_verify_capture([{"count": 257, "flags": "MF"}])
self.send_mixed_and_verify_capture(
- [{'count': 1, 'flags': ''}, {'count': 1, 'flags': 'MF'}])
+ [{"count": 1, "flags": ""}, {"count": 1, "flags": "MF"}]
+ )
self.send_mixed_and_verify_capture(
- [{'count': 2, 'flags': ''}, {'count': 2, 'flags': 'MF'}])
+ [{"count": 2, "flags": ""}, {"count": 2, "flags": "MF"}]
+ )
self.send_mixed_and_verify_capture(
- [{'count': 3, 'flags': ''}, {'count': 3, 'flags': 'MF'}])
+ [{"count": 3, "flags": ""}, {"count": 3, "flags": "MF"}]
+ )
self.send_mixed_and_verify_capture(
- [{'count': 8, 'flags': ''}, {'count': 8, 'flags': 'MF'}])
+ [{"count": 8, "flags": ""}, {"count": 8, "flags": "MF"}]
+ )
self.send_mixed_and_verify_capture(
- [{'count': 129, 'flags': ''}, {'count': 129, 'flags': 'MF'}])
+ [{"count": 129, "flags": ""}, {"count": 129, "flags": "MF"}]
+ )
self.send_mixed_and_verify_capture(
- [{'count': 1, 'flags': ''}, {'count': 1, 'flags': 'MF'},
- {'count': 1, 'flags': ''}, {'count': 1, 'flags': 'MF'}])
+ [
+ {"count": 1, "flags": ""},
+ {"count": 1, "flags": "MF"},
+ {"count": 1, "flags": ""},
+ {"count": 1, "flags": "MF"},
+ ]
+ )
self.send_mixed_and_verify_capture(
- [{'count': 2, 'flags': ''}, {'count': 2, 'flags': 'MF'},
- {'count': 2, 'flags': ''}, {'count': 2, 'flags': 'MF'}])
+ [
+ {"count": 2, "flags": ""},
+ {"count": 2, "flags": "MF"},
+ {"count": 2, "flags": ""},
+ {"count": 2, "flags": "MF"},
+ ]
+ )
self.send_mixed_and_verify_capture(
- [{'count': 3, 'flags': ''}, {'count': 3, 'flags': 'MF'},
- {'count': 3, 'flags': ''}, {'count': 3, 'flags': 'MF'}])
+ [
+ {"count": 3, "flags": ""},
+ {"count": 3, "flags": "MF"},
+ {"count": 3, "flags": ""},
+ {"count": 3, "flags": "MF"},
+ ]
+ )
self.send_mixed_and_verify_capture(
- [{'count': 8, 'flags': ''}, {'count': 8, 'flags': 'MF'},
- {'count': 8, 'flags': ''}, {'count': 8, 'flags': 'MF'}])
+ [
+ {"count": 8, "flags": ""},
+ {"count": 8, "flags": "MF"},
+ {"count": 8, "flags": ""},
+ {"count": 8, "flags": "MF"},
+ ]
+ )
self.send_mixed_and_verify_capture(
- [{'count': 65, 'flags': ''}, {'count': 65, 'flags': 'MF'},
- {'count': 65, 'flags': ''}, {'count': 65, 'flags': 'MF'}])
+ [
+ {"count": 65, "flags": ""},
+ {"count": 65, "flags": "MF"},
+ {"count": 65, "flags": ""},
+ {"count": 65, "flags": "MF"},
+ ]
+ )
class TestIPv4MWReassembly(VppTestCase):
- """ IPv4 Reassembly (multiple workers) """
+ """IPv4 Reassembly (multiple workers)"""
+
vpp_worker_count = 3
@classmethod
def setUpClass(cls):
super().setUpClass()
- cls.create_pg_interfaces(range(cls.vpp_worker_count+1))
+ cls.create_pg_interfaces(range(cls.vpp_worker_count + 1))
cls.src_if = cls.pg0
cls.send_ifs = cls.pg_interfaces[:-1]
cls.dst_if = cls.pg_interfaces[-1]
@@ -828,8 +959,12 @@ class TestIPv4MWReassembly(VppTestCase):
# packets sizes reduced here because we are generating packets without
# Ethernet headers, which are added later (diff fragments go via
# different interfaces)
- cls.packet_sizes = [64-len(Ether()), 512-len(Ether()),
- 1518-len(Ether()), 9018-len(Ether())]
+ cls.packet_sizes = [
+ 64 - len(Ether()),
+ 512 - len(Ether()),
+ 1518 - len(Ether()),
+ 9018 - len(Ether()),
+ ]
cls.padding = " abcdefghijklmn"
cls.create_stream(cls.packet_sizes)
cls.create_fragments()
@@ -839,23 +974,31 @@ class TestIPv4MWReassembly(VppTestCase):
super().tearDownClass()
def setUp(self):
- """ Test setup - force timeout on existing reassemblies """
+ """Test setup - force timeout on existing reassemblies"""
super().setUp()
for intf in self.send_ifs:
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=intf.sw_if_index, enable_ip4=True)
- self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10)
- self.virtual_sleep(.25)
- self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10000)
+ sw_if_index=intf.sw_if_index, enable_ip4=True
+ )
+ self.vapi.ip_reassembly_set(
+ timeout_ms=0,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10,
+ )
+ self.virtual_sleep(0.25)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=1000000,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10000,
+ )
def tearDown(self):
for intf in self.send_ifs:
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=intf.sw_if_index, enable_ip4=False)
+ sw_if_index=intf.sw_if_index, enable_ip4=False
+ )
super().tearDown()
def show_commands_at_teardown(self):
@@ -871,10 +1014,11 @@ class TestIPv4MWReassembly(VppTestCase):
for i in range(0, packet_count):
info = cls.create_packet_info(cls.src_if, cls.src_if)
payload = cls.info_to_payload(info)
- p = (IP(id=info.index, src=cls.src_if.remote_ip4,
- dst=cls.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
+ p = (
+ IP(id=info.index, src=cls.src_if.remote_ip4, dst=cls.dst_if.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
size = packet_sizes[(i // 2) % len(packet_sizes)]
cls.extend_packet(p, size, cls.padding)
info.data = p
@@ -889,10 +1033,11 @@ class TestIPv4MWReassembly(VppTestCase):
# p.__class__(scapy.compat.raw(p))))
fragments_400 = fragment_rfc791(p, 400)
cls.pkt_infos.append((index, fragments_400))
- cls.fragments_400 = [
- x for (_, frags) in cls.pkt_infos for x in frags]
- cls.logger.debug("Fragmented %s packets into %s 400-byte fragments, " %
- (len(infos), len(cls.fragments_400)))
+ cls.fragments_400 = [x for (_, frags) in cls.pkt_infos for x in frags]
+ cls.logger.debug(
+ "Fragmented %s packets into %s 400-byte fragments, "
+ % (len(infos), len(cls.fragments_400))
+ )
def verify_capture(self, capture, dropped_packet_indexes=[]):
"""Verify captured packet stream.
@@ -910,7 +1055,8 @@ class TestIPv4MWReassembly(VppTestCase):
packet_index = payload_info.index
self.assertTrue(
packet_index not in dropped_packet_indexes,
- ppp("Packet received, but should be dropped:", packet))
+ ppp("Packet received, but should be dropped:", packet),
+ )
if packet_index in seen:
raise Exception(ppp("Duplicate packet received", packet))
seen.add(packet_index)
@@ -926,8 +1072,10 @@ class TestIPv4MWReassembly(VppTestCase):
self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
for index in self._packet_infos:
- self.assertTrue(index in seen or index in dropped_packet_indexes,
- "Packet with packet_index %d not received" % index)
+ self.assertTrue(
+ index in seen or index in dropped_packet_indexes,
+ "Packet with packet_index %d not received" % index,
+ )
def send_packets(self, packets):
for counter in range(self.vpp_worker_count):
@@ -935,13 +1083,16 @@ class TestIPv4MWReassembly(VppTestCase):
continue
send_if = self.send_ifs[counter]
send_if.add_stream(
- (Ether(dst=send_if.local_mac, src=send_if.remote_mac) / x
- for x in packets[counter]),
- worker=counter)
+ (
+ Ether(dst=send_if.local_mac, src=send_if.remote_mac) / x
+ for x in packets[counter]
+ ),
+ worker=counter,
+ )
self.pg_start()
def test_worker_conflict(self):
- """ 1st and FO=0 fragments on different workers """
+ """1st and FO=0 fragments on different workers"""
# in first wave we send fragments which don't start at offset 0
# then we send fragments with offset 0 on a different thread
@@ -988,7 +1139,7 @@ class TestIPv4MWReassembly(VppTestCase):
class TestIPv6Reassembly(VppTestCase):
- """ IPv6 Reassembly """
+ """IPv6 Reassembly"""
@classmethod
def setUpClass(cls):
@@ -1015,23 +1166,33 @@ class TestIPv6Reassembly(VppTestCase):
super().tearDownClass()
def setUp(self):
- """ Test setup - force timeout on existing reassemblies """
+ """Test setup - force timeout on existing reassemblies"""
super().setUp()
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.src_if.sw_if_index, enable_ip6=True)
- self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10, is_ip6=1)
- self.virtual_sleep(.25)
- self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10000, is_ip6=1)
+ sw_if_index=self.src_if.sw_if_index, enable_ip6=True
+ )
+ self.vapi.ip_reassembly_set(
+ timeout_ms=0,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10,
+ is_ip6=1,
+ )
+ self.virtual_sleep(0.25)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=1000000,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10000,
+ is_ip6=1,
+ )
self.logger.debug(self.vapi.ppcli("show ip6-full-reassembly details"))
self.logger.debug(self.vapi.ppcli("show buffers"))
def tearDown(self):
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.src_if.sw_if_index, enable_ip6=False)
+ sw_if_index=self.src_if.sw_if_index, enable_ip6=False
+ )
super().tearDown()
def show_commands_at_teardown(self):
@@ -1047,11 +1208,12 @@ class TestIPv6Reassembly(VppTestCase):
for i in range(0, packet_count):
info = cls.create_packet_info(cls.src_if, cls.src_if)
payload = cls.info_to_payload(info)
- p = (Ether(dst=cls.src_if.local_mac, src=cls.src_if.remote_mac) /
- IPv6(src=cls.src_if.remote_ip6,
- dst=cls.dst_if.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
+ p = (
+ Ether(dst=cls.src_if.local_mac, src=cls.src_if.remote_mac)
+ / IPv6(src=cls.src_if.remote_ip6, dst=cls.dst_if.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
size = packet_sizes[(i // 2) % len(packet_sizes)]
cls.extend_packet(p, size, cls.padding)
info.data = p
@@ -1067,14 +1229,13 @@ class TestIPv6Reassembly(VppTestCase):
fragments_400 = fragment_rfc8200(p, info.index, 400)
fragments_300 = fragment_rfc8200(p, info.index, 300)
cls.pkt_infos.append((index, fragments_400, fragments_300))
- cls.fragments_400 = [
- x for _, frags, _ in cls.pkt_infos for x in frags]
- cls.fragments_300 = [
- x for _, _, frags in cls.pkt_infos for x in frags]
- cls.logger.debug("Fragmented %s packets into %s 400-byte fragments, "
- "and %s 300-byte fragments" %
- (len(infos), len(cls.fragments_400),
- len(cls.fragments_300)))
+ cls.fragments_400 = [x for _, frags, _ in cls.pkt_infos for x in frags]
+ cls.fragments_300 = [x for _, _, frags in cls.pkt_infos for x in frags]
+ cls.logger.debug(
+ "Fragmented %s packets into %s 400-byte fragments, "
+ "and %s 300-byte fragments"
+ % (len(infos), len(cls.fragments_400), len(cls.fragments_300))
+ )
def verify_capture(self, capture, dropped_packet_indexes=[]):
"""Verify captured packet strea .
@@ -1092,7 +1253,8 @@ class TestIPv6Reassembly(VppTestCase):
packet_index = payload_info.index
self.assertTrue(
packet_index not in dropped_packet_indexes,
- ppp("Packet received, but should be dropped:", packet))
+ ppp("Packet received, but should be dropped:", packet),
+ )
if packet_index in seen:
raise Exception(ppp("Duplicate packet received", packet))
seen.add(packet_index)
@@ -1108,11 +1270,13 @@ class TestIPv6Reassembly(VppTestCase):
self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
for index in self._packet_infos:
- self.assertTrue(index in seen or index in dropped_packet_indexes,
- "Packet with packet_index %d not received" % index)
+ self.assertTrue(
+ index in seen or index in dropped_packet_indexes,
+ "Packet with packet_index %d not received" % index,
+ )
def test_reassembly(self):
- """ basic reassembly """
+ """basic reassembly"""
self.pg_enable_capture()
self.src_if.add_stream(self.fragments_400)
@@ -1132,16 +1296,16 @@ class TestIPv6Reassembly(VppTestCase):
self.src_if.assert_nothing_captured()
def test_buffer_boundary(self):
- """ fragment header crossing buffer boundary """
-
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6,
- dst=self.src_if.local_ip6) /
- IPv6ExtHdrHopByHop(
- options=[HBHOptUnknown(otype=0xff, optlen=0)] * 1000) /
- IPv6ExtHdrFragment(m=1) /
- UDP(sport=1234, dport=5678) /
- Raw())
+ """fragment header crossing buffer boundary"""
+
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6)
+ / IPv6ExtHdrHopByHop(options=[HBHOptUnknown(otype=0xFF, optlen=0)] * 1000)
+ / IPv6ExtHdrFragment(m=1)
+ / UDP(sport=1234, dport=5678)
+ / Raw()
+ )
self.pg_enable_capture()
self.src_if.add_stream([p])
self.pg_start()
@@ -1149,7 +1313,7 @@ class TestIPv6Reassembly(VppTestCase):
self.dst_if.assert_nothing_captured()
def test_verify_clear_trace_mid_reassembly(self):
- """ verify clear trace works mid-reassembly """
+ """verify clear trace works mid-reassembly"""
self.pg_enable_capture()
self.src_if.add_stream(self.fragments_400[0:-1])
@@ -1164,7 +1328,7 @@ class TestIPv6Reassembly(VppTestCase):
self.verify_capture(packets)
def test_reversed(self):
- """ reverse order reassembly """
+ """reverse order reassembly"""
fragments = list(self.fragments_400)
fragments.reverse()
@@ -1187,7 +1351,7 @@ class TestIPv6Reassembly(VppTestCase):
self.src_if.assert_nothing_captured()
def test_random(self):
- """ random order reassembly """
+ """random order reassembly"""
fragments = list(self.fragments_400)
shuffle(fragments)
@@ -1210,10 +1374,11 @@ class TestIPv6Reassembly(VppTestCase):
self.src_if.assert_nothing_captured()
def test_duplicates(self):
- """ duplicate fragments """
+ """duplicate fragments"""
fragments = [
- x for (_, frags, _) in self.pkt_infos
+ x
+ for (_, frags, _) in self.pkt_infos
for x in frags
for _ in range(0, min(2, len(frags)))
]
@@ -1227,22 +1392,28 @@ class TestIPv6Reassembly(VppTestCase):
self.src_if.assert_nothing_captured()
def test_long_fragment_chain(self):
- """ long fragment chain """
+ """long fragment chain"""
- error_cnt_str = \
+ error_cnt_str = (
"/err/ip6-full-reassembly-feature/fragment chain too long (drop)"
+ )
error_cnt = self.statistics.get_err_counter(error_cnt_str)
- self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000,
- max_reassembly_length=3,
- expire_walk_interval_ms=50, is_ip6=1)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=100,
+ max_reassemblies=1000,
+ max_reassembly_length=3,
+ expire_walk_interval_ms=50,
+ is_ip6=1,
+ )
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6,
- dst=self.dst_if.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(b"X" * 1000))
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(b"X" * 1000)
+ )
frags = fragment_rfc8200(p, 1, 300) + fragment_rfc8200(p, 2, 500)
self.pg_enable_capture()
@@ -1253,7 +1424,7 @@ class TestIPv6Reassembly(VppTestCase):
self.assert_error_counter_equal(error_cnt_str, error_cnt + 1)
def test_overlap1(self):
- """ overlapping fragments case #1 """
+ """overlapping fragments case #1"""
fragments = []
for _, frags_400, frags_300 in self.pkt_infos:
@@ -1273,12 +1444,13 @@ class TestIPv6Reassembly(VppTestCase):
self.pg_start()
packets = self.dst_if.get_capture(
- len(self.pkt_infos) - len(dropped_packet_indexes))
+ len(self.pkt_infos) - len(dropped_packet_indexes)
+ )
self.verify_capture(packets, dropped_packet_indexes)
self.src_if.assert_nothing_captured()
def test_overlap2(self):
- """ overlapping fragments case #2 """
+ """overlapping fragments case #2"""
fragments = []
for _, frags_400, frags_300 in self.pkt_infos:
@@ -1304,27 +1476,33 @@ class TestIPv6Reassembly(VppTestCase):
self.pg_start()
packets = self.dst_if.get_capture(
- len(self.pkt_infos) - len(dropped_packet_indexes))
+ len(self.pkt_infos) - len(dropped_packet_indexes)
+ )
self.verify_capture(packets, dropped_packet_indexes)
self.src_if.assert_nothing_captured()
def test_timeout_inline(self):
- """ timeout (inline) """
+ """timeout (inline)"""
dropped_packet_indexes = set(
index for (index, frags, _) in self.pkt_infos if len(frags) > 1
)
- self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000,
- max_reassembly_length=3,
- expire_walk_interval_ms=10000, is_ip6=1)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=0,
+ max_reassemblies=1000,
+ max_reassembly_length=3,
+ expire_walk_interval_ms=10000,
+ is_ip6=1,
+ )
self.pg_enable_capture()
self.src_if.add_stream(self.fragments_400)
self.pg_start()
packets = self.dst_if.get_capture(
- len(self.pkt_infos) - len(dropped_packet_indexes))
+ len(self.pkt_infos) - len(dropped_packet_indexes)
+ )
self.verify_capture(packets, dropped_packet_indexes)
pkts = self.src_if._get_capture(1)
for icmp in pkts:
@@ -1334,42 +1512,51 @@ class TestIPv6Reassembly(VppTestCase):
dropped_packet_indexes.remove(icmp[IPv6ExtHdrFragment].id)
def test_timeout_cleanup(self):
- """ timeout (cleanup) """
+ """timeout (cleanup)"""
# whole packets + fragmented packets sans last fragment
fragments = [
- x for (_, frags_400, _) in self.pkt_infos
- for x in frags_400[:-1 if len(frags_400) > 1 else None]
+ x
+ for (_, frags_400, _) in self.pkt_infos
+ for x in frags_400[: -1 if len(frags_400) > 1 else None]
]
# last fragments for fragmented packets
- fragments2 = [frags_400[-1]
- for (_, frags_400, _) in self.pkt_infos
- if len(frags_400) > 1]
+ fragments2 = [
+ frags_400[-1] for (_, frags_400, _) in self.pkt_infos if len(frags_400) > 1
+ ]
dropped_packet_indexes = set(
- index for (index, frags_400, _) in self.pkt_infos
- if len(frags_400) > 1)
+ index for (index, frags_400, _) in self.pkt_infos if len(frags_400) > 1
+ )
- self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=50)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=100,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=50,
+ )
- self.vapi.ip_reassembly_set(timeout_ms=100, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=50, is_ip6=1)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=100,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=50,
+ is_ip6=1,
+ )
self.pg_enable_capture()
self.src_if.add_stream(fragments)
self.pg_start()
- self.virtual_sleep(.25, "wait before sending rest of fragments")
+ self.virtual_sleep(0.25, "wait before sending rest of fragments")
self.src_if.add_stream(fragments2)
self.pg_start()
packets = self.dst_if.get_capture(
- len(self.pkt_infos) - len(dropped_packet_indexes))
+ len(self.pkt_infos) - len(dropped_packet_indexes)
+ )
self.verify_capture(packets, dropped_packet_indexes)
pkts = self.src_if._get_capture(1)
for icmp in pkts:
@@ -1379,34 +1566,41 @@ class TestIPv6Reassembly(VppTestCase):
dropped_packet_indexes.remove(icmp[IPv6ExtHdrFragment].id)
def test_disabled(self):
- """ reassembly disabled """
+ """reassembly disabled"""
dropped_packet_indexes = set(
- index for (index, frags_400, _) in self.pkt_infos
- if len(frags_400) > 1)
+ index for (index, frags_400, _) in self.pkt_infos if len(frags_400) > 1
+ )
- self.vapi.ip_reassembly_set(timeout_ms=1000, max_reassemblies=0,
- max_reassembly_length=3,
- expire_walk_interval_ms=10000, is_ip6=1)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=1000,
+ max_reassemblies=0,
+ max_reassembly_length=3,
+ expire_walk_interval_ms=10000,
+ is_ip6=1,
+ )
self.pg_enable_capture()
self.src_if.add_stream(self.fragments_400)
self.pg_start()
packets = self.dst_if.get_capture(
- len(self.pkt_infos) - len(dropped_packet_indexes))
+ len(self.pkt_infos) - len(dropped_packet_indexes)
+ )
self.verify_capture(packets, dropped_packet_indexes)
self.src_if.assert_nothing_captured()
def test_missing_upper(self):
- """ missing upper layer """
- optdata = '\x00' * 100
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6,
- dst=self.src_if.local_ip6) /
- IPv6ExtHdrFragment(m=1) /
- IPv6ExtHdrDestOpt(nh=17, options=PadN(optdata='\101' * 255) /
- PadN(optdata='\102'*255)))
+ """missing upper layer"""
+ optdata = "\x00" * 100
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6)
+ / IPv6ExtHdrFragment(m=1)
+ / IPv6ExtHdrDestOpt(
+ nh=17, options=PadN(optdata="\101" * 255) / PadN(optdata="\102" * 255)
+ )
+ )
self.pg_enable_capture()
self.src_if.add_stream([p])
@@ -1417,21 +1611,23 @@ class TestIPv6Reassembly(VppTestCase):
self.assert_equal(icmp[ICMPv6ParamProblem].code, 3, "ICMP code")
def test_truncated_fragment(self):
- """ truncated fragment """
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6,
- nh=44, plen=2) /
- IPv6ExtHdrFragment(nh=6))
+ """truncated fragment"""
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44, plen=2)
+ / IPv6ExtHdrFragment(nh=6)
+ )
self.send_and_assert_no_replies(self.pg0, [pkt], self.pg0)
def test_invalid_frag_size(self):
- """ fragment size not a multiple of 8 """
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6,
- dst=self.src_if.local_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw())
+ """fragment size not a multiple of 8"""
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw()
+ )
self.extend_packet(p, 1000, self.padding)
fragments = fragment_rfc8200(p, 1, 500)
bad_fragment = fragments[0]
@@ -1445,12 +1641,13 @@ class TestIPv6Reassembly(VppTestCase):
self.assert_equal(icmp[ICMPv6ParamProblem].code, 0, "ICMP code")
def test_invalid_packet_size(self):
- """ total packet size > 65535 """
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6,
- dst=self.src_if.local_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw())
+ """total packet size > 65535"""
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw()
+ )
self.extend_packet(p, 1000, self.padding)
fragments = fragment_rfc8200(p, 1, 500)
bad_fragment = fragments[1]
@@ -1464,44 +1661,56 @@ class TestIPv6Reassembly(VppTestCase):
self.assert_equal(icmp[ICMPv6ParamProblem].code, 0, "ICMP code")
def test_atomic_fragment(self):
- """ IPv6 atomic fragment """
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6,
- nh=44, plen=65535) /
- IPv6ExtHdrFragment(offset=8191, m=1, res1=0xFF, res2=0xFF,
- nh=255, id=0xffff)/('X'*1452))
+ """IPv6 atomic fragment"""
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44, plen=65535)
+ / IPv6ExtHdrFragment(
+ offset=8191, m=1, res1=0xFF, res2=0xFF, nh=255, id=0xFFFF
+ )
+ / ("X" * 1452)
+ )
rx = self.send_and_expect(self.pg0, [pkt], self.pg0)
self.assertIn(ICMPv6ParamProblem, rx[0])
def test_truncated_fragment(self):
- """ IPv6 truncated fragment header """
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6,
- nh=44, plen=2) /
- IPv6ExtHdrFragment(nh=6))
+ """IPv6 truncated fragment header"""
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44, plen=2)
+ / IPv6ExtHdrFragment(nh=6)
+ )
self.send_and_assert_no_replies(self.pg0, [pkt])
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) /
- ICMPv6EchoRequest())
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6)
+ / ICMPv6EchoRequest()
+ )
rx = self.send_and_expect(self.pg0, [pkt], self.pg0)
def test_one_fragment(self):
- """ whole packet in one fragment processed independently """
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- ICMPv6EchoRequest()/Raw('X' * 1600))
+ """whole packet in one fragment processed independently"""
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / ICMPv6EchoRequest()
+ / Raw("X" * 1600)
+ )
frags = fragment_rfc8200(pkt, 1, 400)
# send a fragment with known id
self.send_and_assert_no_replies(self.pg0, [frags[0]])
# send an atomic fragment with same id - should be reassembled
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- IPv6ExtHdrFragment(id=1)/ICMPv6EchoRequest())
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / IPv6ExtHdrFragment(id=1)
+ / ICMPv6EchoRequest()
+ )
rx = self.send_and_expect(self.pg0, [pkt], self.pg0)
self.assertNotIn(IPv6ExtHdrFragment, rx)
@@ -1510,33 +1719,46 @@ class TestIPv6Reassembly(VppTestCase):
self.assertNotIn(IPv6ExtHdrFragment, rx)
def test_bunch_of_fragments(self):
- """ valid fragments followed by rogue fragments and atomic fragment"""
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- ICMPv6EchoRequest()/Raw('X' * 1600))
+ """valid fragments followed by rogue fragments and atomic fragment"""
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / ICMPv6EchoRequest()
+ / Raw("X" * 1600)
+ )
frags = fragment_rfc8200(pkt, 1, 400)
self.send_and_expect(self.pg0, frags, self.pg0, n_rx=1)
- inc_frag = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- IPv6ExtHdrFragment(id=1, nh=58, offset=608)/Raw('X'*308))
+ inc_frag = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / IPv6ExtHdrFragment(id=1, nh=58, offset=608)
+ / Raw("X" * 308)
+ )
- self.send_and_assert_no_replies(self.pg0, inc_frag*604)
+ self.send_and_assert_no_replies(self.pg0, inc_frag * 604)
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- IPv6ExtHdrFragment(id=1)/ICMPv6EchoRequest())
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / IPv6ExtHdrFragment(id=1)
+ / ICMPv6EchoRequest()
+ )
rx = self.send_and_expect(self.pg0, [pkt], self.pg0)
self.assertNotIn(IPv6ExtHdrFragment, rx)
def test_local_enable_disable(self):
- """ local reassembly enabled/disable """
+ """local reassembly enabled/disable"""
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.src_if.sw_if_index, enable_ip6=False)
+ sw_if_index=self.src_if.sw_if_index, enable_ip6=False
+ )
self.vapi.ip_local_reass_enable_disable(enable_ip6=True)
- pkt = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6) /
- ICMPv6EchoRequest(id=1234)/Raw('X' * 1600))
+ pkt = (
+ Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.src_if.local_ip6)
+ / ICMPv6EchoRequest(id=1234)
+ / Raw("X" * 1600)
+ )
frags = fragment_rfc8200(pkt, 1, 400)
r = self.send_and_expect(self.src_if, frags, self.src_if, n_rx=1)[0]
self.assertEqual(1234, r[ICMPv6EchoReply].id)
@@ -1547,14 +1769,15 @@ class TestIPv6Reassembly(VppTestCase):
class TestIPv6MWReassembly(VppTestCase):
- """ IPv6 Reassembly (multiple workers) """
+ """IPv6 Reassembly (multiple workers)"""
+
vpp_worker_count = 3
@classmethod
def setUpClass(cls):
super().setUpClass()
- cls.create_pg_interfaces(range(cls.vpp_worker_count+1))
+ cls.create_pg_interfaces(range(cls.vpp_worker_count + 1))
cls.src_if = cls.pg0
cls.send_ifs = cls.pg_interfaces[:-1]
cls.dst_if = cls.pg_interfaces[-1]
@@ -1568,8 +1791,12 @@ class TestIPv6MWReassembly(VppTestCase):
# packets sizes reduced here because we are generating packets without
# Ethernet headers, which are added later (diff fragments go via
# different interfaces)
- cls.packet_sizes = [64-len(Ether()), 512-len(Ether()),
- 1518-len(Ether()), 9018-len(Ether())]
+ cls.packet_sizes = [
+ 64 - len(Ether()),
+ 512 - len(Ether()),
+ 1518 - len(Ether()),
+ 9018 - len(Ether()),
+ ]
cls.padding = " abcdefghijklmn"
cls.create_stream(cls.packet_sizes)
cls.create_fragments()
@@ -1579,23 +1806,33 @@ class TestIPv6MWReassembly(VppTestCase):
super().tearDownClass()
def setUp(self):
- """ Test setup - force timeout on existing reassemblies """
+ """Test setup - force timeout on existing reassemblies"""
super().setUp()
for intf in self.send_ifs:
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=intf.sw_if_index, enable_ip6=True)
- self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10, is_ip6=1)
- self.virtual_sleep(.25)
- self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=1000, is_ip6=1)
+ sw_if_index=intf.sw_if_index, enable_ip6=True
+ )
+ self.vapi.ip_reassembly_set(
+ timeout_ms=0,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10,
+ is_ip6=1,
+ )
+ self.virtual_sleep(0.25)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=1000000,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=1000,
+ is_ip6=1,
+ )
def tearDown(self):
for intf in self.send_ifs:
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=intf.sw_if_index, enable_ip6=False)
+ sw_if_index=intf.sw_if_index, enable_ip6=False
+ )
super().tearDown()
def show_commands_at_teardown(self):
@@ -1611,10 +1848,11 @@ class TestIPv6MWReassembly(VppTestCase):
for i in range(0, packet_count):
info = cls.create_packet_info(cls.src_if, cls.src_if)
payload = cls.info_to_payload(info)
- p = (IPv6(src=cls.src_if.remote_ip6,
- dst=cls.dst_if.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
+ p = (
+ IPv6(src=cls.src_if.remote_ip6, dst=cls.dst_if.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
size = packet_sizes[(i // 2) % len(packet_sizes)]
cls.extend_packet(p, size, cls.padding)
info.data = p
@@ -1629,10 +1867,11 @@ class TestIPv6MWReassembly(VppTestCase):
# p.__class__(scapy.compat.raw(p))))
fragments_400 = fragment_rfc8200(p, index, 400)
cls.pkt_infos.append((index, fragments_400))
- cls.fragments_400 = [
- x for (_, frags) in cls.pkt_infos for x in frags]
- cls.logger.debug("Fragmented %s packets into %s 400-byte fragments, " %
- (len(infos), len(cls.fragments_400)))
+ cls.fragments_400 = [x for (_, frags) in cls.pkt_infos for x in frags]
+ cls.logger.debug(
+ "Fragmented %s packets into %s 400-byte fragments, "
+ % (len(infos), len(cls.fragments_400))
+ )
def verify_capture(self, capture, dropped_packet_indexes=[]):
"""Verify captured packet strea .
@@ -1650,7 +1889,8 @@ class TestIPv6MWReassembly(VppTestCase):
packet_index = payload_info.index
self.assertTrue(
packet_index not in dropped_packet_indexes,
- ppp("Packet received, but should be dropped:", packet))
+ ppp("Packet received, but should be dropped:", packet),
+ )
if packet_index in seen:
raise Exception(ppp("Duplicate packet received", packet))
seen.add(packet_index)
@@ -1666,8 +1906,10 @@ class TestIPv6MWReassembly(VppTestCase):
self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
for index in self._packet_infos:
- self.assertTrue(index in seen or index in dropped_packet_indexes,
- "Packet with packet_index %d not received" % index)
+ self.assertTrue(
+ index in seen or index in dropped_packet_indexes,
+ "Packet with packet_index %d not received" % index,
+ )
def send_packets(self, packets):
for counter in range(self.vpp_worker_count):
@@ -1675,13 +1917,16 @@ class TestIPv6MWReassembly(VppTestCase):
continue
send_if = self.send_ifs[counter]
send_if.add_stream(
- (Ether(dst=send_if.local_mac, src=send_if.remote_mac) / x
- for x in packets[counter]),
- worker=counter)
+ (
+ Ether(dst=send_if.local_mac, src=send_if.remote_mac) / x
+ for x in packets[counter]
+ ),
+ worker=counter,
+ )
self.pg_start()
def test_worker_conflict(self):
- """ 1st and FO=0 fragments on different workers """
+ """1st and FO=0 fragments on different workers"""
# in first wave we send fragments which don't start at offset 0
# then we send fragments with offset 0 on a different thread
@@ -1728,7 +1973,7 @@ class TestIPv6MWReassembly(VppTestCase):
class TestIPv6SVReassembly(VppTestCase):
- """ IPv6 Shallow Virtual Reassembly """
+ """IPv6 Shallow Virtual Reassembly"""
@classmethod
def setUpClass(cls):
@@ -1745,22 +1990,30 @@ class TestIPv6SVReassembly(VppTestCase):
i.resolve_ndp()
def setUp(self):
- """ Test setup - force timeout on existing reassemblies """
+ """Test setup - force timeout on existing reassemblies"""
super().setUp()
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.src_if.sw_if_index, enable_ip6=True,
- type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL)
+ sw_if_index=self.src_if.sw_if_index,
+ enable_ip6=True,
+ type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL,
+ )
self.vapi.ip_reassembly_set(
- timeout_ms=0, max_reassemblies=1000,
+ timeout_ms=0,
+ max_reassemblies=1000,
max_reassembly_length=1000,
type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL,
- expire_walk_interval_ms=10, is_ip6=1)
- self.virtual_sleep(.25)
+ expire_walk_interval_ms=10,
+ is_ip6=1,
+ )
+ self.virtual_sleep(0.25)
self.vapi.ip_reassembly_set(
- timeout_ms=1000000, max_reassemblies=1000,
+ timeout_ms=1000000,
+ max_reassemblies=1000,
max_reassembly_length=1000,
type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL,
- expire_walk_interval_ms=10000, is_ip6=1)
+ expire_walk_interval_ms=10000,
+ is_ip6=1,
+ )
def tearDown(self):
super().tearDown()
@@ -1768,7 +2021,7 @@ class TestIPv6SVReassembly(VppTestCase):
self.logger.debug(self.vapi.ppcli("show buffers"))
def test_basic(self):
- """ basic reassembly """
+ """basic reassembly"""
payload_len = 1000
payload = ""
counter = 0
@@ -1776,11 +2029,13 @@ class TestIPv6SVReassembly(VppTestCase):
payload += "%u " % counter
counter += 1
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
- fragments = fragment_rfc8200(p, 1, payload_len/4)
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
+ fragments = fragment_rfc8200(p, 1, payload_len / 4)
# send fragment #2 - should be cached inside reassembly
self.pg_enable_capture()
@@ -1816,7 +2071,7 @@ class TestIPv6SVReassembly(VppTestCase):
self.assertEqual(sent[Raw].payload, recvd[Raw].payload)
def test_verify_clear_trace_mid_reassembly(self):
- """ verify clear trace works mid-reassembly """
+ """verify clear trace works mid-reassembly"""
payload_len = 1000
payload = ""
counter = 0
@@ -1824,11 +2079,13 @@ class TestIPv6SVReassembly(VppTestCase):
payload += "%u " % counter
counter += 1
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
- fragments = fragment_rfc8200(p, 1, payload_len/4)
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
+ fragments = fragment_rfc8200(p, 1, payload_len / 4)
self.pg_enable_capture()
self.src_if.add_stream(fragments[1])
@@ -1851,7 +2108,7 @@ class TestIPv6SVReassembly(VppTestCase):
self.dst_if.get_capture(len(fragments[2:]))
def test_timeout(self):
- """ reassembly timeout """
+ """reassembly timeout"""
payload_len = 1000
payload = ""
counter = 0
@@ -1859,18 +2116,22 @@ class TestIPv6SVReassembly(VppTestCase):
payload += "%u " % counter
counter += 1
- p = (Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
- fragments = fragment_rfc8200(p, 1, payload_len/4)
+ p = (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
+ fragments = fragment_rfc8200(p, 1, payload_len / 4)
self.vapi.ip_reassembly_set(
- timeout_ms=100, max_reassemblies=1000,
+ timeout_ms=100,
+ max_reassemblies=1000,
max_reassembly_length=1000,
expire_walk_interval_ms=50,
is_ip6=1,
- type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL)
+ type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL,
+ )
# send fragments #2 and #1 - should be forwarded
self.pg_enable_capture()
@@ -1886,7 +2147,7 @@ class TestIPv6SVReassembly(VppTestCase):
self.assertEqual(sent[Raw].payload, recvd[Raw].payload)
# wait for cleanup
- self.virtual_sleep(.25, "wait before sending rest of fragments")
+ self.virtual_sleep(0.25, "wait before sending rest of fragments")
# send rest of fragments - shouldn't be forwarded
self.pg_enable_capture()
@@ -1895,13 +2156,16 @@ class TestIPv6SVReassembly(VppTestCase):
self.dst_if.assert_nothing_captured()
def test_lru(self):
- """ reassembly reuses LRU element """
+ """reassembly reuses LRU element"""
self.vapi.ip_reassembly_set(
- timeout_ms=1000000, max_reassemblies=1,
+ timeout_ms=1000000,
+ max_reassemblies=1,
max_reassembly_length=1000,
type=VppEnum.vl_api_ip_reass_type_t.IP_REASS_TYPE_SHALLOW_VIRTUAL,
- is_ip6=1, expire_walk_interval_ms=10000)
+ is_ip6=1,
+ expire_walk_interval_ms=10000,
+ )
payload_len = 1000
payload = ""
@@ -1912,15 +2176,17 @@ class TestIPv6SVReassembly(VppTestCase):
packet_count = 10
- fragments = [f
- for i in range(packet_count)
- for p in (Ether(dst=self.src_if.local_mac,
- src=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6,
- dst=self.dst_if.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
- for f in fragment_rfc8200(p, i, payload_len/4)]
+ fragments = [
+ f
+ for i in range(packet_count)
+ for p in (
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
+ for f in fragment_rfc8200(p, i, payload_len / 4)
+ ]
self.pg_enable_capture()
self.src_if.add_stream(fragments)
@@ -1932,55 +2198,71 @@ class TestIPv6SVReassembly(VppTestCase):
self.assertEqual(sent[Raw].payload, recvd[Raw].payload)
def test_one_fragment(self):
- """ whole packet in one fragment processed independently """
- pkt = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) /
- ICMPv6EchoRequest()/Raw('X' * 1600))
+ """whole packet in one fragment processed independently"""
+ pkt = (
+ Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6)
+ / ICMPv6EchoRequest()
+ / Raw("X" * 1600)
+ )
frags = fragment_rfc8200(pkt, 1, 400)
# send a fragment with known id
self.send_and_expect(self.src_if, [frags[0]], self.dst_if)
# send an atomic fragment with same id - should be reassembled
- pkt = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) /
- IPv6ExtHdrFragment(id=1)/ICMPv6EchoRequest())
+ pkt = (
+ Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6)
+ / IPv6ExtHdrFragment(id=1)
+ / ICMPv6EchoRequest()
+ )
rx = self.send_and_expect(self.src_if, [pkt], self.dst_if)
# now forward packets matching original reassembly, should still work
rx = self.send_and_expect(self.src_if, frags[1:], self.dst_if)
def test_bunch_of_fragments(self):
- """ valid fragments followed by rogue fragments and atomic fragment"""
- pkt = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) /
- ICMPv6EchoRequest()/Raw('X' * 1600))
+ """valid fragments followed by rogue fragments and atomic fragment"""
+ pkt = (
+ Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6)
+ / ICMPv6EchoRequest()
+ / Raw("X" * 1600)
+ )
frags = fragment_rfc8200(pkt, 1, 400)
rx = self.send_and_expect(self.src_if, frags, self.dst_if)
- rogue = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) /
- IPv6ExtHdrFragment(id=1, nh=58, offset=608)/Raw('X'*308))
+ rogue = (
+ Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6)
+ / IPv6ExtHdrFragment(id=1, nh=58, offset=608)
+ / Raw("X" * 308)
+ )
- self.send_and_expect(self.src_if, rogue*604, self.dst_if)
+ self.send_and_expect(self.src_if, rogue * 604, self.dst_if)
- pkt = (Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac) /
- IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) /
- IPv6ExtHdrFragment(id=1)/ICMPv6EchoRequest())
+ pkt = (
+ Ether(src=self.src_if.local_mac, dst=self.src_if.remote_mac)
+ / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6)
+ / IPv6ExtHdrFragment(id=1)
+ / ICMPv6EchoRequest()
+ )
rx = self.send_and_expect(self.src_if, [pkt], self.dst_if)
def test_truncated_fragment(self):
- """ truncated fragment """
- pkt = (Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6,
- nh=44, plen=2) /
- IPv6ExtHdrFragment(nh=6))
+ """truncated fragment"""
+ pkt = (
+ Ether(src=self.pg0.local_mac, dst=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6, nh=44, plen=2)
+ / IPv6ExtHdrFragment(nh=6)
+ )
self.send_and_assert_no_replies(self.pg0, [pkt], self.pg0)
class TestIPv4ReassemblyLocalNode(VppTestCase):
- """ IPv4 Reassembly for packets coming to ip4-local node """
+ """IPv4 Reassembly for packets coming to ip4-local node"""
@classmethod
def setUpClass(cls):
@@ -2004,15 +2286,21 @@ class TestIPv4ReassemblyLocalNode(VppTestCase):
super().tearDownClass()
def setUp(self):
- """ Test setup - force timeout on existing reassemblies """
+ """Test setup - force timeout on existing reassemblies"""
super().setUp()
- self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10)
- self.virtual_sleep(.25)
- self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10000)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=0,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10,
+ )
+ self.virtual_sleep(0.25)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=1000000,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10000,
+ )
def tearDown(self):
super().tearDown()
@@ -2030,12 +2318,16 @@ class TestIPv4ReassemblyLocalNode(VppTestCase):
for i in range(0, packet_count):
info = cls.create_packet_info(cls.src_dst_if, cls.src_dst_if)
payload = cls.info_to_payload(info)
- p = (Ether(dst=cls.src_dst_if.local_mac,
- src=cls.src_dst_if.remote_mac) /
- IP(id=info.index, src=cls.src_dst_if.remote_ip4,
- dst=cls.src_dst_if.local_ip4) /
- ICMP(type='echo-request', id=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=cls.src_dst_if.local_mac, src=cls.src_dst_if.remote_mac)
+ / IP(
+ id=info.index,
+ src=cls.src_dst_if.remote_ip4,
+ dst=cls.src_dst_if.local_ip4,
+ )
+ / ICMP(type="echo-request", id=1234)
+ / Raw(payload)
+ )
cls.extend_packet(p, 1518, cls.padding)
info.data = p
@@ -2050,8 +2342,10 @@ class TestIPv4ReassemblyLocalNode(VppTestCase):
fragments_300 = fragment_rfc791(p, 300)
cls.pkt_infos.append((index, fragments_300))
cls.fragments_300 = [x for (_, frags) in cls.pkt_infos for x in frags]
- cls.logger.debug("Fragmented %s packets into %s 300-byte fragments" %
- (len(infos), len(cls.fragments_300)))
+ cls.logger.debug(
+ "Fragmented %s packets into %s 300-byte fragments"
+ % (len(infos), len(cls.fragments_300))
+ )
def verify_capture(self, capture):
"""Verify captured packet stream.
@@ -2084,11 +2378,12 @@ class TestIPv4ReassemblyLocalNode(VppTestCase):
self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
for index in self._packet_infos:
- self.assertIn(index, seen,
- "Packet with packet_index %d not received" % index)
+ self.assertIn(
+ index, seen, "Packet with packet_index %d not received" % index
+ )
def test_reassembly(self):
- """ basic reassembly """
+ """basic reassembly"""
self.pg_enable_capture()
self.src_dst_if.add_stream(self.fragments_300)
@@ -2107,7 +2402,7 @@ class TestIPv4ReassemblyLocalNode(VppTestCase):
class TestFIFReassembly(VppTestCase):
- """ Fragments in fragments reassembly """
+ """Fragments in fragments reassembly"""
@classmethod
def setUpClass(cls):
@@ -2131,27 +2426,41 @@ class TestFIFReassembly(VppTestCase):
super().tearDownClass()
def setUp(self):
- """ Test setup - force timeout on existing reassemblies """
+ """Test setup - force timeout on existing reassemblies"""
super().setUp()
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.src_if.sw_if_index, enable_ip4=True,
- enable_ip6=True)
+ sw_if_index=self.src_if.sw_if_index, enable_ip4=True, enable_ip6=True
+ )
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.dst_if.sw_if_index, enable_ip4=True,
- enable_ip6=True)
- self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10)
- self.vapi.ip_reassembly_set(timeout_ms=0, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10, is_ip6=1)
- self.virtual_sleep(.25)
- self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10000)
- self.vapi.ip_reassembly_set(timeout_ms=1000000, max_reassemblies=1000,
- max_reassembly_length=1000,
- expire_walk_interval_ms=10000, is_ip6=1)
+ sw_if_index=self.dst_if.sw_if_index, enable_ip4=True, enable_ip6=True
+ )
+ self.vapi.ip_reassembly_set(
+ timeout_ms=0,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10,
+ )
+ self.vapi.ip_reassembly_set(
+ timeout_ms=0,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10,
+ is_ip6=1,
+ )
+ self.virtual_sleep(0.25)
+ self.vapi.ip_reassembly_set(
+ timeout_ms=1000000,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10000,
+ )
+ self.vapi.ip_reassembly_set(
+ timeout_ms=1000000,
+ max_reassemblies=1000,
+ max_reassembly_length=1000,
+ expire_walk_interval_ms=10000,
+ is_ip6=1,
+ )
def tearDown(self):
super().tearDown()
@@ -2177,7 +2486,8 @@ class TestFIFReassembly(VppTestCase):
packet_index = payload_info.index
self.assertTrue(
packet_index not in dropped_packet_indexes,
- ppp("Packet received, but should be dropped:", packet))
+ ppp("Packet received, but should be dropped:", packet),
+ )
if packet_index in seen:
raise Exception(ppp("Duplicate packet received", packet))
seen.add(packet_index)
@@ -2193,11 +2503,13 @@ class TestFIFReassembly(VppTestCase):
self.logger.error(ppp("Unexpected or invalid packet:", packet))
raise
for index in self._packet_infos:
- self.assertTrue(index in seen or index in dropped_packet_indexes,
- "Packet with packet_index %d not received" % index)
+ self.assertTrue(
+ index in seen or index in dropped_packet_indexes,
+ "Packet with packet_index %d not received" % index,
+ )
def test_fif4(self):
- """ Fragments in fragments (4o4) """
+ """Fragments in fragments (4o4)"""
# TODO this should be ideally in setUpClass, but then we hit a bug
# with VppIpRoute incorrectly reporting it's present when it's not
@@ -2211,11 +2523,15 @@ class TestFIFReassembly(VppTestCase):
self.gre4.config_ip4()
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.gre4.sw_if_index, enable_ip4=True)
+ sw_if_index=self.gre4.sw_if_index, enable_ip4=True
+ )
- self.route4 = VppIpRoute(self, self.tun_ip4, 32,
- [VppRoutePath(self.src_if.remote_ip4,
- self.src_if.sw_if_index)])
+ self.route4 = VppIpRoute(
+ self,
+ self.tun_ip4,
+ 32,
+ [VppRoutePath(self.src_if.remote_ip4, self.src_if.sw_if_index)],
+ )
self.route4.add_vpp_config()
self.reset_packet_infos()
@@ -2225,28 +2541,33 @@ class TestFIFReassembly(VppTestCase):
# Ethernet header here is only for size calculation, thus it
# doesn't matter how it's initialized. This is to ensure that
# reassembled packet is not > 9000 bytes, so that it's not dropped
- p = (Ether() /
- IP(id=i, src=self.src_if.remote_ip4,
- dst=self.dst_if.remote_ip4) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
+ p = (
+ Ether()
+ / IP(id=i, src=self.src_if.remote_ip4, dst=self.dst_if.remote_ip4)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
size = self.packet_sizes[(i // 2) % len(self.packet_sizes)]
self.extend_packet(p, size, self.padding)
info.data = p[IP] # use only IP part, without ethernet header
- fragments = [x for _, p in self._packet_infos.items()
- for x in fragment_rfc791(p.data, 400)]
+ fragments = [
+ x
+ for _, p in self._packet_infos.items()
+ for x in fragment_rfc791(p.data, 400)
+ ]
- encapped_fragments = \
- [Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IP(src=self.tun_ip4, dst=self.src_if.local_ip4) /
- GRE() /
- p
- for p in fragments]
+ encapped_fragments = [
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IP(src=self.tun_ip4, dst=self.src_if.local_ip4)
+ / GRE()
+ / p
+ for p in fragments
+ ]
- fragmented_encapped_fragments = \
- [x for p in encapped_fragments
- for x in fragment_rfc791(p, 200)]
+ fragmented_encapped_fragments = [
+ x for p in encapped_fragments for x in fragment_rfc791(p, 200)
+ ]
self.src_if.add_stream(fragmented_encapped_fragments)
@@ -2263,7 +2584,7 @@ class TestFIFReassembly(VppTestCase):
self.logger.debug(self.vapi.ppcli("show interface"))
def test_fif6(self):
- """ Fragments in fragments (6o6) """
+ """Fragments in fragments (6o6)"""
# TODO this should be ideally in setUpClass, but then we hit a bug
# with VppIpRoute incorrectly reporting it's present when it's not
# so we need to manually remove the vpp config, thus we cannot have
@@ -2276,12 +2597,15 @@ class TestFIFReassembly(VppTestCase):
self.gre6.config_ip6()
self.vapi.ip_reassembly_enable_disable(
- sw_if_index=self.gre6.sw_if_index, enable_ip6=True)
+ sw_if_index=self.gre6.sw_if_index, enable_ip6=True
+ )
- self.route6 = VppIpRoute(self, self.tun_ip6, 128,
- [VppRoutePath(
- self.src_if.remote_ip6,
- self.src_if.sw_if_index)])
+ self.route6 = VppIpRoute(
+ self,
+ self.tun_ip6,
+ 128,
+ [VppRoutePath(self.src_if.remote_ip6, self.src_if.sw_if_index)],
+ )
self.route6.add_vpp_config()
self.reset_packet_infos()
@@ -2291,34 +2615,41 @@ class TestFIFReassembly(VppTestCase):
# Ethernet header here is only for size calculation, thus it
# doesn't matter how it's initialized. This is to ensure that
# reassembled packet is not > 9000 bytes, so that it's not dropped
- p = (Ether() /
- IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6) /
- UDP(sport=1234, dport=5678) /
- Raw(payload))
+ p = (
+ Ether()
+ / IPv6(src=self.src_if.remote_ip6, dst=self.dst_if.remote_ip6)
+ / UDP(sport=1234, dport=5678)
+ / Raw(payload)
+ )
size = self.packet_sizes[(i // 2) % len(self.packet_sizes)]
self.extend_packet(p, size, self.padding)
info.data = p[IPv6] # use only IPv6 part, without ethernet header
- fragments = [x for _, i in self._packet_infos.items()
- for x in fragment_rfc8200(
- i.data, i.index, 400)]
+ fragments = [
+ x
+ for _, i in self._packet_infos.items()
+ for x in fragment_rfc8200(i.data, i.index, 400)
+ ]
- encapped_fragments = \
- [Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac) /
- IPv6(src=self.tun_ip6, dst=self.src_if.local_ip6) /
- GRE() /
- p
- for p in fragments]
+ encapped_fragments = [
+ Ether(dst=self.src_if.local_mac, src=self.src_if.remote_mac)
+ / IPv6(src=self.tun_ip6, dst=self.src_if.local_ip6)
+ / GRE()
+ / p
+ for p in fragments
+ ]
- fragmented_encapped_fragments = \
- [x for p in encapped_fragments for x in (
+ fragmented_encapped_fragments = [
+ x
+ for p in encapped_fragments
+ for x in (
fragment_rfc8200(
- p,
- 2 * len(self._packet_infos) + p[IPv6ExtHdrFragment].id,
- 200)
- if IPv6ExtHdrFragment in p else [p]
+ p, 2 * len(self._packet_infos) + p[IPv6ExtHdrFragment].id, 200
+ )
+ if IPv6ExtHdrFragment in p
+ else [p]
)
- ]
+ ]
self.src_if.add_stream(fragmented_encapped_fragments)
@@ -2334,5 +2665,5 @@ class TestFIFReassembly(VppTestCase):
self.gre6.remove_vpp_config()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_session.py b/test/test_session.py
index 6c48e5467db..699ebafc386 100644
--- a/test/test_session.py
+++ b/test/test_session.py
@@ -10,7 +10,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
@tag_fixme_vpp_workers
class TestSession(VppTestCase):
- """ Session Test Case """
+ """Session Test Case"""
@classmethod
def setUpClass(cls):
@@ -40,10 +40,12 @@ class TestSession(VppTestCase):
table_id += 1
# Configure namespaces
- self.vapi.app_namespace_add_del(namespace_id="0",
- sw_if_index=self.loop0.sw_if_index)
- self.vapi.app_namespace_add_del(namespace_id="1",
- sw_if_index=self.loop1.sw_if_index)
+ self.vapi.app_namespace_add_del(
+ namespace_id="0", sw_if_index=self.loop0.sw_if_index
+ )
+ self.vapi.app_namespace_add_del(
+ namespace_id="1", sw_if_index=self.loop1.sw_if_index
+ )
def tearDown(self):
for i in self.lo_interfaces:
@@ -55,31 +57,42 @@ class TestSession(VppTestCase):
self.vapi.session_enable_disable(is_enable=1)
def test_segment_manager_alloc(self):
- """ Session Segment Manager Multiple Segment Allocation """
+ """Session Segment Manager Multiple Segment Allocation"""
# Add inter-table routes
- ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=1)])
- ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=0)], table_id=1)
+ ip_t01 = VppIpRoute(
+ self,
+ self.loop1.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)],
+ )
+ ip_t10 = VppIpRoute(
+ self,
+ self.loop0.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)],
+ table_id=1,
+ )
ip_t01.add_vpp_config()
ip_t10.add_vpp_config()
# Start builtin server and client with small private segments
uri = "tcp://" + self.loop0.local_ip4 + "/1234"
- error = self.vapi.cli("test echo server appns 0 fifo-size 64 " +
- "private-segment-size 1m uri " + uri)
+ error = self.vapi.cli(
+ "test echo server appns 0 fifo-size 64 "
+ + "private-segment-size 1m uri "
+ + uri
+ )
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
- error = self.vapi.cli("test echo client nclients 100 appns 1 " +
- "no-output fifo-size 64 syn-timeout 2 " +
- "private-segment-size 1m uri " + uri)
+ error = self.vapi.cli(
+ "test echo client nclients 100 appns 1 "
+ + "no-output fifo-size 64 syn-timeout 2 "
+ + "private-segment-size 1m uri "
+ + uri
+ )
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
@@ -94,7 +107,7 @@ class TestSession(VppTestCase):
@tag_fixme_vpp_workers
class TestSessionUnitTests(VppTestCase):
- """ Session Unit Tests Case """
+ """Session Unit Tests Case"""
@classmethod
def setUpClass(cls):
@@ -109,7 +122,7 @@ class TestSessionUnitTests(VppTestCase):
self.vapi.session_enable_disable(is_enable=1)
def test_session(self):
- """ Session Unit Tests """
+ """Session Unit Tests"""
error = self.vapi.cli("test session all")
if error:
@@ -123,7 +136,7 @@ class TestSessionUnitTests(VppTestCase):
@tag_run_solo
class TestSegmentManagerTests(VppTestCase):
- """ SVM Fifo Unit Tests Case """
+ """SVM Fifo Unit Tests Case"""
@classmethod
def setUpClass(cls):
@@ -137,7 +150,7 @@ class TestSegmentManagerTests(VppTestCase):
super(TestSegmentManagerTests, self).setUp()
def test_segment_manager(self):
- """ Segment manager Tests """
+ """Segment manager Tests"""
error = self.vapi.cli("test segment-manager all")
if error:
@@ -150,7 +163,7 @@ class TestSegmentManagerTests(VppTestCase):
@tag_run_solo
class TestSvmFifoUnitTests(VppTestCase):
- """ SVM Fifo Unit Tests Case """
+ """SVM Fifo Unit Tests Case"""
@classmethod
def setUpClass(cls):
@@ -164,7 +177,7 @@ class TestSvmFifoUnitTests(VppTestCase):
super(TestSvmFifoUnitTests, self).setUp()
def test_svm_fifo(self):
- """ SVM Fifo Unit Tests """
+ """SVM Fifo Unit Tests"""
error = self.vapi.cli("test svm fifo all")
if error:
@@ -174,5 +187,6 @@ class TestSvmFifoUnitTests(VppTestCase):
def tearDown(self):
super(TestSvmFifoUnitTests, self).tearDown()
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_sixrd.py b/test/test_sixrd.py
index 24ff74b8d1c..70ff1fc8769 100644
--- a/test/test_sixrd.py
+++ b/test/test_sixrd.py
@@ -18,7 +18,7 @@ from socket import AF_INET, AF_INET6, inet_pton
class Test6RD(VppTestCase):
- """ 6RD Test Case """
+ """6RD Test Case"""
@classmethod
def setUpClass(cls):
@@ -41,7 +41,7 @@ class Test6RD(VppTestCase):
for n in range(4):
i = self.pg_interfaces[n]
i.admin_up()
- if (n > 1):
+ if n > 1:
i.set_table_ip4(10)
i.set_table_ip6(20)
i.config_ip4()
@@ -82,28 +82,31 @@ class Test6RD(VppTestCase):
self.assertEqual(rx[IPv6].nh, expected[IPv6].nh)
def payload(self, len):
- return 'x' * len
+ return "x" * len
def test_6rd_ip6_to_ip4(self):
- """ ip6 -> ip4 (encap) 6rd test """
+ """ip6 -> ip4 (encap) 6rd test"""
p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
- p_ip6 = IPv6(src="1::1", dst="2002:AC10:0202::1", nh='UDP')
+ p_ip6 = IPv6(src="1::1", dst="2002:AC10:0202::1", nh="UDP")
- rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0,
- ip4_table_id=0,
- ip6_prefix='2002::/16',
- ip4_prefix='0.0.0.0/0',
- ip4_src=self.pg0.local_ip4,
- security_check=True)
+ rv = self.vapi.ipip_6rd_add_tunnel(
+ ip6_table_id=0,
+ ip4_table_id=0,
+ ip6_prefix="2002::/16",
+ ip4_prefix="0.0.0.0/0",
+ ip4_src=self.pg0.local_ip4,
+ security_check=True,
+ )
self.tunnel_index = rv.sw_if_index
self.vapi.cli("show ip6 fib")
p_payload = UDP(sport=1234, dport=1234)
- p = (p_ether / p_ip6 / p_payload)
+ p = p_ether / p_ip6 / p_payload
- p_reply = (IP(src=self.pg0.local_ip4, dst=self.pg1.remote_ip4,
- proto='ipv6') / p_ip6)
+ p_reply = (
+ IP(src=self.pg0.local_ip4, dst=self.pg1.remote_ip4, proto="ipv6") / p_ip6
+ )
rx = self.send_and_expect(self.pg0, p * 10, self.pg1)
for p in rx:
@@ -113,32 +116,37 @@ class Test6RD(VppTestCase):
plen = 1481 - 40 - 8
p_ip6 = IPv6(src="1::1", dst="2002:AC10:0202::1")
p_payload = UDP(sport=1234, dport=1234) / Raw(self.payload(plen))
- p = (p_ether / p_ip6 / p_payload)
+ p = p_ether / p_ip6 / p_payload
- p_reply = (IP(src=self.pg0.local_ip4, dst=self.pg1.remote_ip4,
- proto='ipv6') / p_ip6)
+ p_reply = (
+ IP(src=self.pg0.local_ip4, dst=self.pg1.remote_ip4, proto="ipv6") / p_ip6
+ )
rx = self.send_and_assert_no_replies(self.pg0, p * 10)
self.vapi.ipip_6rd_del_tunnel(self.tunnel_index)
def test_6rd_ip6_to_ip4_vrf(self):
- """ ip6 -> ip4 (encap) 6rd VRF test """
+ """ip6 -> ip4 (encap) 6rd VRF test"""
p_ether = Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
- p_ip6 = IPv6(src="1::1", dst="2002:AC10:0402::1", nh='UDP')
-
- rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=20, ip4_table_id=10,
- ip6_prefix='2002::/16',
- ip4_prefix='0.0.0.0/0',
- ip4_src=self.pg2.local_ip4,
- security_check=True)
+ p_ip6 = IPv6(src="1::1", dst="2002:AC10:0402::1", nh="UDP")
+
+ rv = self.vapi.ipip_6rd_add_tunnel(
+ ip6_table_id=20,
+ ip4_table_id=10,
+ ip6_prefix="2002::/16",
+ ip4_prefix="0.0.0.0/0",
+ ip4_src=self.pg2.local_ip4,
+ security_check=True,
+ )
self.tunnel_index = rv.sw_if_index
self.vapi.cli("show ip6 fib")
p_payload = UDP(sport=1234, dport=1234)
- p = (p_ether / p_ip6 / p_payload)
+ p = p_ether / p_ip6 / p_payload
- p_reply = (IP(src=self.pg2.local_ip4, dst=self.pg3.remote_ip4,
- proto='ipv6') / p_ip6)
+ p_reply = (
+ IP(src=self.pg2.local_ip4, dst=self.pg3.remote_ip4, proto="ipv6") / p_ip6
+ )
rx = self.send_and_expect(self.pg2, p * 10, self.pg3)
for p in rx:
@@ -148,40 +156,47 @@ class Test6RD(VppTestCase):
plen = 1481 - 40 - 8
p_ip6 = IPv6(src="1::1", dst="2002:AC10:0402::1")
p_payload = UDP(sport=1234, dport=1234) / Raw(self.payload(plen))
- p = (p_ether / p_ip6 / p_payload)
+ p = p_ether / p_ip6 / p_payload
- p_reply = (IP(src=self.pg2.local_ip4, dst=self.pg3.remote_ip4,
- proto='ipv6') / p_ip6)
+ p_reply = (
+ IP(src=self.pg2.local_ip4, dst=self.pg3.remote_ip4, proto="ipv6") / p_ip6
+ )
rx = self.send_and_assert_no_replies(self.pg0, p * 10)
self.vapi.ipip_6rd_del_tunnel(self.tunnel_index)
def test_6rd_ip4_to_ip6(self):
- """ ip4 -> ip6 (decap) 6rd test """
-
- rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0,
- ip4_table_id=0,
- ip6_prefix='2002::/16',
- ip4_prefix='0.0.0.0/0',
- ip4_src=self.pg0.local_ip4,
- security_check=True)
+ """ip4 -> ip6 (decap) 6rd test"""
+
+ rv = self.vapi.ipip_6rd_add_tunnel(
+ ip6_table_id=0,
+ ip4_table_id=0,
+ ip6_prefix="2002::/16",
+ ip4_prefix="0.0.0.0/0",
+ ip4_src=self.pg0.local_ip4,
+ security_check=True,
+ )
self.tunnel_index = rv.sw_if_index
rv = self.vapi.ipip_6rd_del_tunnel(rv.sw_if_index)
- rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0,
- ip4_table_id=0,
- ip6_prefix='2002::/16',
- ip4_prefix='0.0.0.0/0',
- ip4_src=self.pg0.local_ip4,
- security_check=True)
+ rv = self.vapi.ipip_6rd_add_tunnel(
+ ip6_table_id=0,
+ ip4_table_id=0,
+ ip6_prefix="2002::/16",
+ ip4_prefix="0.0.0.0/0",
+ ip4_src=self.pg0.local_ip4,
+ security_check=True,
+ )
self.tunnel_index = rv.sw_if_index
- p_ip6 = (IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) /
- UDP(sport=1234, dport=1234))
+ p_ip6 = IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) / UDP(
+ sport=1234, dport=1234
+ )
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4) /
- p_ip6)
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4)
+ / p_ip6
+ )
p_reply = p_ip6
@@ -191,32 +206,38 @@ class Test6RD(VppTestCase):
self.vapi.ipip_6rd_del_tunnel(self.tunnel_index)
def test_6rd_ip4_to_ip6_vrf(self):
- """ ip4 -> ip6 (decap) 6rd VRF test """
-
- rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=20,
- ip4_table_id=10,
- ip6_prefix='2002::/16',
- ip4_prefix='0.0.0.0/0',
- ip4_src=self.pg2.local_ip4,
- security_check=True)
+ """ip4 -> ip6 (decap) 6rd VRF test"""
+
+ rv = self.vapi.ipip_6rd_add_tunnel(
+ ip6_table_id=20,
+ ip4_table_id=10,
+ ip6_prefix="2002::/16",
+ ip4_prefix="0.0.0.0/0",
+ ip4_src=self.pg2.local_ip4,
+ security_check=True,
+ )
self.tunnel_index = rv.sw_if_index
rv = self.vapi.ipip_6rd_del_tunnel(rv.sw_if_index)
- rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=20,
- ip4_table_id=10,
- ip6_prefix='2002::/16',
- ip4_prefix='0.0.0.0/0',
- ip4_src=self.pg2.local_ip4,
- security_check=True)
+ rv = self.vapi.ipip_6rd_add_tunnel(
+ ip6_table_id=20,
+ ip4_table_id=10,
+ ip6_prefix="2002::/16",
+ ip4_prefix="0.0.0.0/0",
+ ip4_src=self.pg2.local_ip4,
+ security_check=True,
+ )
self.tunnel_index = rv.sw_if_index
self.vapi.sw_interface_set_table(self.tunnel_index, 1, 20)
- p_ip6 = (IPv6(src="2002:AC10:0402::1", dst=self.pg3.remote_ip6) /
- UDP(sport=1234, dport=1234))
+ p_ip6 = IPv6(src="2002:AC10:0402::1", dst=self.pg3.remote_ip6) / UDP(
+ sport=1234, dport=1234
+ )
- p = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg3.remote_ip4, dst=self.pg2.local_ip4) /
- p_ip6)
+ p = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg3.remote_ip4, dst=self.pg2.local_ip4)
+ / p_ip6
+ )
p_reply = p_ip6
@@ -227,39 +248,45 @@ class Test6RD(VppTestCase):
self.vapi.ipip_6rd_del_tunnel(self.tunnel_index)
def test_6rd_ip4_to_ip6_multiple(self):
- """ ip4 -> ip6 (decap) 6rd test """
+ """ip4 -> ip6 (decap) 6rd test"""
self.tunnel_index = []
- rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0,
- ip4_table_id=0,
- ip6_prefix='2002::/16',
- ip4_prefix='0.0.0.0/0',
- ip4_src=self.pg0.local_ip4,
- security_check=True)
+ rv = self.vapi.ipip_6rd_add_tunnel(
+ ip6_table_id=0,
+ ip4_table_id=0,
+ ip6_prefix="2002::/16",
+ ip4_prefix="0.0.0.0/0",
+ ip4_src=self.pg0.local_ip4,
+ security_check=True,
+ )
self.tunnel_index.append(rv.sw_if_index)
- rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0,
- ip4_table_id=0,
- ip6_prefix='2003::/16',
- ip4_prefix='0.0.0.0/0',
- ip4_src=self.pg1.local_ip4,
- security_check=True)
+ rv = self.vapi.ipip_6rd_add_tunnel(
+ ip6_table_id=0,
+ ip4_table_id=0,
+ ip6_prefix="2003::/16",
+ ip4_prefix="0.0.0.0/0",
+ ip4_src=self.pg1.local_ip4,
+ security_check=True,
+ )
self.tunnel_index.append(rv.sw_if_index)
self.vapi.cli("show ip6 fib")
p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
p_ip4 = IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4)
- p_ip6_1 = (IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) /
- UDP(sport=1234, dport=1234))
- p_ip6_2 = (IPv6(src="2003:AC10:0202::1", dst=self.pg1.remote_ip6) /
- UDP(sport=1234, dport=1234))
-
- p = (p_ether / p_ip4 / p_ip6_1)
+ p_ip6_1 = IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) / UDP(
+ sport=1234, dport=1234
+ )
+ p_ip6_2 = IPv6(src="2003:AC10:0202::1", dst=self.pg1.remote_ip6) / UDP(
+ sport=1234, dport=1234
+ )
+
+ p = p_ether / p_ip4 / p_ip6_1
rx = self.send_and_expect(self.pg0, p * 10, self.pg1)
for p in rx:
self.validate_4in6(p, p_ip6_1)
- p = (p_ether / p_ip4 / p_ip6_2)
+ p = p_ether / p_ip4 / p_ip6_2
rx = self.send_and_expect(self.pg0, p * 10, self.pg1)
for p in rx:
self.validate_4in6(p, p_ip6_2)
@@ -267,49 +294,57 @@ class Test6RD(VppTestCase):
self.vapi.ipip_6rd_del_tunnel(i)
def test_6rd_ip4_to_ip6_suffix(self):
- """ ip4 -> ip6 (decap) 6rd test """
-
- rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0,
- ip4_table_id=0,
- ip6_prefix='2002::/16',
- ip4_prefix='172.0.0.0/8',
- ip4_src=self.pg0.local_ip4,
- security_check=True)
+ """ip4 -> ip6 (decap) 6rd test"""
+
+ rv = self.vapi.ipip_6rd_add_tunnel(
+ ip6_table_id=0,
+ ip4_table_id=0,
+ ip6_prefix="2002::/16",
+ ip4_prefix="172.0.0.0/8",
+ ip4_src=self.pg0.local_ip4,
+ security_check=True,
+ )
self.tunnel_index = rv.sw_if_index
self.vapi.cli("show ip6 fib")
p_ether = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
p_ip4 = IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4)
- p_ip6 = (IPv6(src="2002:1002:0200::1", dst=self.pg1.remote_ip6) /
- UDP(sport=1234, dport=1234))
+ p_ip6 = IPv6(src="2002:1002:0200::1", dst=self.pg1.remote_ip6) / UDP(
+ sport=1234, dport=1234
+ )
- p = (p_ether / p_ip4 / p_ip6)
+ p = p_ether / p_ip4 / p_ip6
rx = self.send_and_expect(self.pg0, p * 10, self.pg1)
for p in rx:
self.validate_4in6(p, p_ip6)
self.vapi.ipip_6rd_del_tunnel(self.tunnel_index)
def test_6rd_ip4_to_ip6_sec_check(self):
- """ ip4 -> ip6 (decap) security check 6rd test """
-
- rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0,
- ip4_table_id=0,
- ip6_prefix='2002::/16',
- ip4_prefix='0.0.0.0/0',
- ip4_src=self.pg0.local_ip4,
- security_check=True)
+ """ip4 -> ip6 (decap) security check 6rd test"""
+
+ rv = self.vapi.ipip_6rd_add_tunnel(
+ ip6_table_id=0,
+ ip4_table_id=0,
+ ip6_prefix="2002::/16",
+ ip4_prefix="0.0.0.0/0",
+ ip4_src=self.pg0.local_ip4,
+ security_check=True,
+ )
self.tunnel_index = rv.sw_if_index
self.vapi.cli("show ip6 fib")
- p_ip6 = (IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) /
- UDP(sport=1234, dport=1234))
- p_ip6_fail = (IPv6(src="2002:DEAD:0202::1", dst=self.pg1.remote_ip6) /
- UDP(sport=1234, dport=1234))
-
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4) /
- p_ip6)
+ p_ip6 = IPv6(src="2002:AC10:0202::1", dst=self.pg1.remote_ip6) / UDP(
+ sport=1234, dport=1234
+ )
+ p_ip6_fail = IPv6(src="2002:DEAD:0202::1", dst=self.pg1.remote_ip6) / UDP(
+ sport=1234, dport=1234
+ )
+
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4)
+ / p_ip6
+ )
p_reply = p_ip6
@@ -317,55 +352,62 @@ class Test6RD(VppTestCase):
for p in rx:
self.validate_4in6(p, p_reply)
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4) /
- p_ip6_fail)
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg0.local_ip4)
+ / p_ip6_fail
+ )
rx = self.send_and_assert_no_replies(self.pg0, p * 10)
self.vapi.ipip_6rd_del_tunnel(self.tunnel_index)
def test_6rd_bgp_tunnel(self):
- """ 6rd BGP tunnel """
+ """6rd BGP tunnel"""
- rv = self.vapi.ipip_6rd_add_tunnel(ip6_table_id=0,
- ip4_table_id=0,
- ip6_prefix='2002::/16',
- ip4_prefix='0.0.0.0/0',
- ip4_src=self.pg0.local_ip4,
- security_check=False)
+ rv = self.vapi.ipip_6rd_add_tunnel(
+ ip6_table_id=0,
+ ip4_table_id=0,
+ ip6_prefix="2002::/16",
+ ip4_prefix="0.0.0.0/0",
+ ip4_src=self.pg0.local_ip4,
+ security_check=False,
+ )
self.tunnel_index = rv.sw_if_index
- default_route = VppIpRoute(self, "DEAD::", 16,
- [VppRoutePath("2002:0808:0808::",
- self.tunnel_index)])
+ default_route = VppIpRoute(
+ self, "DEAD::", 16, [VppRoutePath("2002:0808:0808::", self.tunnel_index)]
+ )
default_route.add_vpp_config()
- ip4_route = VppIpRoute(self, "8.0.0.0", 8,
- [VppRoutePath(self.pg1.remote_ip4, 0xFFFFFFFF)])
+ ip4_route = VppIpRoute(
+ self, "8.0.0.0", 8, [VppRoutePath(self.pg1.remote_ip4, 0xFFFFFFFF)]
+ )
ip4_route.add_vpp_config()
# Via recursive route 6 -> 4
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src="1::1", dst="DEAD:BEEF::1") /
- UDP(sport=1234, dport=1234))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src="1::1", dst="DEAD:BEEF::1")
+ / UDP(sport=1234, dport=1234)
+ )
- p_reply = (IP(src=self.pg0.local_ip4, dst="8.8.8.8",
- proto='ipv6') /
- IPv6(src='1::1', dst='DEAD:BEEF::1', nh='UDP'))
+ p_reply = IP(src=self.pg0.local_ip4, dst="8.8.8.8", proto="ipv6") / IPv6(
+ src="1::1", dst="DEAD:BEEF::1", nh="UDP"
+ )
rx = self.send_and_expect(self.pg0, p * 10, self.pg1)
for p in rx:
self.validate_6in4(p, p_reply)
# Via recursive route 4 -> 6 (Security check must be disabled)
- p_ip6 = (IPv6(src="DEAD:BEEF::1", dst=self.pg1.remote_ip6) /
- UDP(sport=1234, dport=1234))
- p = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="8.8.8.8", dst=self.pg0.local_ip4) /
- p_ip6)
+ p_ip6 = IPv6(src="DEAD:BEEF::1", dst=self.pg1.remote_ip6) / UDP(
+ sport=1234, dport=1234
+ )
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="8.8.8.8", dst=self.pg0.local_ip4)
+ / p_ip6
+ )
p_reply = p_ip6
@@ -377,5 +419,5 @@ class Test6RD(VppTestCase):
self.vapi.ipip_6rd_del_tunnel(self.tunnel_index)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_span.py b/test/test_span.py
index ecefe153706..3572d64e79c 100644
--- a/test/test_span.py
+++ b/test/test_span.py
@@ -16,19 +16,19 @@ from collections import namedtuple
from vpp_papi import VppEnum
-Tag = namedtuple('Tag', ['dot1', 'vlan'])
+Tag = namedtuple("Tag", ["dot1", "vlan"])
DOT1AD = 0x88A8
DOT1Q = 0x8100
class TestSpan(VppTestCase):
- """ SPAN Test Case """
+ """SPAN Test Case"""
@classmethod
def setUpClass(cls):
super(TestSpan, cls).setUpClass()
# Test variables
- cls.pkts_per_burst = 257 # Number of packets per burst
+ cls.pkts_per_burst = 257 # Number of packets per burst
# create 3 pg interfaces
cls.create_pg_interfaces(range(3))
@@ -56,8 +56,9 @@ class TestSpan(VppTestCase):
def setUp(self):
super(TestSpan, self).setUp()
- self.vxlan = VppVxlanTunnel(self, src=self.pg2.local_ip4,
- dst=self.pg2.remote_ip4, vni=1111)
+ self.vxlan = VppVxlanTunnel(
+ self, src=self.pg2.local_ip4, dst=self.pg2.remote_ip4, vni=1111
+ )
self.vxlan.add_vpp_config()
self.reset_packet_infos()
@@ -72,8 +73,9 @@ class TestSpan(VppTestCase):
self.vapi.sw_interface_set_l2_xconnect(b, a, enable=is_add)
def bridge(self, sw_if_index, is_add=1):
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=sw_if_index,
- bd_id=self.bd_id, enable=is_add)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=sw_if_index, bd_id=self.bd_id, enable=is_add
+ )
def _remove_tag(self, packet, vlan, tag_type):
self.assertEqual(packet.type, tag_type)
@@ -145,10 +147,12 @@ class TestSpan(VppTestCase):
for i in range(0, self.pkts_per_burst):
payload = "span test"
size = packet_sizes[int((i / 2) % len(packet_sizes))]
- p = (Ether(src=src_if.local_mac, dst=dst_mac) /
- IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4) /
- UDP(sport=10000 + src_if.sw_if_index * 1000 + i, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(src=src_if.local_mac, dst=dst_mac)
+ / IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4)
+ / UDP(sport=10000 + src_if.sw_if_index * 1000 + i, dport=1234)
+ / Raw(payload)
+ )
if do_dot1:
p = self.sub_if.add_dot1_layer(p)
self.extend_packet(p, size)
@@ -156,9 +160,12 @@ class TestSpan(VppTestCase):
return pkts
def verify_capture(self, cap1, cap2):
- self.assertEqual(len(cap1), len(cap2),
- "Different number of sent and mirrored packets :"
- "%u != %u" % (len(cap1), len(cap2)))
+ self.assertEqual(
+ len(cap1),
+ len(cap2),
+ "Different number of sent and mirrored packets :"
+ "%u != %u" % (len(cap1), len(cap2)),
+ )
pkts1 = [(pkt[Ether] / pkt[IP] / pkt[UDP]) for pkt in cap1]
pkts2 = [(pkt[Ether] / pkt[IP] / pkt[UDP]) for pkt in cap2]
@@ -166,7 +173,7 @@ class TestSpan(VppTestCase):
self.assertEqual(pkts1.sort(), pkts2.sort())
def test_device_span(self):
- """ SPAN device rx mirror """
+ """SPAN device rx mirror"""
# Create bi-directional cross-connects between pg0 and pg1
self.xconnect(self.pg0.sw_if_index, self.pg1.sw_if_index)
@@ -176,7 +183,8 @@ class TestSpan(VppTestCase):
# Enable SPAN on pg0 (mirrored to pg2)
self.vapi.sw_interface_span_enable_disable(
- self.pg0.sw_if_index, self.pg2.sw_if_index)
+ self.pg0.sw_if_index, self.pg2.sw_if_index
+ )
self.logger.info(self.vapi.ppcli("show interface span"))
# Enable packet capturing and start packet sending
@@ -190,13 +198,14 @@ class TestSpan(VppTestCase):
# Disable SPAN on pg0 (mirrored to pg2)
self.vapi.sw_interface_span_enable_disable(
- self.pg0.sw_if_index, self.pg2.sw_if_index, state=0)
+ self.pg0.sw_if_index, self.pg2.sw_if_index, state=0
+ )
self.xconnect(self.pg0.sw_if_index, self.pg1.sw_if_index, is_add=0)
self.verify_capture(pg1_pkts, pg2_pkts)
def test_span_l2_rx(self):
- """ SPAN l2 rx mirror """
+ """SPAN l2 rx mirror"""
self.sub_if.admin_up()
@@ -204,13 +213,13 @@ class TestSpan(VppTestCase):
# Create bi-directional cross-connects between pg0 subif and pg1
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index)
# Create incoming packet streams for packet-generator interfaces
- pkts = self.create_stream(
- self.pg0, self.pg_if_packet_sizes, do_dot1=True)
+ pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True)
self.pg0.add_stream(pkts)
# Enable SPAN on pg0 (mirrored to pg2)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1)
+ self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1
+ )
self.logger.info(self.vapi.ppcli("show interface span"))
# Enable packet capturing and start packet sending
@@ -225,29 +234,29 @@ class TestSpan(VppTestCase):
# Disable SPAN on pg0 (mirrored to pg2)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1)
+ self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1
+ )
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0)
self.verify_capture(pg1_pkts, pg2_pkts)
def test_span_l2_rx_dst_vxlan(self):
- """ SPAN l2 rx mirror into vxlan """
+ """SPAN l2 rx mirror into vxlan"""
self.sub_if.admin_up()
- self.vapi.sw_interface_set_flags(self.vxlan.sw_if_index,
- flags=1)
+ self.vapi.sw_interface_set_flags(self.vxlan.sw_if_index, flags=1)
self.bridge(self.vxlan.sw_if_index, is_add=1)
# Create bi-directional cross-connects between pg0 subif and pg1
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index)
# Create incoming packet streams for packet-generator interfaces
- pkts = self.create_stream(
- self.pg0, self.pg_if_packet_sizes, do_dot1=True)
+ pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True)
self.pg0.add_stream(pkts)
# Enable SPAN on pg0 sub if (mirrored to vxlan)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.vxlan.sw_if_index, is_l2=1)
+ self.sub_if.sw_if_index, self.vxlan.sw_if_index, is_l2=1
+ )
self.logger.info(self.vapi.ppcli("show interface span"))
# Enable packet capturing and start packet sending
@@ -262,20 +271,23 @@ class TestSpan(VppTestCase):
self.bridge(self.vxlan.sw_if_index, is_add=0)
# Disable SPAN on pg0 sub if (mirrored to vxlan)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.vxlan.sw_if_index, state=0, is_l2=1)
+ self.sub_if.sw_if_index, self.vxlan.sw_if_index, state=0, is_l2=1
+ )
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0)
self.verify_capture(pg1_pkts, pg2_pkts)
def test_span_l2_rx_dst_gre_erspan(self):
- """ SPAN l2 rx mirror into gre-erspan """
+ """SPAN l2 rx mirror into gre-erspan"""
self.sub_if.admin_up()
- gre_if = VppGreInterface(self, self.pg2.local_ip4,
- self.pg2.remote_ip4,
- session=543,
- type=(VppEnum.vl_api_gre_tunnel_type_t.
- GRE_API_TUNNEL_TYPE_ERSPAN))
+ gre_if = VppGreInterface(
+ self,
+ self.pg2.local_ip4,
+ self.pg2.remote_ip4,
+ session=543,
+ type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_ERSPAN),
+ )
gre_if.add_vpp_config()
gre_if.admin_up()
@@ -285,13 +297,13 @@ class TestSpan(VppTestCase):
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=1)
# Create incoming packet streams for packet-generator interfaces
- pkts = self.create_stream(
- self.pg0, self.pg_if_packet_sizes, do_dot1=True)
+ pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True)
self.pg0.add_stream(pkts)
# Enable SPAN on pg0 sub if (mirrored to gre-erspan)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, gre_if.sw_if_index, is_l2=1)
+ self.sub_if.sw_if_index, gre_if.sw_if_index, is_l2=1
+ )
# Enable packet capturing and start packet sending
self.pg_enable_capture(self.pg_interfaces)
@@ -302,28 +314,33 @@ class TestSpan(VppTestCase):
pg1_pkts = self.pg1.get_capture(n_pkts)
pg2_pkts = self.pg2.get_capture(n_pkts)
- def decap(p): return self.decap_erspan(p, session=543)
+ def decap(p):
+ return self.decap_erspan(p, session=543)
+
pg2_decaped = [decap(p) for p in pg2_pkts]
self.bridge(gre_if.sw_if_index, is_add=0)
# Disable SPAN on pg0 sub if
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, gre_if.sw_if_index, state=0, is_l2=1)
+ self.sub_if.sw_if_index, gre_if.sw_if_index, state=0, is_l2=1
+ )
gre_if.remove_vpp_config()
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0)
self.verify_capture(pg1_pkts, pg2_decaped)
def test_span_l2_rx_dst_gre_subif_vtr(self):
- """ SPAN l2 rx mirror into gre-subif+vtr """
+ """SPAN l2 rx mirror into gre-subif+vtr"""
self.sub_if.admin_up()
- gre_if = VppGreInterface(self, self.pg2.local_ip4,
- self.pg2.remote_ip4,
- type=(VppEnum.vl_api_gre_tunnel_type_t.
- GRE_API_TUNNEL_TYPE_TEB))
+ gre_if = VppGreInterface(
+ self,
+ self.pg2.local_ip4,
+ self.pg2.remote_ip4,
+ type=(VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_TEB),
+ )
gre_if.add_vpp_config()
gre_if.admin_up()
@@ -337,13 +354,13 @@ class TestSpan(VppTestCase):
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=1)
# Create incoming packet streams for packet-generator interfaces
- pkts = self.create_stream(
- self.pg0, self.pg_if_packet_sizes, do_dot1=True)
+ pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True)
self.pg0.add_stream(pkts)
# Enable SPAN on pg0 sub if (mirrored to gre sub if)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, gre_sub_if.sw_if_index, is_l2=1)
+ self.sub_if.sw_if_index, gre_sub_if.sw_if_index, is_l2=1
+ )
# Enable packet capturing and start packet sending
self.pg_enable_capture(self.pg_interfaces)
@@ -354,22 +371,24 @@ class TestSpan(VppTestCase):
pg1_pkts = self.pg1.get_capture(n_pkts)
pg2_pkts = self.pg2.get_capture(n_pkts)
- def decap(p): return self.remove_tags(
- self.decap_gre(p), [Tag(dot1=DOT1Q, vlan=500)])
+ def decap(p):
+ return self.remove_tags(self.decap_gre(p), [Tag(dot1=DOT1Q, vlan=500)])
+
pg2_decaped = [decap(p) for p in pg2_pkts]
self.bridge(gre_sub_if.sw_if_index, is_add=0)
# Disable SPAN on pg0 sub if
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, gre_sub_if.sw_if_index, state=0, is_l2=1)
+ self.sub_if.sw_if_index, gre_sub_if.sw_if_index, state=0, is_l2=1
+ )
gre_if.remove_vpp_config()
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0)
self.verify_capture(pg1_pkts, pg2_decaped)
def test_span_l2_rx_dst_1q_vtr(self):
- """ SPAN l2 rx mirror into 1q subif+vtr """
+ """SPAN l2 rx mirror into 1q subif+vtr"""
self.sub_if.admin_up()
self.vlan_sub_if.admin_up()
@@ -379,12 +398,12 @@ class TestSpan(VppTestCase):
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=1)
# Create incoming packet streams for packet-generator interfaces
- pkts = self.create_stream(
- self.pg0, self.pg_if_packet_sizes, do_dot1=True)
+ pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True)
self.pg0.add_stream(pkts)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.vlan_sub_if.sw_if_index, is_l2=1)
+ self.sub_if.sw_if_index, self.vlan_sub_if.sw_if_index, is_l2=1
+ )
# Enable packet capturing and start packet sending
self.pg_enable_capture(self.pg_interfaces)
@@ -394,20 +413,21 @@ class TestSpan(VppTestCase):
n_pkts = len(pkts)
pg1_pkts = self.pg1.get_capture(n_pkts)
pg2_pkts = self.pg2.get_capture(n_pkts)
- pg2_untagged = [self.remove_tags(p, [Tag(dot1=DOT1Q, vlan=300)])
- for p in pg2_pkts]
+ pg2_untagged = [
+ self.remove_tags(p, [Tag(dot1=DOT1Q, vlan=300)]) for p in pg2_pkts
+ ]
self.bridge(self.vlan_sub_if.sw_if_index, is_add=0)
# Disable SPAN on pg0 sub if (mirrored to vxlan)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.vlan_sub_if.sw_if_index, state=0,
- is_l2=1)
+ self.sub_if.sw_if_index, self.vlan_sub_if.sw_if_index, state=0, is_l2=1
+ )
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0)
self.verify_capture(pg1_pkts, pg2_untagged)
def test_span_l2_rx_dst_1ad_vtr(self):
- """ SPAN l2 rx mirror into 1ad subif+vtr """
+ """SPAN l2 rx mirror into 1ad subif+vtr"""
self.sub_if.admin_up()
self.qinq_sub_if.admin_up()
@@ -417,12 +437,12 @@ class TestSpan(VppTestCase):
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=1)
# Create incoming packet streams for packet-generator interfaces
- pkts = self.create_stream(
- self.pg0, self.pg_if_packet_sizes, do_dot1=True)
+ pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True)
self.pg0.add_stream(pkts)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.qinq_sub_if.sw_if_index, is_l2=1)
+ self.sub_if.sw_if_index, self.qinq_sub_if.sw_if_index, is_l2=1
+ )
# Enable packet capturing and start packet sending
self.pg_enable_capture(self.pg_interfaces)
@@ -432,34 +452,35 @@ class TestSpan(VppTestCase):
n_pkts = len(pkts)
pg1_pkts = self.pg1.get_capture(n_pkts)
pg2_pkts = self.pg2.get_capture(n_pkts)
- pg2_untagged = [self.remove_tags(p, [Tag(dot1=DOT1AD, vlan=400),
- Tag(dot1=DOT1Q, vlan=500)])
- for p in pg2_pkts]
+ pg2_untagged = [
+ self.remove_tags(p, [Tag(dot1=DOT1AD, vlan=400), Tag(dot1=DOT1Q, vlan=500)])
+ for p in pg2_pkts
+ ]
self.bridge(self.qinq_sub_if.sw_if_index, is_add=0)
# Disable SPAN on pg0 sub if (mirrored to vxlan)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.qinq_sub_if.sw_if_index, state=0,
- is_l2=1)
+ self.sub_if.sw_if_index, self.qinq_sub_if.sw_if_index, state=0, is_l2=1
+ )
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0)
self.verify_capture(pg1_pkts, pg2_untagged)
def test_l2_tx_span(self):
- """ SPAN l2 tx mirror """
+ """SPAN l2 tx mirror"""
self.sub_if.admin_up()
self.bridge(self.pg2.sw_if_index)
# Create bi-directional cross-connects between pg0 and pg1
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index)
# Create incoming packet streams for packet-generator interfaces
- pkts = self.create_stream(
- self.pg0, self.pg_if_packet_sizes, do_dot1=True)
+ pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True)
self.pg0.add_stream(pkts)
# Enable SPAN on pg1 (mirrored to pg2)
self.vapi.sw_interface_span_enable_disable(
- self.pg1.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=2)
+ self.pg1.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=2
+ )
self.logger.info(self.vapi.ppcli("show interface span"))
# Enable packet capturing and start packet sending
@@ -473,13 +494,14 @@ class TestSpan(VppTestCase):
self.bridge(self.pg2.sw_if_index, is_add=0)
# Disable SPAN on pg0 (mirrored to pg2)
self.vapi.sw_interface_span_enable_disable(
- self.pg1.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1)
+ self.pg1.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1
+ )
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0)
self.verify_capture(pg1_pkts, pg2_pkts)
def test_l2_rx_tx_span(self):
- """ SPAN l2 rx tx mirror """
+ """SPAN l2 rx tx mirror"""
self.sub_if.admin_up()
self.bridge(self.pg2.sw_if_index)
@@ -487,16 +509,15 @@ class TestSpan(VppTestCase):
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index)
# Create incoming packet streams for packet-generator interfaces
- pg0_pkts = self.create_stream(
- self.pg0, self.pg_if_packet_sizes, do_dot1=True)
+ pg0_pkts = self.create_stream(self.pg0, self.pg_if_packet_sizes, do_dot1=True)
self.pg0.add_stream(pg0_pkts)
- pg1_pkts = self.create_stream(
- self.pg1, self.pg_if_packet_sizes, do_dot1=False)
+ pg1_pkts = self.create_stream(self.pg1, self.pg_if_packet_sizes, do_dot1=False)
self.pg1.add_stream(pg1_pkts)
# Enable SPAN on pg0 (mirrored to pg2)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=3)
+ self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=3
+ )
self.logger.info(self.vapi.ppcli("show interface span"))
# Enable packet capturing and start packet sending
@@ -515,34 +536,40 @@ class TestSpan(VppTestCase):
self.bridge(self.pg2.sw_if_index, is_add=0)
# Disable SPAN on pg0 (mirrored to pg2)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1)
+ self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1
+ )
self.xconnect(self.sub_if.sw_if_index, self.pg1.sw_if_index, is_add=0)
self.verify_capture(pg0_pkts + pg1_pkts, pg2_pkts)
def test_l2_bcast_mirror(self):
- """ SPAN l2 broadcast mirror """
+ """SPAN l2 broadcast mirror"""
self.sub_if.admin_up()
self.bridge(self.pg2.sw_if_index)
# Create bi-directional cross-connects between pg0 and pg1
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.sub_if.sw_if_index, bd_id=99, enable=1)
+ rx_sw_if_index=self.sub_if.sw_if_index, bd_id=99, enable=1
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg1.sw_if_index, bd_id=99, enable=1)
+ rx_sw_if_index=self.pg1.sw_if_index, bd_id=99, enable=1
+ )
# Create incoming packet streams for packet-generator interfaces
pg0_pkts = self.create_stream(
- self.pg0, self.pg_if_packet_sizes, do_dot1=True, bcast=True)
+ self.pg0, self.pg_if_packet_sizes, do_dot1=True, bcast=True
+ )
self.pg0.add_stream(pg0_pkts)
pg1_pkts = self.create_stream(
- self.pg1, self.pg_if_packet_sizes, do_dot1=False, bcast=True)
+ self.pg1, self.pg_if_packet_sizes, do_dot1=False, bcast=True
+ )
self.pg1.add_stream(pg1_pkts)
# Enable SPAN on pg0 (mirrored to pg2)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=3)
+ self.sub_if.sw_if_index, self.pg2.sw_if_index, is_l2=1, state=3
+ )
self.logger.info(self.vapi.ppcli("show interface span"))
# Enable packet capturing and start packet sending
@@ -560,15 +587,18 @@ class TestSpan(VppTestCase):
self.bridge(self.pg2.sw_if_index, is_add=0)
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.sub_if.sw_if_index, bd_id=99, enable=0)
+ rx_sw_if_index=self.sub_if.sw_if_index, bd_id=99, enable=0
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg1.sw_if_index, bd_id=99, enable=0)
+ rx_sw_if_index=self.pg1.sw_if_index, bd_id=99, enable=0
+ )
# Disable SPAN on pg0 (mirrored to pg2)
self.vapi.sw_interface_span_enable_disable(
- self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1)
+ self.sub_if.sw_if_index, self.pg2.sw_if_index, state=0, is_l2=1
+ )
self.verify_capture(pg0_pkts + pg1_pkts, pg2_pkts)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_sparse_vec.py b/test/test_sparse_vec.py
index a683faefd57..6b1cb2885e0 100644
--- a/test/test_sparse_vec.py
+++ b/test/test_sparse_vec.py
@@ -7,7 +7,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
class TestSparseVec(VppTestCase):
- """ SparseVec Test Cases """
+ """SparseVec Test Cases"""
@classmethod
def setUpClass(cls):
@@ -24,11 +24,12 @@ class TestSparseVec(VppTestCase):
super(TestSparseVec, self).tearDown()
def test_string_unittest(self):
- """ SparseVec unit tests """
+ """SparseVec unit tests"""
error = self.vapi.cli("test sparse_vec")
if error.find("failed") != -1:
self.logger.critical("FAILURE in the sparse_vec test")
self.assertNotIn("failed", error)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_srmpls.py b/test/test_srmpls.py
index b9abeaeffec..bac3eff2542 100644
--- a/test/test_srmpls.py
+++ b/test/test_srmpls.py
@@ -5,8 +5,14 @@ import socket
from framework import VppTestCase, VppTestRunner
from vpp_ip import DpoProto
-from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsRoute, \
- VppIpTable, VppMplsTable, VppMplsLabel
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ VppMplsRoute,
+ VppIpTable,
+ VppMplsTable,
+ VppMplsLabel,
+)
from vpp_mpls_tunnel_interface import VppMPLSTunnelInterface
from scapy.packet import Raw
@@ -47,7 +53,7 @@ def verify_mpls_stack(tst, rx, mpls_labels):
class TestSRMPLS(VppTestCase):
- """ SR-MPLS Test Case """
+ """SR-MPLS Test Case"""
@classmethod
def setUpClass(cls):
@@ -94,17 +100,19 @@ class TestSRMPLS(VppTestCase):
for i in range(0, 257):
info = self.create_packet_info(src_if, src_if)
payload = self.info_to_payload(info)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- IP(src=src_if.remote_ip4, dst=dst_ip,
- ttl=ip_ttl, tos=ip_dscp) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / IP(src=src_if.remote_ip4, dst=dst_ip, ttl=ip_ttl, tos=ip_dscp)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
info.data = p.copy()
pkts.append(p)
return pkts
- def verify_capture_labelled_ip4(self, src_if, capture, sent,
- mpls_labels, ip_ttl=None):
+ def verify_capture_labelled_ip4(
+ self, src_if, capture, sent, mpls_labels, ip_ttl=None
+ ):
try:
capture = verify_filter(capture, sent)
@@ -152,15 +160,21 @@ class TestSRMPLS(VppTestCase):
raise
def test_sr_mpls(self):
- """ SR MPLS """
+ """SR MPLS"""
#
# A simple MPLS xconnect - neos label in label out
#
- route_32_eos = VppMplsRoute(self, 32, 0,
- [VppRoutePath(self.pg0.remote_ip4,
- self.pg0.sw_if_index,
- labels=[VppMplsLabel(32)])])
+ route_32_eos = VppMplsRoute(
+ self,
+ 32,
+ 0,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip4, self.pg0.sw_if_index, labels=[VppMplsLabel(32)]
+ )
+ ],
+ )
route_32_eos.add_vpp_config()
#
@@ -171,32 +185,38 @@ class TestSRMPLS(VppTestCase):
#
# A labeled IP route that resolves thru the binding SID
#
- ip_10_0_0_1 = VppIpRoute(self, "10.0.0.1", 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_via_label=999,
- labels=[VppMplsLabel(55)])])
+ ip_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.1",
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0", 0xFFFFFFFF, nh_via_label=999, labels=[VppMplsLabel(55)]
+ )
+ ],
+ )
ip_10_0_0_1.add_vpp_config()
tx = self.create_stream_ip4(self.pg1, "10.0.0.1")
rx = self.send_and_expect(self.pg1, tx, self.pg0)
- self.verify_capture_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32),
- VppMplsLabel(55)])
+ self.verify_capture_labelled_ip4(
+ self.pg0, rx, tx, [VppMplsLabel(32), VppMplsLabel(55)]
+ )
#
# An unlabeled IP route that resolves thru the binding SID
#
- ip_10_0_0_1 = VppIpRoute(self, "10.0.0.2", 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_via_label=999)])
+ ip_10_0_0_1 = VppIpRoute(
+ self,
+ "10.0.0.2",
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_via_label=999)],
+ )
ip_10_0_0_1.add_vpp_config()
tx = self.create_stream_ip4(self.pg1, "10.0.0.2")
rx = self.send_and_expect(self.pg1, tx, self.pg0)
- self.verify_capture_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32)])
+ self.verify_capture_labelled_ip4(self.pg0, rx, tx, [VppMplsLabel(32)])
self.vapi.sr_mpls_policy_del(999)
@@ -207,71 +227,89 @@ class TestSRMPLS(VppTestCase):
tx = self.create_stream_ip4(self.pg1, "10.0.0.1")
rx = self.send_and_expect(self.pg1, tx, self.pg0)
- self.verify_capture_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32),
- VppMplsLabel(33),
- VppMplsLabel(34),
- VppMplsLabel(55)])
+ self.verify_capture_labelled_ip4(
+ self.pg0,
+ rx,
+ tx,
+ [VppMplsLabel(32), VppMplsLabel(33), VppMplsLabel(34), VppMplsLabel(55)],
+ )
tx = self.create_stream_ip4(self.pg1, "10.0.0.2")
rx = self.send_and_expect(self.pg1, tx, self.pg0)
- self.verify_capture_labelled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32),
- VppMplsLabel(33),
- VppMplsLabel(34)])
+ self.verify_capture_labelled_ip4(
+ self.pg0, rx, tx, [VppMplsLabel(32), VppMplsLabel(33), VppMplsLabel(34)]
+ )
#
# Resolve an MPLS tunnel via the SID
#
mpls_tun = VppMPLSTunnelInterface(
self,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_via_label=999,
- labels=[VppMplsLabel(44),
- VppMplsLabel(46)])])
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ nh_via_label=999,
+ labels=[VppMplsLabel(44), VppMplsLabel(46)],
+ )
+ ],
+ )
mpls_tun.add_vpp_config()
mpls_tun.admin_up()
#
# add an unlabelled route through the new tunnel
#
- route_10_0_0_3 = VppIpRoute(self, "10.0.0.3", 32,
- [VppRoutePath("0.0.0.0",
- mpls_tun._sw_if_index)])
+ route_10_0_0_3 = VppIpRoute(
+ self, "10.0.0.3", 32, [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index)]
+ )
route_10_0_0_3.add_vpp_config()
self.logger.info(self.vapi.cli("sh mpls tun 0"))
self.logger.info(self.vapi.cli("sh adj 21"))
tx = self.create_stream_ip4(self.pg1, "10.0.0.3")
rx = self.send_and_expect(self.pg1, tx, self.pg0)
- self.verify_capture_tunneled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32),
- VppMplsLabel(33),
- VppMplsLabel(34),
- VppMplsLabel(44),
- VppMplsLabel(46)])
+ self.verify_capture_tunneled_ip4(
+ self.pg0,
+ rx,
+ tx,
+ [
+ VppMplsLabel(32),
+ VppMplsLabel(33),
+ VppMplsLabel(34),
+ VppMplsLabel(44),
+ VppMplsLabel(46),
+ ],
+ )
#
# add a labelled route through the new tunnel
#
- route_10_0_0_3 = VppIpRoute(self, "10.0.0.4", 32,
- [VppRoutePath("0.0.0.0",
- mpls_tun._sw_if_index,
- labels=[VppMplsLabel(55)])])
+ route_10_0_0_3 = VppIpRoute(
+ self,
+ "10.0.0.4",
+ 32,
+ [VppRoutePath("0.0.0.0", mpls_tun._sw_if_index, labels=[VppMplsLabel(55)])],
+ )
route_10_0_0_3.add_vpp_config()
tx = self.create_stream_ip4(self.pg1, "10.0.0.4")
rx = self.send_and_expect(self.pg1, tx, self.pg0)
- self.verify_capture_tunneled_ip4(self.pg0, rx, tx,
- [VppMplsLabel(32),
- VppMplsLabel(33),
- VppMplsLabel(34),
- VppMplsLabel(44),
- VppMplsLabel(46),
- VppMplsLabel(55)])
+ self.verify_capture_tunneled_ip4(
+ self.pg0,
+ rx,
+ tx,
+ [
+ VppMplsLabel(32),
+ VppMplsLabel(33),
+ VppMplsLabel(34),
+ VppMplsLabel(44),
+ VppMplsLabel(46),
+ VppMplsLabel(55),
+ ],
+ )
self.vapi.sr_mpls_policy_del(999)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_srv6.py b/test/test_srv6.py
index ec2fb6d4369..40b53375ddb 100644
--- a/test/test_srv6.py
+++ b/test/test_srv6.py
@@ -6,8 +6,14 @@ from socket import AF_INET6
from framework import VppTestCase, VppTestRunner
from vpp_ip_route import VppIpRoute, VppRoutePath, FibPathProto, VppIpTable
-from vpp_srv6 import SRv6LocalSIDBehaviors, VppSRv6LocalSID, VppSRv6Policy, \
- SRv6PolicyType, VppSRv6Steering, SRv6PolicySteeringTypes
+from vpp_srv6 import (
+ SRv6LocalSIDBehaviors,
+ VppSRv6LocalSID,
+ VppSRv6Policy,
+ SRv6PolicyType,
+ VppSRv6Steering,
+ SRv6PolicySteeringTypes,
+)
import scapy.compat
from scapy.packet import Raw
@@ -19,7 +25,7 @@ from util import ppp
class TestSRv6(VppTestCase):
- """ SRv6 Test Case """
+ """SRv6 Test Case"""
@classmethod
def setUpClass(cls):
@@ -30,8 +36,7 @@ class TestSRv6(VppTestCase):
super(TestSRv6, cls).tearDownClass()
def setUp(self):
- """ Perform test setup before each test case.
- """
+ """Perform test setup before each test case."""
super(TestSRv6, self).setUp()
# packet sizes, inclusive L2 overhead
@@ -41,17 +46,15 @@ class TestSRv6(VppTestCase):
self.reset_packet_infos()
def tearDown(self):
- """ Clean up test setup after each test case.
- """
+ """Clean up test setup after each test case."""
self.teardown_interfaces()
super(TestSRv6, self).tearDown()
- def configure_interface(self,
- interface,
- ipv6=False, ipv4=False,
- ipv6_table_id=0, ipv4_table_id=0):
- """ Configure interface.
+ def configure_interface(
+ self, interface, ipv6=False, ipv4=False, ipv6_table_id=0, ipv4_table_id=0
+ ):
+ """Configure interface.
:param ipv6: configure IPv6 on interface
:param ipv4: configure IPv4 on interface
:param ipv6_table_id: FIB table_id for IPv6
@@ -70,9 +73,8 @@ class TestSRv6(VppTestCase):
interface.resolve_arp()
interface.admin_up()
- def setup_interfaces(self, ipv6=[], ipv4=[],
- ipv6_table_id=[], ipv4_table_id=[]):
- """ Create and configure interfaces.
+ def setup_interfaces(self, ipv6=[], ipv4=[], ipv6_table_id=[], ipv4_table_id=[]):
+ """Create and configure interfaces.
:param ipv6: list of interface IPv6 capabilities
:param ipv4: list of interface IPv4 capabilities
@@ -107,9 +109,9 @@ class TestSRv6(VppTestCase):
# setup all interfaces
for i in range(count):
intf = self.pg_interfaces[i]
- self.configure_interface(intf,
- ipv6[i], ipv4[i],
- ipv6_table_id[i], ipv4_table_id[i])
+ self.configure_interface(
+ intf, ipv6[i], ipv4[i], ipv6_table_id[i], ipv4_table_id[i]
+ )
if any(ipv6):
self.logger.debug(self.vapi.cli("show ip6 neighbors"))
@@ -121,8 +123,7 @@ class TestSRv6(VppTestCase):
return self.pg_interfaces
def teardown_interfaces(self):
- """ Unconfigure and bring down interface.
- """
+ """Unconfigure and bring down interface."""
self.logger.debug("Tearing down interfaces")
# tear down all interfaces
# AFAIK they cannot be deleted
@@ -135,16 +136,15 @@ class TestSRv6(VppTestCase):
@unittest.skipUnless(0, "PC to fix")
def test_SRv6_T_Encaps(self):
- """ Test SRv6 Transit.Encaps behavior for IPv6.
- """
+ """Test SRv6 Transit.Encaps behavior for IPv6."""
# send traffic to one destination interface
# source and destination are IPv6 only
self.setup_interfaces(ipv6=[True, True])
# configure FIB entries
- route = VppIpRoute(self, "a4::", 64,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ route = VppIpRoute(
+ self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)]
+ )
route.add_vpp_config()
# configure encaps IPv6 source address
@@ -152,16 +152,19 @@ class TestSRv6(VppTestCase):
# TODO: API?
self.vapi.cli("set sr encaps source addr a3::")
- bsid = 'a3::9999:1'
+ bsid = "a3::9999:1"
# configure SRv6 Policy
# Note: segment list order: first -> last
sr_policy = VppSRv6Policy(
- self, bsid=bsid,
+ self,
+ bsid=bsid,
is_encap=1,
sr_type=SRv6PolicyType.SR_POLICY_TYPE_DEFAULT,
- weight=1, fib_table=0,
- segments=['a4::', 'a5::', 'a6::c7'],
- source='a3::')
+ weight=1,
+ fib_table=0,
+ segments=["a4::", "a5::", "a6::c7"],
+ source="a3::",
+ )
sr_policy.add_vpp_config()
self.sr_policy = sr_policy
@@ -171,12 +174,15 @@ class TestSRv6(VppTestCase):
# steer IPv6 traffic to a7::/64 into SRv6 Policy
# use the bsid of the above self.sr_policy
pol_steering = VppSRv6Steering(
- self,
- bsid=self.sr_policy.bsid,
- prefix="a7::", mask_width=64,
- traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV6,
- sr_policy_index=0, table_id=0,
- sw_if_index=0)
+ self,
+ bsid=self.sr_policy.bsid,
+ prefix="a7::",
+ mask_width=64,
+ traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV6,
+ sr_policy_index=0,
+ table_id=0,
+ sw_if_index=0,
+ )
pol_steering.add_vpp_config()
# log the sr steering policies
@@ -184,37 +190,46 @@ class TestSRv6(VppTestCase):
# create packets
count = len(self.pg_packet_sizes)
- dst_inner = 'a7::1234'
+ dst_inner = "a7::1234"
pkts = []
# create IPv6 packets without SRH
packet_header = self.create_packet_header_IPv6(dst_inner)
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# create IPv6 packets with SRH
# packets with segments-left 1, active segment a7::
packet_header = self.create_packet_header_IPv6_SRH(
- sidlist=['a8::', 'a7::', 'a6::'],
- segleft=1)
+ sidlist=["a8::", "a7::", "a6::"], segleft=1
+ )
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# create IPv6 packets with SRH and IPv6
# packets with segments-left 1, active segment a7::
packet_header = self.create_packet_header_IPv6_SRH_IPv6(
- dst_inner,
- sidlist=['a8::', 'a7::', 'a6::'],
- segleft=1)
+ dst_inner, sidlist=["a8::", "a7::", "a6::"], segleft=1
+ )
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts, self.pg1,
- self.compare_rx_tx_packet_T_Encaps)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_T_Encaps
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -235,16 +250,15 @@ class TestSRv6(VppTestCase):
@unittest.skipUnless(0, "PC to fix")
def test_SRv6_T_Insert(self):
- """ Test SRv6 Transit.Insert behavior (IPv6 only).
- """
+ """Test SRv6 Transit.Insert behavior (IPv6 only)."""
# send traffic to one destination interface
# source and destination are IPv6 only
self.setup_interfaces(ipv6=[True, True])
# configure FIB entries
- route = VppIpRoute(self, "a4::", 64,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ route = VppIpRoute(
+ self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)]
+ )
route.add_vpp_config()
# configure encaps IPv6 source address
@@ -252,16 +266,19 @@ class TestSRv6(VppTestCase):
# TODO: API?
self.vapi.cli("set sr encaps source addr a3::")
- bsid = 'a3::9999:1'
+ bsid = "a3::9999:1"
# configure SRv6 Policy
# Note: segment list order: first -> last
sr_policy = VppSRv6Policy(
- self, bsid=bsid,
+ self,
+ bsid=bsid,
is_encap=0,
sr_type=SRv6PolicyType.SR_POLICY_TYPE_DEFAULT,
- weight=1, fib_table=0,
- segments=['a4::', 'a5::', 'a6::c7'],
- source='a3::')
+ weight=1,
+ fib_table=0,
+ segments=["a4::", "a5::", "a6::c7"],
+ source="a3::",
+ )
sr_policy.add_vpp_config()
self.sr_policy = sr_policy
@@ -271,12 +288,15 @@ class TestSRv6(VppTestCase):
# steer IPv6 traffic to a7::/64 into SRv6 Policy
# use the bsid of the above self.sr_policy
pol_steering = VppSRv6Steering(
- self,
- bsid=self.sr_policy.bsid,
- prefix="a7::", mask_width=64,
- traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV6,
- sr_policy_index=0, table_id=0,
- sw_if_index=0)
+ self,
+ bsid=self.sr_policy.bsid,
+ prefix="a7::",
+ mask_width=64,
+ traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV6,
+ sr_policy_index=0,
+ table_id=0,
+ sw_if_index=0,
+ )
pol_steering.add_vpp_config()
# log the sr steering policies
@@ -284,27 +304,34 @@ class TestSRv6(VppTestCase):
# create packets
count = len(self.pg_packet_sizes)
- dst_inner = 'a7::1234'
+ dst_inner = "a7::1234"
pkts = []
# create IPv6 packets without SRH
packet_header = self.create_packet_header_IPv6(dst_inner)
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# create IPv6 packets with SRH
# packets with segments-left 1, active segment a7::
packet_header = self.create_packet_header_IPv6_SRH(
- sidlist=['a8::', 'a7::', 'a6::'],
- segleft=1)
+ sidlist=["a8::", "a7::", "a6::"], segleft=1
+ )
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts, self.pg1,
- self.compare_rx_tx_packet_T_Insert)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_T_Insert
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -325,17 +352,16 @@ class TestSRv6(VppTestCase):
@unittest.skipUnless(0, "PC to fix")
def test_SRv6_T_Encaps_IPv4(self):
- """ Test SRv6 Transit.Encaps behavior for IPv4.
- """
+ """Test SRv6 Transit.Encaps behavior for IPv4."""
# send traffic to one destination interface
# source interface is IPv4 only
# destination interface is IPv6 only
self.setup_interfaces(ipv6=[False, True], ipv4=[True, False])
# configure FIB entries
- route = VppIpRoute(self, "a4::", 64,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ route = VppIpRoute(
+ self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)]
+ )
route.add_vpp_config()
# configure encaps IPv6 source address
@@ -343,16 +369,19 @@ class TestSRv6(VppTestCase):
# TODO: API?
self.vapi.cli("set sr encaps source addr a3::")
- bsid = 'a3::9999:1'
+ bsid = "a3::9999:1"
# configure SRv6 Policy
# Note: segment list order: first -> last
sr_policy = VppSRv6Policy(
- self, bsid=bsid,
+ self,
+ bsid=bsid,
is_encap=1,
sr_type=SRv6PolicyType.SR_POLICY_TYPE_DEFAULT,
- weight=1, fib_table=0,
- segments=['a4::', 'a5::', 'a6::c7'],
- source='a3::')
+ weight=1,
+ fib_table=0,
+ segments=["a4::", "a5::", "a6::c7"],
+ source="a3::",
+ )
sr_policy.add_vpp_config()
self.sr_policy = sr_policy
@@ -362,12 +391,15 @@ class TestSRv6(VppTestCase):
# steer IPv4 traffic to 7.1.1.0/24 into SRv6 Policy
# use the bsid of the above self.sr_policy
pol_steering = VppSRv6Steering(
- self,
- bsid=self.sr_policy.bsid,
- prefix="7.1.1.0", mask_width=24,
- traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV4,
- sr_policy_index=0, table_id=0,
- sw_if_index=0)
+ self,
+ bsid=self.sr_policy.bsid,
+ prefix="7.1.1.0",
+ mask_width=24,
+ traffic_type=SRv6PolicySteeringTypes.SR_STEER_IPV4,
+ sr_policy_index=0,
+ table_id=0,
+ sw_if_index=0,
+ )
pol_steering.add_vpp_config()
# log the sr steering policies
@@ -375,18 +407,22 @@ class TestSRv6(VppTestCase):
# create packets
count = len(self.pg_packet_sizes)
- dst_inner = '7.1.1.123'
+ dst_inner = "7.1.1.123"
pkts = []
# create IPv4 packets
packet_header = self.create_packet_header_IPv4(dst_inner)
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts, self.pg1,
- self.compare_rx_tx_packet_T_Encaps_IPv4)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_T_Encaps_IPv4
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -407,17 +443,16 @@ class TestSRv6(VppTestCase):
@unittest.skip("VPP crashes after running this test")
def test_SRv6_T_Encaps_L2(self):
- """ Test SRv6 Transit.Encaps behavior for L2.
- """
+ """Test SRv6 Transit.Encaps behavior for L2."""
# send traffic to one destination interface
# source interface is IPv4 only TODO?
# destination interface is IPv6 only
self.setup_interfaces(ipv6=[False, True], ipv4=[False, False])
# configure FIB entries
- route = VppIpRoute(self, "a4::", 64,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ route = VppIpRoute(
+ self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)]
+ )
route.add_vpp_config()
# configure encaps IPv6 source address
@@ -425,16 +460,19 @@ class TestSRv6(VppTestCase):
# TODO: API?
self.vapi.cli("set sr encaps source addr a3::")
- bsid = 'a3::9999:1'
+ bsid = "a3::9999:1"
# configure SRv6 Policy
# Note: segment list order: first -> last
sr_policy = VppSRv6Policy(
- self, bsid=bsid,
+ self,
+ bsid=bsid,
is_encap=1,
sr_type=SRv6PolicyType.SR_POLICY_TYPE_DEFAULT,
- weight=1, fib_table=0,
- segments=['a4::', 'a5::', 'a6::c7'],
- source='a3::')
+ weight=1,
+ fib_table=0,
+ segments=["a4::", "a5::", "a6::c7"],
+ source="a3::",
+ )
sr_policy.add_vpp_config()
self.sr_policy = sr_policy
@@ -444,12 +482,15 @@ class TestSRv6(VppTestCase):
# steer L2 traffic into SRv6 Policy
# use the bsid of the above self.sr_policy
pol_steering = VppSRv6Steering(
- self,
- bsid=self.sr_policy.bsid,
- prefix="::", mask_width=0,
- traffic_type=SRv6PolicySteeringTypes.SR_STEER_L2,
- sr_policy_index=0, table_id=0,
- sw_if_index=self.pg0.sw_if_index)
+ self,
+ bsid=self.sr_policy.bsid,
+ prefix="::",
+ mask_width=0,
+ traffic_type=SRv6PolicySteeringTypes.SR_STEER_L2,
+ sr_policy_index=0,
+ table_id=0,
+ sw_if_index=self.pg0.sw_if_index,
+ )
pol_steering.add_vpp_config()
# log the sr steering policies
@@ -462,18 +503,25 @@ class TestSRv6(VppTestCase):
# create L2 packets without dot1q header
packet_header = self.create_packet_header_L2()
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# create L2 packets with dot1q header
packet_header = self.create_packet_header_L2(vlan=123)
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts, self.pg1,
- self.compare_rx_tx_packet_T_Encaps_L2)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_T_Encaps_L2
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -493,27 +541,28 @@ class TestSRv6(VppTestCase):
self.teardown_interfaces()
def test_SRv6_End(self):
- """ Test SRv6 End (without PSP) behavior.
- """
+ """Test SRv6 End (without PSP) behavior."""
# send traffic to one destination interface
# source and destination interfaces are IPv6 only
self.setup_interfaces(ipv6=[True, True])
# configure FIB entries
- route = VppIpRoute(self, "a4::", 64,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ route = VppIpRoute(
+ self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)]
+ )
route.add_vpp_config()
# configure SRv6 localSID End without PSP behavior
localsid = VppSRv6LocalSID(
- self, localsid='A3::0',
- behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_END,
- nh_addr=0,
- end_psp=0,
- sw_if_index=0,
- vlan_index=0,
- fib_table=0)
+ self,
+ localsid="A3::0",
+ behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_END,
+ nh_addr=0,
+ end_psp=0,
+ sw_if_index=0,
+ vlan_index=0,
+ fib_table=0,
+ )
localsid.add_vpp_config()
# log the localsids
self.logger.debug(self.vapi.cli("show sr localsid"))
@@ -522,41 +571,52 @@ class TestSRv6(VppTestCase):
# send one packet per SL value per packet size
# SL=0 packet with localSID End with USP needs 2nd SRH
count = len(self.pg_packet_sizes)
- dst_inner = 'a4::1234'
+ dst_inner = "a4::1234"
pkts = []
# packets with segments-left 2, active segment a3::
packet_header = self.create_packet_header_IPv6_SRH_IPv6(
- dst_inner,
- sidlist=['a5::', 'a4::', 'a3::'],
- segleft=2)
+ dst_inner, sidlist=["a5::", "a4::", "a3::"], segleft=2
+ )
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# packets with segments-left 1, active segment a3::
packet_header = self.create_packet_header_IPv6_SRH_IPv6(
- dst_inner,
- sidlist=['a4::', 'a3::', 'a2::'],
- segleft=1)
+ dst_inner, sidlist=["a4::", "a3::", "a2::"], segleft=1
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# TODO: test behavior with SL=0 packet (needs 2*SRH?)
expected_count = len(pkts)
# packets without SRH (should not crash)
- packet_header = self.create_packet_header_IPv6('a3::')
+ packet_header = self.create_packet_header_IPv6("a3::")
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts, self.pg1,
- self.compare_rx_tx_packet_End,
- expected_count=expected_count)
+ self.send_and_verify_pkts(
+ self.pg0,
+ pkts,
+ self.pg1,
+ self.compare_rx_tx_packet_End,
+ expected_count=expected_count,
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -571,27 +631,28 @@ class TestSRv6(VppTestCase):
self.teardown_interfaces()
def test_SRv6_End_with_PSP(self):
- """ Test SRv6 End with PSP behavior.
- """
+ """Test SRv6 End with PSP behavior."""
# send traffic to one destination interface
# source and destination interfaces are IPv6 only
self.setup_interfaces(ipv6=[True, True])
# configure FIB entries
- route = VppIpRoute(self, "a4::", 64,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index)])
+ route = VppIpRoute(
+ self, "a4::", 64, [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index)]
+ )
route.add_vpp_config()
# configure SRv6 localSID End with PSP behavior
localsid = VppSRv6LocalSID(
- self, localsid='A3::0',
- behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_END,
- nh_addr=0,
- end_psp=1,
- sw_if_index=0,
- vlan_index=0,
- fib_table=0)
+ self,
+ localsid="A3::0",
+ behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_END,
+ nh_addr=0,
+ end_psp=1,
+ sw_if_index=0,
+ vlan_index=0,
+ fib_table=0,
+ )
localsid.add_vpp_config()
# log the localsids
self.logger.debug(self.vapi.cli("show sr localsid"))
@@ -600,30 +661,35 @@ class TestSRv6(VppTestCase):
# send one packet per SL value per packet size
# SL=0 packet with localSID End with PSP is dropped
count = len(self.pg_packet_sizes)
- dst_inner = 'a4::1234'
+ dst_inner = "a4::1234"
pkts = []
# packets with segments-left 2, active segment a3::
packet_header = self.create_packet_header_IPv6_SRH_IPv6(
- dst_inner,
- sidlist=['a5::', 'a4::', 'a3::'],
- segleft=2)
+ dst_inner, sidlist=["a5::", "a4::", "a3::"], segleft=2
+ )
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# packets with segments-left 1, active segment a3::
packet_header = self.create_packet_header_IPv6_SRH_IPv6(
- dst_inner,
- sidlist=['a4::', 'a3::', 'a2::'],
- segleft=1)
+ dst_inner, sidlist=["a4::", "a3::", "a2::"], segleft=1
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts, self.pg1,
- self.compare_rx_tx_packet_End_PSP)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End_PSP
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -638,32 +704,37 @@ class TestSRv6(VppTestCase):
self.teardown_interfaces()
def test_SRv6_End_X(self):
- """ Test SRv6 End.X (without PSP) behavior.
- """
+ """Test SRv6 End.X (without PSP) behavior."""
# create three interfaces (1 source, 2 destinations)
# source and destination interfaces are IPv6 only
self.setup_interfaces(ipv6=[True, True, True])
# configure FIB entries
# a4::/64 via pg1 and pg2
- route = VppIpRoute(self, "a4::", 64,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index),
- VppRoutePath(self.pg2.remote_ip6,
- self.pg2.sw_if_index)])
+ route = VppIpRoute(
+ self,
+ "a4::",
+ 64,
+ [
+ VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index),
+ VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index),
+ ],
+ )
route.add_vpp_config()
self.logger.debug(self.vapi.cli("show ip6 fib"))
# configure SRv6 localSID End.X without PSP behavior
# End.X points to interface pg1
localsid = VppSRv6LocalSID(
- self, localsid='A3::C4',
- behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_X,
- nh_addr=self.pg1.remote_ip6,
- end_psp=0,
- sw_if_index=self.pg1.sw_if_index,
- vlan_index=0,
- fib_table=0)
+ self,
+ localsid="A3::C4",
+ behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_X,
+ nh_addr=self.pg1.remote_ip6,
+ end_psp=0,
+ sw_if_index=self.pg1.sw_if_index,
+ vlan_index=0,
+ fib_table=0,
+ )
localsid.add_vpp_config()
# log the localsids
self.logger.debug(self.vapi.cli("show sr localsid"))
@@ -672,31 +743,36 @@ class TestSRv6(VppTestCase):
# send one packet per SL value per packet size
# SL=0 packet with localSID End with PSP is dropped
count = len(self.pg_packet_sizes)
- dst_inner = 'a4::1234'
+ dst_inner = "a4::1234"
pkts = []
# packets with segments-left 2, active segment a3::c4
packet_header = self.create_packet_header_IPv6_SRH_IPv6(
- dst_inner,
- sidlist=['a5::', 'a4::', 'a3::c4'],
- segleft=2)
+ dst_inner, sidlist=["a5::", "a4::", "a3::c4"], segleft=2
+ )
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# packets with segments-left 1, active segment a3::c4
packet_header = self.create_packet_header_IPv6_SRH_IPv6(
- dst_inner,
- sidlist=['a4::', 'a3::c4', 'a2::'],
- segleft=1)
+ dst_inner, sidlist=["a4::", "a3::c4", "a2::"], segleft=1
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
# using same comparison function as End (no PSP)
- self.send_and_verify_pkts(self.pg0, pkts, self.pg1,
- self.compare_rx_tx_packet_End)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End
+ )
# assert nothing was received on the other interface (pg2)
self.pg2.assert_nothing_captured(remark="mis-directed packet(s)")
@@ -714,31 +790,35 @@ class TestSRv6(VppTestCase):
self.teardown_interfaces()
def test_SRv6_End_X_with_PSP(self):
- """ Test SRv6 End.X with PSP behavior.
- """
+ """Test SRv6 End.X with PSP behavior."""
# create three interfaces (1 source, 2 destinations)
# source and destination interfaces are IPv6 only
self.setup_interfaces(ipv6=[True, True, True])
# configure FIB entries
# a4::/64 via pg1 and pg2
- route = VppIpRoute(self, "a4::", 64,
- [VppRoutePath(
- self.pg1.remote_ip6,
- self.pg1.sw_if_index),
- VppRoutePath(self.pg2.remote_ip6,
- self.pg2.sw_if_index)])
+ route = VppIpRoute(
+ self,
+ "a4::",
+ 64,
+ [
+ VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index),
+ VppRoutePath(self.pg2.remote_ip6, self.pg2.sw_if_index),
+ ],
+ )
route.add_vpp_config()
# configure SRv6 localSID End with PSP behavior
localsid = VppSRv6LocalSID(
- self, localsid='A3::C4',
- behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_X,
- nh_addr=self.pg1.remote_ip6,
- end_psp=1,
- sw_if_index=self.pg1.sw_if_index,
- vlan_index=0,
- fib_table=0)
+ self,
+ localsid="A3::C4",
+ behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_X,
+ nh_addr=self.pg1.remote_ip6,
+ end_psp=1,
+ sw_if_index=self.pg1.sw_if_index,
+ vlan_index=0,
+ fib_table=0,
+ )
localsid.add_vpp_config()
# log the localsids
self.logger.debug(self.vapi.cli("show sr localsid"))
@@ -747,31 +827,36 @@ class TestSRv6(VppTestCase):
# send one packet per SL value per packet size
# SL=0 packet with localSID End with PSP is dropped
count = len(self.pg_packet_sizes)
- dst_inner = 'a4::1234'
+ dst_inner = "a4::1234"
pkts = []
# packets with segments-left 2, active segment a3::
packet_header = self.create_packet_header_IPv6_SRH_IPv6(
- dst_inner,
- sidlist=['a5::', 'a4::', 'a3::c4'],
- segleft=2)
+ dst_inner, sidlist=["a5::", "a4::", "a3::c4"], segleft=2
+ )
# create traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# packets with segments-left 1, active segment a3::
packet_header = self.create_packet_header_IPv6_SRH_IPv6(
- dst_inner,
- sidlist=['a4::', 'a3::c4', 'a2::'],
- segleft=1)
+ dst_inner, sidlist=["a4::", "a3::c4", "a2::"], segleft=1
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
# using same comparison function as End with PSP
- self.send_and_verify_pkts(self.pg0, pkts, self.pg1,
- self.compare_rx_tx_packet_End_PSP)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End_PSP
+ )
# assert nothing was received on the other interface (pg2)
self.pg2.assert_nothing_captured(remark="mis-directed packet(s)")
@@ -789,21 +874,22 @@ class TestSRv6(VppTestCase):
self.teardown_interfaces()
def test_SRv6_End_DX6(self):
- """ Test SRv6 End.DX6 behavior.
- """
+ """Test SRv6 End.DX6 behavior."""
# send traffic to one destination interface
# source and destination interfaces are IPv6 only
self.setup_interfaces(ipv6=[True, True])
# configure SRv6 localSID End.DX6 behavior
localsid = VppSRv6LocalSID(
- self, localsid='A3::C4',
- behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX6,
- nh_addr=self.pg1.remote_ip6,
- end_psp=0,
- sw_if_index=self.pg1.sw_if_index,
- vlan_index=0,
- fib_table=0)
+ self,
+ localsid="A3::C4",
+ behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX6,
+ nh_addr=self.pg1.remote_ip6,
+ end_psp=0,
+ sw_if_index=self.pg1.sw_if_index,
+ vlan_index=0,
+ fib_table=0,
+ )
localsid.add_vpp_config()
# log the localsids
self.logger.debug(self.vapi.cli("show sr localsid"))
@@ -811,30 +897,36 @@ class TestSRv6(VppTestCase):
# create IPv6 packets with SRH (SL=0)
# send one packet per packet size
count = len(self.pg_packet_sizes)
- dst_inner = 'a4::1234' # inner header destination address
+ dst_inner = "a4::1234" # inner header destination address
pkts = []
# packets with SRH, segments-left 0, active segment a3::c4
packet_header = self.create_packet_header_IPv6_SRH_IPv6(
- dst_inner,
- sidlist=['a3::c4', 'a2::', 'a1::'],
- segleft=0)
+ dst_inner, sidlist=["a3::c4", "a2::", "a1::"], segleft=0
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# packets without SRH, IPv6 in IPv6
# outer IPv6 dest addr is the localsid End.DX6
packet_header = self.create_packet_header_IPv6_IPv6(
- dst_inner,
- dst_outer='a3::c4')
+ dst_inner, dst_outer="a3::c4"
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts, self.pg1,
- self.compare_rx_tx_packet_End_DX6)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End_DX6
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -846,8 +938,7 @@ class TestSRv6(VppTestCase):
self.teardown_interfaces()
def test_SRv6_End_DT6(self):
- """ Test SRv6 End.DT6 behavior.
- """
+ """Test SRv6 End.DT6 behavior."""
# create three interfaces (1 source, 2 destinations)
# all interfaces are IPv6 only
# source interface in global FIB (0)
@@ -855,24 +946,31 @@ class TestSRv6(VppTestCase):
vrf_1 = 1
ipt = VppIpTable(self, vrf_1, is_ip6=True)
ipt.add_vpp_config()
- self.setup_interfaces(ipv6=[True, True, True],
- ipv6_table_id=[0, 0, vrf_1])
+ self.setup_interfaces(ipv6=[True, True, True], ipv6_table_id=[0, 0, vrf_1])
# configure FIB entries
# a4::/64 is reachable
# via pg1 in table 0 (global)
# and via pg2 in table vrf_1
- route0 = VppIpRoute(self, "a4::", 64,
- [VppRoutePath(self.pg1.remote_ip6,
- self.pg1.sw_if_index,
- nh_table_id=0)],
- table_id=0)
+ route0 = VppIpRoute(
+ self,
+ "a4::",
+ 64,
+ [VppRoutePath(self.pg1.remote_ip6, self.pg1.sw_if_index, nh_table_id=0)],
+ table_id=0,
+ )
route0.add_vpp_config()
- route1 = VppIpRoute(self, "a4::", 64,
- [VppRoutePath(self.pg2.remote_ip6,
- self.pg2.sw_if_index,
- nh_table_id=vrf_1)],
- table_id=vrf_1)
+ route1 = VppIpRoute(
+ self,
+ "a4::",
+ 64,
+ [
+ VppRoutePath(
+ self.pg2.remote_ip6, self.pg2.sw_if_index, nh_table_id=vrf_1
+ )
+ ],
+ table_id=vrf_1,
+ )
route1.add_vpp_config()
self.logger.debug(self.vapi.cli("show ip6 fib"))
@@ -881,13 +979,15 @@ class TestSRv6(VppTestCase):
# fib_table: where the localsid is installed
# sw_if_index: in T-variants of localsid this is the vrf table_id
localsid = VppSRv6LocalSID(
- self, localsid='A3::C4',
- behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DT6,
- nh_addr=0,
- end_psp=0,
- sw_if_index=vrf_1,
- vlan_index=0,
- fib_table=0)
+ self,
+ localsid="A3::C4",
+ behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DT6,
+ nh_addr=0,
+ end_psp=0,
+ sw_if_index=vrf_1,
+ vlan_index=0,
+ fib_table=0,
+ )
localsid.add_vpp_config()
# log the localsids
self.logger.debug(self.vapi.cli("show sr localsid"))
@@ -895,31 +995,37 @@ class TestSRv6(VppTestCase):
# create IPv6 packets with SRH (SL=0)
# send one packet per packet size
count = len(self.pg_packet_sizes)
- dst_inner = 'a4::1234' # inner header destination address
+ dst_inner = "a4::1234" # inner header destination address
pkts = []
# packets with SRH, segments-left 0, active segment a3::c4
packet_header = self.create_packet_header_IPv6_SRH_IPv6(
- dst_inner,
- sidlist=['a3::c4', 'a2::', 'a1::'],
- segleft=0)
+ dst_inner, sidlist=["a3::c4", "a2::", "a1::"], segleft=0
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg2, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg2, packet_header, self.pg_packet_sizes, count
+ )
+ )
# packets without SRH, IPv6 in IPv6
# outer IPv6 dest addr is the localsid End.DT6
packet_header = self.create_packet_header_IPv6_IPv6(
- dst_inner,
- dst_outer='a3::c4')
+ dst_inner, dst_outer="a3::c4"
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg2, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg2, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
# using same comparison function as End.DX6
- self.send_and_verify_pkts(self.pg0, pkts, self.pg2,
- self.compare_rx_tx_packet_End_DX6)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg2, self.compare_rx_tx_packet_End_DX6
+ )
# assert nothing was received on the other interface (pg2)
self.pg1.assert_nothing_captured(remark="mis-directed packet(s)")
@@ -937,8 +1043,7 @@ class TestSRv6(VppTestCase):
self.teardown_interfaces()
def test_SRv6_End_DX4(self):
- """ Test SRv6 End.DX4 behavior.
- """
+ """Test SRv6 End.DX4 behavior."""
# send traffic to one destination interface
# source interface is IPv6 only
# destination interface is IPv4 only
@@ -946,43 +1051,51 @@ class TestSRv6(VppTestCase):
# configure SRv6 localSID End.DX4 behavior
localsid = VppSRv6LocalSID(
- self, localsid='A3::C4',
- behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX4,
- nh_addr=self.pg1.remote_ip4,
- end_psp=0,
- sw_if_index=self.pg1.sw_if_index,
- vlan_index=0,
- fib_table=0)
+ self,
+ localsid="A3::C4",
+ behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX4,
+ nh_addr=self.pg1.remote_ip4,
+ end_psp=0,
+ sw_if_index=self.pg1.sw_if_index,
+ vlan_index=0,
+ fib_table=0,
+ )
localsid.add_vpp_config()
# log the localsids
self.logger.debug(self.vapi.cli("show sr localsid"))
# send one packet per packet size
count = len(self.pg_packet_sizes)
- dst_inner = '4.1.1.123' # inner header destination address
+ dst_inner = "4.1.1.123" # inner header destination address
pkts = []
# packets with SRH, segments-left 0, active segment a3::c4
packet_header = self.create_packet_header_IPv6_SRH_IPv4(
- dst_inner,
- sidlist=['a3::c4', 'a2::', 'a1::'],
- segleft=0)
+ dst_inner, sidlist=["a3::c4", "a2::", "a1::"], segleft=0
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# packets without SRH, IPv4 in IPv6
# outer IPv6 dest addr is the localsid End.DX4
packet_header = self.create_packet_header_IPv6_IPv4(
- dst_inner,
- dst_outer='a3::c4')
+ dst_inner, dst_outer="a3::c4"
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts, self.pg1,
- self.compare_rx_tx_packet_End_DX4)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End_DX4
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -994,8 +1107,7 @@ class TestSRv6(VppTestCase):
self.teardown_interfaces()
def test_SRv6_End_DT4(self):
- """ Test SRv6 End.DT4 behavior.
- """
+ """Test SRv6 End.DT4 behavior."""
# create three interfaces (1 source, 2 destinations)
# source interface is IPv6-only
# destination interfaces are IPv4 only
@@ -1004,26 +1116,36 @@ class TestSRv6(VppTestCase):
vrf_1 = 1
ipt = VppIpTable(self, vrf_1)
ipt.add_vpp_config()
- self.setup_interfaces(ipv6=[True, False, False],
- ipv4=[False, True, True],
- ipv6_table_id=[0, 0, 0],
- ipv4_table_id=[0, 0, vrf_1])
+ self.setup_interfaces(
+ ipv6=[True, False, False],
+ ipv4=[False, True, True],
+ ipv6_table_id=[0, 0, 0],
+ ipv4_table_id=[0, 0, vrf_1],
+ )
# configure FIB entries
# 4.1.1.0/24 is reachable
# via pg1 in table 0 (global)
# and via pg2 in table vrf_1
- route0 = VppIpRoute(self, "4.1.1.0", 24,
- [VppRoutePath(self.pg1.remote_ip4,
- self.pg1.sw_if_index,
- nh_table_id=0)],
- table_id=0)
+ route0 = VppIpRoute(
+ self,
+ "4.1.1.0",
+ 24,
+ [VppRoutePath(self.pg1.remote_ip4, self.pg1.sw_if_index, nh_table_id=0)],
+ table_id=0,
+ )
route0.add_vpp_config()
- route1 = VppIpRoute(self, "4.1.1.0", 24,
- [VppRoutePath(self.pg2.remote_ip4,
- self.pg2.sw_if_index,
- nh_table_id=vrf_1)],
- table_id=vrf_1)
+ route1 = VppIpRoute(
+ self,
+ "4.1.1.0",
+ 24,
+ [
+ VppRoutePath(
+ self.pg2.remote_ip4, self.pg2.sw_if_index, nh_table_id=vrf_1
+ )
+ ],
+ table_id=vrf_1,
+ )
route1.add_vpp_config()
self.logger.debug(self.vapi.cli("show ip fib"))
@@ -1032,13 +1154,15 @@ class TestSRv6(VppTestCase):
# fib_table: where the localsid is installed
# sw_if_index: in T-variants of localsid: vrf table_id
localsid = VppSRv6LocalSID(
- self, localsid='A3::C4',
- behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DT4,
- nh_addr=0,
- end_psp=0,
- sw_if_index=vrf_1,
- vlan_index=0,
- fib_table=0)
+ self,
+ localsid="A3::C4",
+ behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DT4,
+ nh_addr=0,
+ end_psp=0,
+ sw_if_index=vrf_1,
+ vlan_index=0,
+ fib_table=0,
+ )
localsid.add_vpp_config()
# log the localsids
self.logger.debug(self.vapi.cli("show sr localsid"))
@@ -1046,31 +1170,37 @@ class TestSRv6(VppTestCase):
# create IPv6 packets with SRH (SL=0)
# send one packet per packet size
count = len(self.pg_packet_sizes)
- dst_inner = '4.1.1.123' # inner header destination address
+ dst_inner = "4.1.1.123" # inner header destination address
pkts = []
# packets with SRH, segments-left 0, active segment a3::c4
packet_header = self.create_packet_header_IPv6_SRH_IPv4(
- dst_inner,
- sidlist=['a3::c4', 'a2::', 'a1::'],
- segleft=0)
+ dst_inner, sidlist=["a3::c4", "a2::", "a1::"], segleft=0
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg2, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg2, packet_header, self.pg_packet_sizes, count
+ )
+ )
# packets without SRH, IPv6 in IPv6
# outer IPv6 dest addr is the localsid End.DX4
packet_header = self.create_packet_header_IPv6_IPv4(
- dst_inner,
- dst_outer='a3::c4')
+ dst_inner, dst_outer="a3::c4"
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg2, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg2, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
# using same comparison function as End.DX4
- self.send_and_verify_pkts(self.pg0, pkts, self.pg2,
- self.compare_rx_tx_packet_End_DX4)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg2, self.compare_rx_tx_packet_End_DX4
+ )
# assert nothing was received on the other interface (pg2)
self.pg1.assert_nothing_captured(remark="mis-directed packet(s)")
@@ -1088,21 +1218,22 @@ class TestSRv6(VppTestCase):
self.teardown_interfaces()
def test_SRv6_End_DX2(self):
- """ Test SRv6 End.DX2 behavior.
- """
+ """Test SRv6 End.DX2 behavior."""
# send traffic to one destination interface
# source interface is IPv6 only
self.setup_interfaces(ipv6=[True, False], ipv4=[False, False])
# configure SRv6 localSID End.DX2 behavior
localsid = VppSRv6LocalSID(
- self, localsid='A3::C4',
- behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX2,
- nh_addr=0,
- end_psp=0,
- sw_if_index=self.pg1.sw_if_index,
- vlan_index=0,
- fib_table=0)
+ self,
+ localsid="A3::C4",
+ behavior=SRv6LocalSIDBehaviors.SR_BEHAVIOR_DX2,
+ nh_addr=0,
+ end_psp=0,
+ sw_if_index=self.pg1.sw_if_index,
+ vlan_index=0,
+ fib_table=0,
+ )
localsid.add_vpp_config()
# log the localsids
self.logger.debug(self.vapi.cli("show sr localsid"))
@@ -1114,46 +1245,53 @@ class TestSRv6(VppTestCase):
# packets with SRH, segments-left 0, active segment a3::c4
# L2 has no dot1q header
packet_header = self.create_packet_header_IPv6_SRH_L2(
- sidlist=['a3::c4', 'a2::', 'a1::'],
- segleft=0,
- vlan=0)
+ sidlist=["a3::c4", "a2::", "a1::"], segleft=0, vlan=0
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# packets with SRH, segments-left 0, active segment a3::c4
# L2 has dot1q header
packet_header = self.create_packet_header_IPv6_SRH_L2(
- sidlist=['a3::c4', 'a2::', 'a1::'],
- segleft=0,
- vlan=123)
+ sidlist=["a3::c4", "a2::", "a1::"], segleft=0, vlan=123
+ )
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# packets without SRH, L2 in IPv6
# outer IPv6 dest addr is the localsid End.DX2
# L2 has no dot1q header
- packet_header = self.create_packet_header_IPv6_L2(
- dst_outer='a3::c4',
- vlan=0)
+ packet_header = self.create_packet_header_IPv6_L2(dst_outer="a3::c4", vlan=0)
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# packets without SRH, L2 in IPv6
# outer IPv6 dest addr is the localsid End.DX2
# L2 has dot1q header
- packet_header = self.create_packet_header_IPv6_L2(
- dst_outer='a3::c4',
- vlan=123)
+ packet_header = self.create_packet_header_IPv6_L2(dst_outer="a3::c4", vlan=123)
# add to traffic stream pg0->pg1
- pkts.extend(self.create_stream(self.pg0, self.pg1, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg0, self.pg1, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts, self.pg1,
- self.compare_rx_tx_packet_End_DX2)
+ self.send_and_verify_pkts(
+ self.pg0, pkts, self.pg1, self.compare_rx_tx_packet_End_DX2
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -1166,18 +1304,17 @@ class TestSRv6(VppTestCase):
@unittest.skipUnless(0, "PC to fix")
def test_SRv6_T_Insert_Classifier(self):
- """ Test SRv6 Transit.Insert behavior (IPv6 only).
- steer packets using the classifier
+ """Test SRv6 Transit.Insert behavior (IPv6 only).
+ steer packets using the classifier
"""
# send traffic to one destination interface
# source and destination are IPv6 only
self.setup_interfaces(ipv6=[False, False, False, True, True])
# configure FIB entries
- route = VppIpRoute(self, "a4::", 64,
- [VppRoutePath(
- self.pg4.remote_ip6,
- self.pg4.sw_if_index)])
+ route = VppIpRoute(
+ self, "a4::", 64, [VppRoutePath(self.pg4.remote_ip6, self.pg4.sw_if_index)]
+ )
route.add_vpp_config()
# configure encaps IPv6 source address
@@ -1185,16 +1322,19 @@ class TestSRv6(VppTestCase):
# TODO: API?
self.vapi.cli("set sr encaps source addr a3::")
- bsid = 'a3::9999:1'
+ bsid = "a3::9999:1"
# configure SRv6 Policy
# Note: segment list order: first -> last
sr_policy = VppSRv6Policy(
- self, bsid=bsid,
+ self,
+ bsid=bsid,
is_encap=0,
sr_type=SRv6PolicyType.SR_POLICY_TYPE_DEFAULT,
- weight=1, fib_table=0,
- segments=['a4::', 'a5::', 'a6::c7'],
- source='a3::')
+ weight=1,
+ fib_table=0,
+ segments=["a4::", "a5::", "a6::c7"],
+ source="a3::",
+ )
sr_policy.add_vpp_config()
self.sr_policy = sr_policy
@@ -1203,75 +1343,79 @@ class TestSRv6(VppTestCase):
# add classify table
# mask on dst ip address prefix a7::/8
- mask = '{!s:0<16}'.format('ff')
+ mask = "{!s:0<16}".format("ff")
r = self.vapi.classify_add_del_table(
1,
binascii.unhexlify(mask),
match_n_vectors=(len(mask) - 1) // 32 + 1,
current_data_flag=1,
- skip_n_vectors=2) # data offset
- self.assertIsNotNone(r, 'No response msg for add_del_table')
+ skip_n_vectors=2,
+ ) # data offset
+ self.assertIsNotNone(r, "No response msg for add_del_table")
table_index = r.new_table_index
# add the source routing node as a ip6 inacl netxt node
- r = self.vapi.add_node_next('ip6-inacl',
- 'sr-pl-rewrite-insert')
+ r = self.vapi.add_node_next("ip6-inacl", "sr-pl-rewrite-insert")
inacl_next_node_index = r.node_index
- match = '{!s:0<16}'.format('a7')
+ match = "{!s:0<16}".format("a7")
r = self.vapi.classify_add_del_session(
1,
table_index,
binascii.unhexlify(match),
hit_next_index=inacl_next_node_index,
action=3,
- metadata=0) # sr policy index
- self.assertIsNotNone(r, 'No response msg for add_del_session')
+ metadata=0,
+ ) # sr policy index
+ self.assertIsNotNone(r, "No response msg for add_del_session")
# log the classify table used in the steering policy
self.logger.info(self.vapi.cli("show classify table"))
r = self.vapi.input_acl_set_interface(
- is_add=1,
- sw_if_index=self.pg3.sw_if_index,
- ip6_table_index=table_index)
- self.assertIsNotNone(r,
- 'No response msg for input_acl_set_interface')
+ is_add=1, sw_if_index=self.pg3.sw_if_index, ip6_table_index=table_index
+ )
+ self.assertIsNotNone(r, "No response msg for input_acl_set_interface")
# log the ip6 inacl
self.logger.info(self.vapi.cli("show inacl type ip6"))
# create packets
count = len(self.pg_packet_sizes)
- dst_inner = 'a7::1234'
+ dst_inner = "a7::1234"
pkts = []
# create IPv6 packets without SRH
packet_header = self.create_packet_header_IPv6(dst_inner)
# create traffic stream pg3->pg4
- pkts.extend(self.create_stream(self.pg3, self.pg4, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg3, self.pg4, packet_header, self.pg_packet_sizes, count
+ )
+ )
# create IPv6 packets with SRH
# packets with segments-left 1, active segment a7::
packet_header = self.create_packet_header_IPv6_SRH(
- sidlist=['a8::', 'a7::', 'a6::'],
- segleft=1)
+ sidlist=["a8::", "a7::", "a6::"], segleft=1
+ )
# create traffic stream pg3->pg4
- pkts.extend(self.create_stream(self.pg3, self.pg4, packet_header,
- self.pg_packet_sizes, count))
+ pkts.extend(
+ self.create_stream(
+ self.pg3, self.pg4, packet_header, self.pg_packet_sizes, count
+ )
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg3, pkts, self.pg4,
- self.compare_rx_tx_packet_T_Insert)
+ self.send_and_verify_pkts(
+ self.pg3, pkts, self.pg4, self.compare_rx_tx_packet_T_Insert
+ )
# remove the interface l2 input feature
r = self.vapi.input_acl_set_interface(
- is_add=0,
- sw_if_index=self.pg3.sw_if_index,
- ip6_table_index=table_index)
- self.assertIsNotNone(r,
- 'No response msg for input_acl_set_interface')
+ is_add=0, sw_if_index=self.pg3.sw_if_index, ip6_table_index=table_index
+ )
+ self.assertIsNotNone(r, "No response msg for input_acl_set_interface")
# log the ip6 inacl after cleaning
self.logger.info(self.vapi.cli("show inacl type ip6"))
@@ -1289,16 +1433,14 @@ class TestSRv6(VppTestCase):
# remove classify session and table
r = self.vapi.classify_add_del_session(
- 0,
- table_index,
- binascii.unhexlify(match))
- self.assertIsNotNone(r, 'No response msg for add_del_session')
+ 0, table_index, binascii.unhexlify(match)
+ )
+ self.assertIsNotNone(r, "No response msg for add_del_session")
r = self.vapi.classify_add_del_table(
- 0,
- binascii.unhexlify(mask),
- table_index=table_index)
- self.assertIsNotNone(r, 'No response msg for add_del_table')
+ 0, binascii.unhexlify(mask), table_index=table_index
+ )
+ self.assertIsNotNone(r, "No response msg for add_del_table")
self.logger.info(self.vapi.cli("show classify table"))
@@ -1309,7 +1451,7 @@ class TestSRv6(VppTestCase):
self.teardown_interfaces()
def compare_rx_tx_packet_T_Encaps(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing T.Encaps
+ """Compare input and output packet after passing T.Encaps
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -1350,7 +1492,7 @@ class TestSRv6(VppTestCase):
# rx'ed seglist should be equal to expected seglist
self.assertEqual(rx_srh.addresses, tx_seglist)
# segleft should be equal to size expected seglist-1
- self.assertEqual(rx_srh.segleft, len(tx_seglist)-1)
+ self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1)
# segleft should be equal to lastentry
self.assertEqual(rx_srh.segleft, rx_srh.lastentry)
@@ -1364,7 +1506,7 @@ class TestSRv6(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_T_Encaps_IPv4(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing T.Encaps for IPv4
+ """Compare input and output packet after passing T.Encaps for IPv4
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -1404,7 +1546,7 @@ class TestSRv6(VppTestCase):
# rx'ed seglist should be equal to seglist
self.assertEqual(rx_srh.addresses, tx_seglist)
# segleft should be equal to size seglist-1
- self.assertEqual(rx_srh.segleft, len(tx_seglist)-1)
+ self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1)
# segleft should be equal to lastentry
self.assertEqual(rx_srh.segleft, rx_srh.lastentry)
@@ -1423,7 +1565,7 @@ class TestSRv6(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_T_Encaps_L2(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing T.Encaps for L2
+ """Compare input and output packet after passing T.Encaps for L2
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -1461,7 +1603,7 @@ class TestSRv6(VppTestCase):
# rx'ed seglist should be equal to seglist
self.assertEqual(rx_srh.addresses, tx_seglist)
# segleft should be equal to size seglist-1
- self.assertEqual(rx_srh.segleft, len(tx_seglist)-1)
+ self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1)
# segleft should be equal to lastentry
self.assertEqual(rx_srh.segleft, rx_srh.lastentry)
# nh should be "No Next Header" (143)
@@ -1473,7 +1615,7 @@ class TestSRv6(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_T_Insert(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing T.Insert
+ """Compare input and output packet after passing T.Insert
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -1529,7 +1671,7 @@ class TestSRv6(VppTestCase):
# rx'ed seglist should be equal to expected seglist
self.assertEqual(rx_srh.addresses, tx_seglist)
# segleft should be equal to size(expected seglist)-1
- self.assertEqual(rx_srh.segleft, len(tx_seglist)-1)
+ self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1)
# segleft should be equal to lastentry
self.assertEqual(rx_srh.segleft, rx_srh.lastentry)
@@ -1556,7 +1698,7 @@ class TestSRv6(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End (without PSP)
+ """Compare input and output packet after passing End (without PSP)
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -1596,7 +1738,7 @@ class TestSRv6(VppTestCase):
# sidlist should be unchanged
self.assertEqual(rx_srh.addresses, tx_srh.addresses)
# segleft should have been decremented
- self.assertEqual(rx_srh.segleft, tx_srh.segleft-1)
+ self.assertEqual(rx_srh.segleft, tx_srh.segleft - 1)
# received ip.dst should be equal to sidlist[segleft]
self.assertEqual(rx_ip.dst, rx_srh.addresses[rx_srh.segleft])
# lastentry should be unchanged
@@ -1605,7 +1747,7 @@ class TestSRv6(VppTestCase):
self.assertEqual(rx_ip2.src, tx_ip2.src)
self.assertEqual(rx_ip2.dst, tx_ip2.dst)
# else: # tx_ip.segleft == 0
- # TODO: Does this work with 2 SRHs in ingress packet?
+ # TODO: Does this work with 2 SRHs in ingress packet?
# UDP layer should be unchanged
self.assertEqual(rx_udp, tx_udp)
@@ -1613,7 +1755,7 @@ class TestSRv6(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_PSP(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End with PSP
+ """Compare input and output packet after passing End with PSP
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -1658,7 +1800,7 @@ class TestSRv6(VppTestCase):
# sidlist should be unchanged
self.assertEqual(rx_srh.addresses, tx_srh.addresses)
# segleft should have been decremented
- self.assertEqual(rx_srh.segleft, tx_srh.segleft-1)
+ self.assertEqual(rx_srh.segleft, tx_srh.segleft - 1)
# received ip.dst should be equal to sidlist[segleft]
self.assertEqual(rx_ip.dst, rx_srh.addresses[rx_srh.segleft])
# lastentry should be unchanged
@@ -1674,7 +1816,7 @@ class TestSRv6(VppTestCase):
# outer IPv6 header ip.src should be equal to tx'ed ip.src
self.assertEqual(rx_ip.src, tx_ip.src)
# outer IPv6 header ip.dst should be = to tx'ed sidlist[segleft-1]
- self.assertEqual(rx_ip.dst, tx_srh.addresses[tx_srh.segleft-1])
+ self.assertEqual(rx_ip.dst, tx_srh.addresses[tx_srh.segleft - 1])
# UDP layer should be unchanged
self.assertEqual(rx_udp, tx_udp)
@@ -1682,7 +1824,7 @@ class TestSRv6(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_DX6(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.DX6
+ """Compare input and output packet after passing End.DX6
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -1714,7 +1856,7 @@ class TestSRv6(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_DX4(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.DX4
+ """Compare input and output packet after passing End.DX4
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -1751,7 +1893,7 @@ class TestSRv6(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_DX2(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.DX2
+ """Compare input and output packet after passing End.DX2
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -1780,8 +1922,7 @@ class TestSRv6(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
- def create_stream(self, src_if, dst_if, packet_header, packet_sizes,
- count):
+ def create_stream(self, src_if, dst_if, packet_header, packet_sizes, count):
"""Create SRv6 input packet stream for defined interface.
:param VppInterface src_if: Interface to create packet stream for
@@ -1796,19 +1937,19 @@ class TestSRv6(VppTestCase):
"""
self.logger.info("Creating packets")
pkts = []
- for i in range(0, count-1):
+ for i in range(0, count - 1):
payload_info = self.create_packet_info(src_if, dst_if)
- self.logger.debug(
- "Creating packet with index %d" % (payload_info.index))
+ self.logger.debug("Creating packet with index %d" % (payload_info.index))
payload = self.info_to_payload(payload_info)
# add L2 header if not yet provided in packet_header
- if packet_header.getlayer(0).name == 'Ethernet':
- p = (packet_header /
- Raw(payload))
+ if packet_header.getlayer(0).name == "Ethernet":
+ p = packet_header / Raw(payload)
else:
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- packet_header /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / packet_header
+ / Raw(payload)
+ )
size = packet_sizes[i % len(packet_sizes)]
self.logger.debug("Packet size %d" % (size))
self.extend_packet(p, size)
@@ -1823,8 +1964,9 @@ class TestSRv6(VppTestCase):
self.logger.info("Done creating packets")
return pkts
- def send_and_verify_pkts(self, input, pkts, output, compare_func,
- expected_count=None):
+ def send_and_verify_pkts(
+ self, input, pkts, output, compare_func, expected_count=None
+ ):
"""Send packets and verify received packets using compare_func
:param input: ingress interface of DUT
@@ -1863,8 +2005,7 @@ class TestSRv6(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IPv6(src='1234::1', dst=dst) /
- UDP(sport=1234, dport=1234))
+ p = IPv6(src="1234::1", dst=dst) / UDP(sport=1234, dport=1234)
return p
def create_packet_header_IPv6_SRH(self, sidlist, segleft):
@@ -1878,9 +2019,11 @@ class TestSRv6(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IPv6(src='1234::1', dst=sidlist[segleft]) /
- IPv6ExtHdrSegmentRouting(addresses=sidlist) /
- UDP(sport=1234, dport=1234))
+ p = (
+ IPv6(src="1234::1", dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist)
+ / UDP(sport=1234, dport=1234)
+ )
return p
def create_packet_header_IPv6_SRH_IPv6(self, dst, sidlist, segleft):
@@ -1896,11 +2039,12 @@ class TestSRv6(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IPv6(src='1234::1', dst=sidlist[segleft]) /
- IPv6ExtHdrSegmentRouting(addresses=sidlist,
- segleft=segleft, nh=41) /
- IPv6(src='4321::1', dst=dst) /
- UDP(sport=1234, dport=1234))
+ p = (
+ IPv6(src="1234::1", dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=41)
+ / IPv6(src="4321::1", dst=dst)
+ / UDP(sport=1234, dport=1234)
+ )
return p
def create_packet_header_IPv6_IPv6(self, dst_inner, dst_outer):
@@ -1914,13 +2058,16 @@ class TestSRv6(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IPv6(src='1234::1', dst=dst_outer) /
- IPv6(src='4321::1', dst=dst_inner) /
- UDP(sport=1234, dport=1234))
+ p = (
+ IPv6(src="1234::1", dst=dst_outer)
+ / IPv6(src="4321::1", dst=dst_inner)
+ / UDP(sport=1234, dport=1234)
+ )
return p
- def create_packet_header_IPv6_SRH_SRH_IPv6(self, dst, sidlist1, segleft1,
- sidlist2, segleft2):
+ def create_packet_header_IPv6_SRH_SRH_IPv6(
+ self, dst, sidlist1, segleft1, sidlist2, segleft2
+ ):
"""Create packet header: IPv6 encapsulated in SRv6 with 2 SRH:
IPv6 header with SRH, 2nd SRH, IPv6 header, UDP header
@@ -1935,13 +2082,13 @@ class TestSRv6(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IPv6(src='1234::1', dst=sidlist1[segleft1]) /
- IPv6ExtHdrSegmentRouting(addresses=sidlist1,
- segleft=segleft1, nh=43) /
- IPv6ExtHdrSegmentRouting(addresses=sidlist2,
- segleft=segleft2, nh=41) /
- IPv6(src='4321::1', dst=dst) /
- UDP(sport=1234, dport=1234))
+ p = (
+ IPv6(src="1234::1", dst=sidlist1[segleft1])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist1, segleft=segleft1, nh=43)
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist2, segleft=segleft2, nh=41)
+ / IPv6(src="4321::1", dst=dst)
+ / UDP(sport=1234, dport=1234)
+ )
return p
def create_packet_header_IPv4(self, dst):
@@ -1953,8 +2100,7 @@ class TestSRv6(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IP(src='123.1.1.1', dst=dst) /
- UDP(sport=1234, dport=1234))
+ p = IP(src="123.1.1.1", dst=dst) / UDP(sport=1234, dport=1234)
return p
def create_packet_header_IPv6_IPv4(self, dst_inner, dst_outer):
@@ -1969,9 +2115,11 @@ class TestSRv6(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IPv6(src='1234::1', dst=dst_outer) /
- IP(src='123.1.1.1', dst=dst_inner) /
- UDP(sport=1234, dport=1234))
+ p = (
+ IPv6(src="1234::1", dst=dst_outer)
+ / IP(src="123.1.1.1", dst=dst_inner)
+ / UDP(sport=1234, dport=1234)
+ )
return p
def create_packet_header_IPv6_SRH_IPv4(self, dst, sidlist, segleft):
@@ -1988,11 +2136,12 @@ class TestSRv6(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IPv6(src='1234::1', dst=sidlist[segleft]) /
- IPv6ExtHdrSegmentRouting(addresses=sidlist,
- segleft=segleft, nh=4) /
- IP(src='123.1.1.1', dst=dst) /
- UDP(sport=1234, dport=1234))
+ p = (
+ IPv6(src="1234::1", dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=4)
+ / IP(src="123.1.1.1", dst=dst)
+ / UDP(sport=1234, dport=1234)
+ )
return p
def create_packet_header_L2(self, vlan=0):
@@ -2003,7 +2152,7 @@ class TestSRv6(VppTestCase):
# Note: the dst addr ('00:55:44:33:22:11') is used in
# the compare function compare_rx_tx_packet_T_Encaps_L2
# to detect presence of L2 in SRH payload
- p = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11')
+ p = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11")
etype = 0x8137 # IPX
if vlan:
# add 802.1q layer
@@ -2023,7 +2172,7 @@ class TestSRv6(VppTestCase):
Outer IPv6 destination address is set to sidlist[segleft]
IPv6 source address is 1234::1
"""
- eth = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11')
+ eth = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11")
etype = 0x8137 # IPX
if vlan:
# add 802.1q layer
@@ -2031,10 +2180,11 @@ class TestSRv6(VppTestCase):
else:
eth.type = etype
- p = (IPv6(src='1234::1', dst=sidlist[segleft]) /
- IPv6ExtHdrSegmentRouting(addresses=sidlist,
- segleft=segleft, nh=143) /
- eth)
+ p = (
+ IPv6(src="1234::1", dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=143)
+ / eth
+ )
return p
def create_packet_header_IPv6_L2(self, dst_outer, vlan=0):
@@ -2044,7 +2194,7 @@ class TestSRv6(VppTestCase):
:param ipv6address dst_outer: outer IPv6 destination address
:param vlan: L2 vlan; if vlan!=0 then add 802.1q header
"""
- eth = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11')
+ eth = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11")
etype = 0x8137 # IPX
if vlan:
# add 802.1q layer
@@ -2052,12 +2202,11 @@ class TestSRv6(VppTestCase):
else:
eth.type = etype
- p = (IPv6(src='1234::1', dst=dst_outer, nh=143) / eth)
+ p = IPv6(src="1234::1", dst=dst_outer, nh=143) / eth
return p
def get_payload_info(self, packet):
- """ Extract the payload_info from the packet
- """
+ """Extract the payload_info from the packet"""
# in most cases, payload_info is in packet[Raw]
# but packet[Raw] gives the complete payload
# (incl L2 header) for the T.Encaps L2 case
@@ -2068,8 +2217,7 @@ class TestSRv6(VppTestCase):
# remote L2 header from packet[Raw]:
# take packet[Raw], convert it to an Ether layer
# and then extract Raw from it
- payload_info = self.payload_to_info(
- Ether(scapy.compat.r(packet[Raw]))[Raw])
+ payload_info = self.payload_to_info(Ether(scapy.compat.r(packet[Raw]))[Raw])
return payload_info
@@ -2082,8 +2230,10 @@ class TestSRv6(VppTestCase):
:param capture: captured packets
:param compare_func: function to compare in and out packet
"""
- self.logger.info("Verifying capture on interface %s using function %s"
- % (dst_if.name, compare_func.__name__))
+ self.logger.info(
+ "Verifying capture on interface %s using function %s"
+ % (dst_if.name, compare_func.__name__)
+ )
last_info = dict()
for i in self.pg_interfaces:
@@ -2096,19 +2246,19 @@ class TestSRv6(VppTestCase):
payload_info = self.get_payload_info(packet)
packet_index = payload_info.index
- self.logger.debug("Verifying packet with index %d"
- % (packet_index))
+ self.logger.debug("Verifying packet with index %d" % (packet_index))
# packet should have arrived on the expected interface
self.assertEqual(payload_info.dst, dst_sw_if_index)
self.logger.debug(
- "Got packet on interface %s: src=%u (idx=%u)" %
- (dst_if.name, payload_info.src, packet_index))
+ "Got packet on interface %s: src=%u (idx=%u)"
+ % (dst_if.name, payload_info.src, packet_index)
+ )
# search for payload_info with same src and dst if_index
# this will give us the transmitted packet
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
# next_info should not be None
self.assertTrue(next_info is not None)
@@ -2117,8 +2267,9 @@ class TestSRv6(VppTestCase):
# data field of next_info contains the tx packet
txed_packet = next_info.data
- self.logger.debug(ppp("Transmitted packet:",
- txed_packet)) # ppp=Pretty Print Packet
+ self.logger.debug(
+ ppp("Transmitted packet:", txed_packet)
+ ) # ppp=Pretty Print Packet
self.logger.debug(ppp("Received packet:", packet))
@@ -2143,5 +2294,5 @@ class TestSRv6(VppTestCase):
# "didn't arrive" % (dst_if.name, i.name))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_srv6_ad.py b/test/test_srv6_ad.py
index dad7c186a93..88c0b1d8074 100644
--- a/test/test_srv6_ad.py
+++ b/test/test_srv6_ad.py
@@ -7,8 +7,14 @@ from socket import AF_INET6
from framework import VppTestCase, VppTestRunner
from vpp_ip import DpoProto
from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpTable
-from vpp_srv6 import SRv6LocalSIDBehaviors, VppSRv6LocalSID, VppSRv6Policy, \
- SRv6PolicyType, VppSRv6Steering, SRv6PolicySteeringTypes
+from vpp_srv6 import (
+ SRv6LocalSIDBehaviors,
+ VppSRv6LocalSID,
+ VppSRv6Policy,
+ SRv6PolicyType,
+ VppSRv6Steering,
+ SRv6PolicySteeringTypes,
+)
import scapy.compat
from scapy.packet import Raw
@@ -20,7 +26,7 @@ from util import ppp
class TestSRv6Ad(VppTestCase):
- """ SRv6 Dynamic Proxy plugin Test Case """
+ """SRv6 Dynamic Proxy plugin Test Case"""
@classmethod
def setUpClass(self):
@@ -31,8 +37,7 @@ class TestSRv6Ad(VppTestCase):
super(TestSRv6Ad, cls).tearDownClass()
def setUp(self):
- """ Perform test setup before each test case.
- """
+ """Perform test setup before each test case."""
super(TestSRv6Ad, self).setUp()
# packet sizes, inclusive L2 overhead
@@ -42,17 +47,15 @@ class TestSRv6Ad(VppTestCase):
self.reset_packet_infos()
def tearDown(self):
- """ Clean up test setup after each test case.
- """
+ """Clean up test setup after each test case."""
self.teardown_interfaces()
super(TestSRv6Ad, self).tearDown()
- def configure_interface(self,
- interface,
- ipv6=False, ipv4=False,
- ipv6_table_id=0, ipv4_table_id=0):
- """ Configure interface.
+ def configure_interface(
+ self, interface, ipv6=False, ipv4=False, ipv6_table_id=0, ipv4_table_id=0
+ ):
+ """Configure interface.
:param ipv6: configure IPv6 on interface
:param ipv4: configure IPv4 on interface
:param ipv6_table_id: FIB table_id for IPv6
@@ -71,9 +74,8 @@ class TestSRv6Ad(VppTestCase):
interface.resolve_arp()
interface.admin_up()
- def setup_interfaces(self, ipv6=[], ipv4=[],
- ipv6_table_id=[], ipv4_table_id=[]):
- """ Create and configure interfaces.
+ def setup_interfaces(self, ipv6=[], ipv4=[], ipv6_table_id=[], ipv4_table_id=[]):
+ """Create and configure interfaces.
:param ipv6: list of interface IPv6 capabilities
:param ipv4: list of interface IPv4 capabilities
@@ -108,9 +110,9 @@ class TestSRv6Ad(VppTestCase):
# setup all interfaces
for i in range(count):
intf = self.pg_interfaces[i]
- self.configure_interface(intf,
- ipv6[i], ipv4[i],
- ipv6_table_id[i], ipv4_table_id[i])
+ self.configure_interface(
+ intf, ipv6[i], ipv4[i], ipv6_table_id[i], ipv4_table_id[i]
+ )
if any(ipv6):
self.logger.debug(self.vapi.cli("show ip6 neighbors"))
@@ -122,8 +124,7 @@ class TestSRv6Ad(VppTestCase):
return self.pg_interfaces
def teardown_interfaces(self):
- """ Unconfigure and bring down interface.
- """
+ """Unconfigure and bring down interface."""
self.logger.debug("Tearing down interfaces")
# tear down all interfaces
# AFAIK they cannot be deleted
@@ -135,10 +136,9 @@ class TestSRv6Ad(VppTestCase):
i.set_table_ip6(0)
def test_SRv6_End_AD_IPv6(self):
- """ Test SRv6 End.AD behavior with IPv6 traffic.
- """
- self.src_addr = 'a0::'
- self.sid_list = ['a1::', 'a2::a6', 'a3::']
+ """Test SRv6 End.AD behavior with IPv6 traffic."""
+ self.src_addr = "a0::"
+ self.sid_list = ["a1::", "a2::a6", "a3::"]
self.test_sid_index = 1
# send traffic to one destination interface
@@ -146,19 +146,32 @@ class TestSRv6Ad(VppTestCase):
self.setup_interfaces(ipv6=[True, True])
# configure route to next segment
- route = VppIpRoute(self, self.sid_list[self.test_sid_index + 1], 128,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index,
- proto=DpoProto.DPO_PROTO_IP6)])
+ route = VppIpRoute(
+ self,
+ self.sid_list[self.test_sid_index + 1],
+ 128,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip6,
+ self.pg0.sw_if_index,
+ proto=DpoProto.DPO_PROTO_IP6,
+ )
+ ],
+ )
route.add_vpp_config()
# configure SRv6 localSID behavior
- cli_str = "sr localsid address " + \
- self.sid_list[self.test_sid_index] + \
- " behavior end.ad" + \
- " nh " + self.pg1.remote_ip6 + \
- " oif " + self.pg1.name + \
- " iif " + self.pg1.name
+ cli_str = (
+ "sr localsid address "
+ + self.sid_list[self.test_sid_index]
+ + " behavior end.ad"
+ + " nh "
+ + self.pg1.remote_ip6
+ + " oif "
+ + self.pg1.name
+ + " iif "
+ + self.pg1.name
+ )
self.vapi.cli(cli_str)
# log the localsids
@@ -171,15 +184,18 @@ class TestSRv6Ad(VppTestCase):
packet_header1 = self.create_packet_header_IPv6_SRH_IPv6(
srcaddr=self.src_addr,
sidlist=self.sid_list[::-1],
- segleft=len(self.sid_list) - self.test_sid_index - 1)
+ segleft=len(self.sid_list) - self.test_sid_index - 1,
+ )
# generate packets (pg0->pg1)
- pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1,
- self.pg_packet_sizes, count)
+ pkts1 = self.create_stream(
+ self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts1, self.pg1,
- self.compare_rx_tx_packet_End_AD_IPv6_out)
+ self.send_and_verify_pkts(
+ self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AD_IPv6_out
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -188,26 +204,27 @@ class TestSRv6Ad(VppTestCase):
packet_header2 = self.create_packet_header_IPv6()
# generate returning packets (pg1->pg0)
- pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2,
- self.pg_packet_sizes, count)
+ pkts2 = self.create_stream(
+ self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg1, pkts2, self.pg0,
- self.compare_rx_tx_packet_End_AD_IPv6_in)
+ self.send_and_verify_pkts(
+ self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AD_IPv6_in
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
# remove SRv6 localSIDs
- cli_str = "sr localsid del address " + \
- self.sid_list[self.test_sid_index]
+ cli_str = "sr localsid del address " + self.sid_list[self.test_sid_index]
self.vapi.cli(cli_str)
# cleanup interfaces
self.teardown_interfaces()
def compare_rx_tx_packet_End_AD_IPv6_out(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AD with IPv6
+ """Compare input and output packet after passing End.AD with IPv6
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -232,7 +249,7 @@ class TestSRv6Ad(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_AD_IPv6_in(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AD
+ """Compare input and output packet after passing End.AD
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -253,8 +270,7 @@ class TestSRv6Ad(VppTestCase):
# rx'ed seglist should be equal to SID-list in reversed order
self.assertEqual(rx_srh.addresses, self.sid_list[::-1])
# segleft should be equal to previous segleft value minus 1
- self.assertEqual(rx_srh.segleft,
- len(self.sid_list) - self.test_sid_index - 2)
+ self.assertEqual(rx_srh.segleft, len(self.sid_list) - self.test_sid_index - 2)
# lastentry should be equal to the SID-list length minus 1
self.assertEqual(rx_srh.lastentry, len(self.sid_list) - 1)
@@ -269,10 +285,9 @@ class TestSRv6Ad(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def test_SRv6_End_AD_IPv4(self):
- """ Test SRv6 End.AD behavior with IPv4 traffic.
- """
- self.src_addr = 'a0::'
- self.sid_list = ['a1::', 'a2::a4', 'a3::']
+ """Test SRv6 End.AD behavior with IPv4 traffic."""
+ self.src_addr = "a0::"
+ self.sid_list = ["a1::", "a2::a4", "a3::"]
self.test_sid_index = 1
# send traffic to one destination interface
@@ -280,19 +295,32 @@ class TestSRv6Ad(VppTestCase):
self.setup_interfaces(ipv6=[True, False], ipv4=[False, True])
# configure route to next segment
- route = VppIpRoute(self, self.sid_list[self.test_sid_index + 1], 128,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index,
- proto=DpoProto.DPO_PROTO_IP6)])
+ route = VppIpRoute(
+ self,
+ self.sid_list[self.test_sid_index + 1],
+ 128,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip6,
+ self.pg0.sw_if_index,
+ proto=DpoProto.DPO_PROTO_IP6,
+ )
+ ],
+ )
route.add_vpp_config()
# configure SRv6 localSID behavior
- cli_str = "sr localsid address " + \
- self.sid_list[self.test_sid_index] + \
- " behavior end.ad" + \
- " nh " + self.pg1.remote_ip4 + \
- " oif " + self.pg1.name + \
- " iif " + self.pg1.name
+ cli_str = (
+ "sr localsid address "
+ + self.sid_list[self.test_sid_index]
+ + " behavior end.ad"
+ + " nh "
+ + self.pg1.remote_ip4
+ + " oif "
+ + self.pg1.name
+ + " iif "
+ + self.pg1.name
+ )
self.vapi.cli(cli_str)
# log the localsids
@@ -305,15 +333,18 @@ class TestSRv6Ad(VppTestCase):
packet_header1 = self.create_packet_header_IPv6_SRH_IPv4(
srcaddr=self.src_addr,
sidlist=self.sid_list[::-1],
- segleft=len(self.sid_list) - self.test_sid_index - 1)
+ segleft=len(self.sid_list) - self.test_sid_index - 1,
+ )
# generate packets (pg0->pg1)
- pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1,
- self.pg_packet_sizes, count)
+ pkts1 = self.create_stream(
+ self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts1, self.pg1,
- self.compare_rx_tx_packet_End_AD_IPv4_out)
+ self.send_and_verify_pkts(
+ self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AD_IPv4_out
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -322,26 +353,27 @@ class TestSRv6Ad(VppTestCase):
packet_header2 = self.create_packet_header_IPv4()
# generate returning packets (pg1->pg0)
- pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2,
- self.pg_packet_sizes, count)
+ pkts2 = self.create_stream(
+ self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg1, pkts2, self.pg0,
- self.compare_rx_tx_packet_End_AD_IPv4_in)
+ self.send_and_verify_pkts(
+ self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AD_IPv4_in
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
# remove SRv6 localSIDs
- cli_str = "sr localsid del address " + \
- self.sid_list[self.test_sid_index]
+ cli_str = "sr localsid del address " + self.sid_list[self.test_sid_index]
self.vapi.cli(cli_str)
# cleanup interfaces
self.teardown_interfaces()
def compare_rx_tx_packet_End_AD_IPv4_out(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AD with IPv4
+ """Compare input and output packet after passing End.AD with IPv4
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -371,7 +403,7 @@ class TestSRv6Ad(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_AD_IPv4_in(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AD
+ """Compare input and output packet after passing End.AD
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -392,8 +424,7 @@ class TestSRv6Ad(VppTestCase):
# rx'ed seglist should be equal to SID-list in reversed order
self.assertEqual(rx_srh.addresses, self.sid_list[::-1])
# segleft should be equal to previous segleft value minus 1
- self.assertEqual(rx_srh.segleft,
- len(self.sid_list) - self.test_sid_index - 2)
+ self.assertEqual(rx_srh.segleft, len(self.sid_list) - self.test_sid_index - 2)
# lastentry should be equal to the SID-list length minus 1
self.assertEqual(rx_srh.lastentry, len(self.sid_list) - 1)
@@ -411,10 +442,9 @@ class TestSRv6Ad(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def test_SRv6_End_AD_L2(self):
- """ Test SRv6 End.AD behavior with L2 traffic.
- """
- self.src_addr = 'a0::'
- self.sid_list = ['a1::', 'a2::a4', 'a3::']
+ """Test SRv6 End.AD behavior with L2 traffic."""
+ self.src_addr = "a0::"
+ self.sid_list = ["a1::", "a2::a4", "a3::"]
self.test_sid_index = 1
# send traffic to one destination interface
@@ -422,18 +452,30 @@ class TestSRv6Ad(VppTestCase):
self.setup_interfaces(ipv6=[True, False])
# configure route to next segment
- route = VppIpRoute(self, self.sid_list[self.test_sid_index + 1], 128,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index,
- proto=DpoProto.DPO_PROTO_IP6)])
+ route = VppIpRoute(
+ self,
+ self.sid_list[self.test_sid_index + 1],
+ 128,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip6,
+ self.pg0.sw_if_index,
+ proto=DpoProto.DPO_PROTO_IP6,
+ )
+ ],
+ )
route.add_vpp_config()
# configure SRv6 localSID behavior
- cli_str = "sr localsid address " + \
- self.sid_list[self.test_sid_index] + \
- " behavior end.ad" + \
- " oif " + self.pg1.name + \
- " iif " + self.pg1.name
+ cli_str = (
+ "sr localsid address "
+ + self.sid_list[self.test_sid_index]
+ + " behavior end.ad"
+ + " oif "
+ + self.pg1.name
+ + " iif "
+ + self.pg1.name
+ )
self.vapi.cli(cli_str)
# log the localsids
@@ -447,15 +489,18 @@ class TestSRv6Ad(VppTestCase):
srcaddr=self.src_addr,
sidlist=self.sid_list[::-1],
segleft=len(self.sid_list) - self.test_sid_index - 1,
- vlan=0)
+ vlan=0,
+ )
# generate packets (pg0->pg1)
- pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1,
- self.pg_packet_sizes, count)
+ pkts1 = self.create_stream(
+ self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts1, self.pg1,
- self.compare_rx_tx_packet_End_AD_L2_out)
+ self.send_and_verify_pkts(
+ self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AD_L2_out
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -464,26 +509,27 @@ class TestSRv6Ad(VppTestCase):
packet_header2 = self.create_packet_header_L2()
# generate returning packets (pg1->pg0)
- pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2,
- self.pg_packet_sizes, count)
+ pkts2 = self.create_stream(
+ self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg1, pkts2, self.pg0,
- self.compare_rx_tx_packet_End_AD_L2_in)
+ self.send_and_verify_pkts(
+ self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AD_L2_in
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
# remove SRv6 localSIDs
- cli_str = "sr localsid del address " + \
- self.sid_list[self.test_sid_index]
+ cli_str = "sr localsid del address " + self.sid_list[self.test_sid_index]
self.vapi.cli(cli_str)
# cleanup interfaces
self.teardown_interfaces()
def compare_rx_tx_packet_End_AD_L2_out(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AD with L2
+ """Compare input and output packet after passing End.AD with L2
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -506,7 +552,7 @@ class TestSRv6Ad(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_AD_L2_in(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AD
+ """Compare input and output packet after passing End.AD
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -528,8 +574,7 @@ class TestSRv6Ad(VppTestCase):
# rx'ed seglist should be equal to SID-list in reversed order
self.assertEqual(rx_srh.addresses, self.sid_list[::-1])
# segleft should be equal to previous segleft value minus 1
- self.assertEqual(rx_srh.segleft,
- len(self.sid_list) - self.test_sid_index - 2)
+ self.assertEqual(rx_srh.segleft, len(self.sid_list) - self.test_sid_index - 2)
# lastentry should be equal to the SID-list length minus 1
self.assertEqual(rx_srh.lastentry, len(self.sid_list) - 1)
@@ -539,8 +584,7 @@ class TestSRv6Ad(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
- def create_stream(self, src_if, dst_if, packet_header, packet_sizes,
- count):
+ def create_stream(self, src_if, dst_if, packet_header, packet_sizes, count):
"""Create SRv6 input packet stream for defined interface.
:param VppInterface src_if: Interface to create packet stream for
@@ -557,15 +601,17 @@ class TestSRv6Ad(VppTestCase):
pkts = []
for i in range(0, count - 1):
payload_info = self.create_packet_info(src_if, dst_if)
- self.logger.debug(
- "Creating packet with index %d" % (payload_info.index))
+ self.logger.debug("Creating packet with index %d" % (payload_info.index))
payload = self.info_to_payload(payload_info)
# add L2 header if not yet provided in packet_header
- if packet_header.getlayer(0).name == 'Ethernet':
+ if packet_header.getlayer(0).name == "Ethernet":
p = packet_header / Raw(payload)
else:
- p = Ether(dst=src_if.local_mac, src=src_if.remote_mac) / \
- packet_header / Raw(payload)
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / packet_header
+ / Raw(payload)
+ )
size = packet_sizes[i % len(packet_sizes)]
self.logger.debug("Packet size %d" % (size))
self.extend_packet(p, size)
@@ -618,7 +664,7 @@ class TestSRv6Ad(VppTestCase):
UDP source port and destination port are 1234
"""
- p = IPv6(src='1234::1', dst='4321::1') / UDP(sport=1234, dport=1234)
+ p = IPv6(src="1234::1", dst="4321::1") / UDP(sport=1234, dport=1234)
return p
def create_packet_header_IPv6_SRH_IPv6(self, srcaddr, sidlist, segleft):
@@ -636,11 +682,12 @@ class TestSRv6Ad(VppTestCase):
UDP source port and destination port are 1234
"""
- p = IPv6(src=srcaddr, dst=sidlist[segleft]) / \
- IPv6ExtHdrSegmentRouting(addresses=sidlist,
- segleft=segleft, nh=41) / \
- IPv6(src='1234::1', dst='4321::1') / \
- UDP(sport=1234, dport=1234)
+ p = (
+ IPv6(src=srcaddr, dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=41)
+ / IPv6(src="1234::1", dst="4321::1")
+ / UDP(sport=1234, dport=1234)
+ )
return p
def create_packet_header_IPv4(self):
@@ -653,7 +700,7 @@ class TestSRv6Ad(VppTestCase):
UDP source port and destination port are 1234
"""
- p = IP(src='123.1.1.1', dst='124.1.1.1') / UDP(sport=1234, dport=1234)
+ p = IP(src="123.1.1.1", dst="124.1.1.1") / UDP(sport=1234, dport=1234)
return p
def create_packet_header_IPv6_SRH_IPv4(self, srcaddr, sidlist, segleft):
@@ -671,11 +718,12 @@ class TestSRv6Ad(VppTestCase):
UDP source port and destination port are 1234
"""
- p = IPv6(src=srcaddr, dst=sidlist[segleft]) / \
- IPv6ExtHdrSegmentRouting(addresses=sidlist,
- segleft=segleft, nh=4) / \
- IP(src='123.1.1.1', dst='124.1.1.1') / \
- UDP(sport=1234, dport=1234)
+ p = (
+ IPv6(src=srcaddr, dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=4)
+ / IP(src="123.1.1.1", dst="124.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ )
return p
def create_packet_header_L2(self, vlan=0):
@@ -686,7 +734,7 @@ class TestSRv6Ad(VppTestCase):
# Note: the dst addr ('00:55:44:33:22:11') is used in
# the compare function compare_rx_tx_packet_T_Encaps_L2
# to detect presence of L2 in SRH payload
- p = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11')
+ p = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11")
etype = 0x8137 # IPX
if vlan:
# add 802.1q layer
@@ -695,8 +743,7 @@ class TestSRv6Ad(VppTestCase):
p.type = etype
return p
- def create_packet_header_IPv6_SRH_L2(self, srcaddr, sidlist, segleft,
- vlan=0):
+ def create_packet_header_IPv6_SRH_L2(self, srcaddr, sidlist, segleft, vlan=0):
"""Create packet header: L2 encapsulated in SRv6:
IPv6 header with SRH, L2
@@ -708,7 +755,7 @@ class TestSRv6Ad(VppTestCase):
IPv6 source address is set to srcaddr
IPv6 destination address is set to sidlist[segleft]
"""
- eth = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11')
+ eth = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11")
etype = 0x8137 # IPX
if vlan:
# add 802.1q layer
@@ -716,15 +763,15 @@ class TestSRv6Ad(VppTestCase):
else:
eth.type = etype
- p = IPv6(src=srcaddr, dst=sidlist[segleft]) / \
- IPv6ExtHdrSegmentRouting(addresses=sidlist,
- segleft=segleft, nh=143) / \
- eth
+ p = (
+ IPv6(src=srcaddr, dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=143)
+ / eth
+ )
return p
def get_payload_info(self, packet):
- """ Extract the payload_info from the packet
- """
+ """Extract the payload_info from the packet"""
# in most cases, payload_info is in packet[Raw]
# but packet[Raw] gives the complete payload
# (incl L2 header) for the T.Encaps L2 case
@@ -736,7 +783,8 @@ class TestSRv6Ad(VppTestCase):
# take packet[Raw], convert it to an Ether layer
# and then extract Raw from it
payload_info = self.payload_to_info(
- Ether(scapy.compat.raw(packet[Raw]))[Raw])
+ Ether(scapy.compat.raw(packet[Raw]))[Raw]
+ )
return payload_info
@@ -749,8 +797,10 @@ class TestSRv6Ad(VppTestCase):
:param capture: captured packets
:param compare_func: function to compare in and out packet
"""
- self.logger.info("Verifying capture on interface %s using function %s"
- % (dst_if.name, compare_func.__name__))
+ self.logger.info(
+ "Verifying capture on interface %s using function %s"
+ % (dst_if.name, compare_func.__name__)
+ )
last_info = dict()
for i in self.pg_interfaces:
@@ -763,19 +813,19 @@ class TestSRv6Ad(VppTestCase):
payload_info = self.get_payload_info(packet)
packet_index = payload_info.index
- self.logger.debug("Verifying packet with index %d"
- % (packet_index))
+ self.logger.debug("Verifying packet with index %d" % (packet_index))
# packet should have arrived on the expected interface
self.assertEqual(payload_info.dst, dst_sw_if_index)
self.logger.debug(
- "Got packet on interface %s: src=%u (idx=%u)" %
- (dst_if.name, payload_info.src, packet_index))
+ "Got packet on interface %s: src=%u (idx=%u)"
+ % (dst_if.name, payload_info.src, packet_index)
+ )
# search for payload_info with same src and dst if_index
# this will give us the transmitted packet
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
# next_info should not be None
self.assertTrue(next_info is not None)
@@ -784,8 +834,9 @@ class TestSRv6Ad(VppTestCase):
# data field of next_info contains the tx packet
txed_packet = next_info.data
- self.logger.debug(ppp("Transmitted packet:",
- txed_packet)) # ppp=Pretty Print Packet
+ self.logger.debug(
+ ppp("Transmitted packet:", txed_packet)
+ ) # ppp=Pretty Print Packet
self.logger.debug(ppp("Received packet:", packet))
@@ -799,11 +850,14 @@ class TestSRv6Ad(VppTestCase):
# have all expected packets arrived?
for i in self.pg_interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index])
- self.assertTrue(remaining_packet is None,
- "Interface %s: Packet expected from interface %s "
- "didn't arrive" % (dst_if.name, i.name))
+ i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]
+ )
+ self.assertTrue(
+ remaining_packet is None,
+ "Interface %s: Packet expected from interface %s "
+ "didn't arrive" % (dst_if.name, i.name),
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_srv6_ad_flow.py b/test/test_srv6_ad_flow.py
index 6b4ec19a31b..4b274c92232 100644
--- a/test/test_srv6_ad_flow.py
+++ b/test/test_srv6_ad_flow.py
@@ -18,7 +18,7 @@ from util import ppp
class TestSRv6AdFlow(VppTestCase):
- """ SRv6 Flow-based Dynamic Proxy plugin Test Case """
+ """SRv6 Flow-based Dynamic Proxy plugin Test Case"""
@classmethod
def setUpClass(self):
@@ -29,8 +29,7 @@ class TestSRv6AdFlow(VppTestCase):
super(TestSRv6AdFlow, cls).tearDownClass()
def setUp(self):
- """ Perform test setup before each test case.
- """
+ """Perform test setup before each test case."""
super(TestSRv6AdFlow, self).setUp()
# packet sizes, inclusive L2 overhead
@@ -40,17 +39,15 @@ class TestSRv6AdFlow(VppTestCase):
self.reset_packet_infos()
def tearDown(self):
- """ Clean up test setup after each test case.
- """
+ """Clean up test setup after each test case."""
self.teardown_interfaces()
super(TestSRv6AdFlow, self).tearDown()
- def configure_interface(self,
- interface,
- ipv6=False, ipv4=False,
- ipv6_table_id=0, ipv4_table_id=0):
- """ Configure interface.
+ def configure_interface(
+ self, interface, ipv6=False, ipv4=False, ipv6_table_id=0, ipv4_table_id=0
+ ):
+ """Configure interface.
:param ipv6: configure IPv6 on interface
:param ipv4: configure IPv4 on interface
:param ipv6_table_id: FIB table_id for IPv6
@@ -69,9 +66,8 @@ class TestSRv6AdFlow(VppTestCase):
interface.resolve_arp()
interface.admin_up()
- def setup_interfaces(self, ipv6=[], ipv4=[],
- ipv6_table_id=[], ipv4_table_id=[]):
- """ Create and configure interfaces.
+ def setup_interfaces(self, ipv6=[], ipv4=[], ipv6_table_id=[], ipv4_table_id=[]):
+ """Create and configure interfaces.
:param ipv6: list of interface IPv6 capabilities
:param ipv4: list of interface IPv4 capabilities
@@ -106,9 +102,9 @@ class TestSRv6AdFlow(VppTestCase):
# setup all interfaces
for i in range(count):
intf = self.pg_interfaces[i]
- self.configure_interface(intf,
- ipv6[i], ipv4[i],
- ipv6_table_id[i], ipv4_table_id[i])
+ self.configure_interface(
+ intf, ipv6[i], ipv4[i], ipv6_table_id[i], ipv4_table_id[i]
+ )
if any(ipv6):
self.logger.debug(self.vapi.cli("show ip6 neighbors"))
@@ -120,8 +116,7 @@ class TestSRv6AdFlow(VppTestCase):
return self.pg_interfaces
def teardown_interfaces(self):
- """ Unconfigure and bring down interface.
- """
+ """Unconfigure and bring down interface."""
self.logger.debug("Tearing down interfaces")
# tear down all interfaces
# AFAIK they cannot be deleted
@@ -133,10 +128,9 @@ class TestSRv6AdFlow(VppTestCase):
i.set_table_ip6(0)
def test_SRv6_End_AD_IPv6(self):
- """ Test SRv6 End.AD behavior with IPv6 traffic.
- """
- self.src_addr = 'a0::'
- self.sid_list = ['a1::', 'a2::a6', 'a3::']
+ """Test SRv6 End.AD behavior with IPv6 traffic."""
+ self.src_addr = "a0::"
+ self.sid_list = ["a1::", "a2::a6", "a3::"]
self.test_sid_index = 1
# send traffic to one destination interface
@@ -144,19 +138,32 @@ class TestSRv6AdFlow(VppTestCase):
self.setup_interfaces(ipv6=[True, True])
# configure route to next segment
- route = VppIpRoute(self, self.sid_list[self.test_sid_index + 1], 128,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index,
- proto=DpoProto.DPO_PROTO_IP6)])
+ route = VppIpRoute(
+ self,
+ self.sid_list[self.test_sid_index + 1],
+ 128,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip6,
+ self.pg0.sw_if_index,
+ proto=DpoProto.DPO_PROTO_IP6,
+ )
+ ],
+ )
route.add_vpp_config()
# configure SRv6 localSID behavior
- cli_str = "sr localsid address " + \
- self.sid_list[self.test_sid_index] + \
- " behavior end.ad.flow" + \
- " nh " + self.pg1.remote_ip6 + \
- " oif " + self.pg1.name + \
- " iif " + self.pg1.name
+ cli_str = (
+ "sr localsid address "
+ + self.sid_list[self.test_sid_index]
+ + " behavior end.ad.flow"
+ + " nh "
+ + self.pg1.remote_ip6
+ + " oif "
+ + self.pg1.name
+ + " iif "
+ + self.pg1.name
+ )
self.vapi.cli(cli_str)
# log the localsids
@@ -169,15 +176,18 @@ class TestSRv6AdFlow(VppTestCase):
packet_header1 = self.create_packet_header_IPv6_SRH_IPv6(
srcaddr=self.src_addr,
sidlist=self.sid_list[::-1],
- segleft=len(self.sid_list) - self.test_sid_index - 1)
+ segleft=len(self.sid_list) - self.test_sid_index - 1,
+ )
# generate packets (pg0->pg1)
- pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1,
- self.pg_packet_sizes, count)
+ pkts1 = self.create_stream(
+ self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts1, self.pg1,
- self.compare_rx_tx_packet_End_AD_IPv6_out)
+ self.send_and_verify_pkts(
+ self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AD_IPv6_out
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -186,26 +196,27 @@ class TestSRv6AdFlow(VppTestCase):
packet_header2 = self.create_packet_header_IPv6()
# generate returning packets (pg1->pg0)
- pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2,
- self.pg_packet_sizes, count)
+ pkts2 = self.create_stream(
+ self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg1, pkts2, self.pg0,
- self.compare_rx_tx_packet_End_AD_IPv6_in)
+ self.send_and_verify_pkts(
+ self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AD_IPv6_in
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
# remove SRv6 localSIDs
- cli_str = "sr localsid del address " + \
- self.sid_list[self.test_sid_index]
+ cli_str = "sr localsid del address " + self.sid_list[self.test_sid_index]
self.vapi.cli(cli_str)
# cleanup interfaces
self.teardown_interfaces()
def compare_rx_tx_packet_End_AD_IPv6_out(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AD with IPv6
+ """Compare input and output packet after passing End.AD with IPv6
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -230,7 +241,7 @@ class TestSRv6AdFlow(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_AD_IPv6_in(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AD
+ """Compare input and output packet after passing End.AD
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -251,8 +262,7 @@ class TestSRv6AdFlow(VppTestCase):
# rx'ed seglist should be equal to SID-list in reversed order
self.assertEqual(rx_srh.addresses, self.sid_list[::-1])
# segleft should be equal to previous segleft value minus 1
- self.assertEqual(rx_srh.segleft,
- len(self.sid_list) - self.test_sid_index - 2)
+ self.assertEqual(rx_srh.segleft, len(self.sid_list) - self.test_sid_index - 2)
# lastentry should be equal to the SID-list length minus 1
self.assertEqual(rx_srh.lastentry, len(self.sid_list) - 1)
@@ -267,10 +277,9 @@ class TestSRv6AdFlow(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def test_SRv6_End_AD_IPv4(self):
- """ Test SRv6 End.AD behavior with IPv4 traffic.
- """
- self.src_addr = 'a0::'
- self.sid_list = ['a1::', 'a2::a4', 'a3::']
+ """Test SRv6 End.AD behavior with IPv4 traffic."""
+ self.src_addr = "a0::"
+ self.sid_list = ["a1::", "a2::a4", "a3::"]
self.test_sid_index = 1
# send traffic to one destination interface
@@ -278,19 +287,32 @@ class TestSRv6AdFlow(VppTestCase):
self.setup_interfaces(ipv6=[True, False], ipv4=[False, True])
# configure route to next segment
- route = VppIpRoute(self, self.sid_list[self.test_sid_index + 1], 128,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index,
- proto=DpoProto.DPO_PROTO_IP6)])
+ route = VppIpRoute(
+ self,
+ self.sid_list[self.test_sid_index + 1],
+ 128,
+ [
+ VppRoutePath(
+ self.pg0.remote_ip6,
+ self.pg0.sw_if_index,
+ proto=DpoProto.DPO_PROTO_IP6,
+ )
+ ],
+ )
route.add_vpp_config()
# configure SRv6 localSID behavior
- cli_str = "sr localsid address " + \
- self.sid_list[self.test_sid_index] + \
- " behavior end.ad.flow" + \
- " nh " + self.pg1.remote_ip4 + \
- " oif " + self.pg1.name + \
- " iif " + self.pg1.name
+ cli_str = (
+ "sr localsid address "
+ + self.sid_list[self.test_sid_index]
+ + " behavior end.ad.flow"
+ + " nh "
+ + self.pg1.remote_ip4
+ + " oif "
+ + self.pg1.name
+ + " iif "
+ + self.pg1.name
+ )
self.vapi.cli(cli_str)
# log the localsids
@@ -303,15 +325,18 @@ class TestSRv6AdFlow(VppTestCase):
packet_header1 = self.create_packet_header_IPv6_SRH_IPv4(
srcaddr=self.src_addr,
sidlist=self.sid_list[::-1],
- segleft=len(self.sid_list) - self.test_sid_index - 1)
+ segleft=len(self.sid_list) - self.test_sid_index - 1,
+ )
# generate packets (pg0->pg1)
- pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1,
- self.pg_packet_sizes, count)
+ pkts1 = self.create_stream(
+ self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts1, self.pg1,
- self.compare_rx_tx_packet_End_AD_IPv4_out)
+ self.send_and_verify_pkts(
+ self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AD_IPv4_out
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -320,26 +345,27 @@ class TestSRv6AdFlow(VppTestCase):
packet_header2 = self.create_packet_header_IPv4()
# generate returning packets (pg1->pg0)
- pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2,
- self.pg_packet_sizes, count)
+ pkts2 = self.create_stream(
+ self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg1, pkts2, self.pg0,
- self.compare_rx_tx_packet_End_AD_IPv4_in)
+ self.send_and_verify_pkts(
+ self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AD_IPv4_in
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
# remove SRv6 localSIDs
- cli_str = "sr localsid del address " + \
- self.sid_list[self.test_sid_index]
+ cli_str = "sr localsid del address " + self.sid_list[self.test_sid_index]
self.vapi.cli(cli_str)
# cleanup interfaces
self.teardown_interfaces()
def compare_rx_tx_packet_End_AD_IPv4_out(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AD with IPv4
+ """Compare input and output packet after passing End.AD with IPv4
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -369,7 +395,7 @@ class TestSRv6AdFlow(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_AD_IPv4_in(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AD
+ """Compare input and output packet after passing End.AD
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -390,8 +416,7 @@ class TestSRv6AdFlow(VppTestCase):
# rx'ed seglist should be equal to SID-list in reversed order
self.assertEqual(rx_srh.addresses, self.sid_list[::-1])
# segleft should be equal to previous segleft value minus 1
- self.assertEqual(rx_srh.segleft,
- len(self.sid_list) - self.test_sid_index - 2)
+ self.assertEqual(rx_srh.segleft, len(self.sid_list) - self.test_sid_index - 2)
# lastentry should be equal to the SID-list length minus 1
self.assertEqual(rx_srh.lastentry, len(self.sid_list) - 1)
@@ -408,8 +433,7 @@ class TestSRv6AdFlow(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
- def create_stream(self, src_if, dst_if, packet_header, packet_sizes,
- count):
+ def create_stream(self, src_if, dst_if, packet_header, packet_sizes, count):
"""Create SRv6 input packet stream for defined interface.
:param VppInterface src_if: Interface to create packet stream for
@@ -426,15 +450,17 @@ class TestSRv6AdFlow(VppTestCase):
pkts = []
for i in range(0, count - 1):
payload_info = self.create_packet_info(src_if, dst_if)
- self.logger.debug(
- "Creating packet with index %d" % (payload_info.index))
+ self.logger.debug("Creating packet with index %d" % (payload_info.index))
payload = self.info_to_payload(payload_info)
# add L2 header if not yet provided in packet_header
- if packet_header.getlayer(0).name == 'Ethernet':
+ if packet_header.getlayer(0).name == "Ethernet":
p = packet_header / Raw(payload)
else:
- p = Ether(dst=src_if.local_mac, src=src_if.remote_mac) / \
- packet_header / Raw(payload)
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / packet_header
+ / Raw(payload)
+ )
size = packet_sizes[i % len(packet_sizes)]
self.logger.debug("Packet size %d" % (size))
self.extend_packet(p, size)
@@ -477,8 +503,9 @@ class TestSRv6AdFlow(VppTestCase):
# verify captured packets
self.verify_captured_pkts(output, capture, compare_func)
- def create_packet_header_IPv6(self, saddr='1234::1', daddr='4321::1',
- sport=1234, dport=1234):
+ def create_packet_header_IPv6(
+ self, saddr="1234::1", daddr="4321::1", sport=1234, dport=1234
+ ):
"""Create packet header: IPv6 header, UDP header
:param dst: IPv6 destination address
@@ -491,9 +518,16 @@ class TestSRv6AdFlow(VppTestCase):
p = IPv6(src=saddr, dst=daddr) / UDP(sport=sport, dport=dport)
return p
- def create_packet_header_IPv6_SRH_IPv6(self, srcaddr, sidlist, segleft,
- insrc='1234::1', indst='4321::1',
- sport=1234, dport=1234):
+ def create_packet_header_IPv6_SRH_IPv6(
+ self,
+ srcaddr,
+ sidlist,
+ segleft,
+ insrc="1234::1",
+ indst="4321::1",
+ sport=1234,
+ dport=1234,
+ ):
"""Create packet header: IPv6 encapsulated in SRv6:
IPv6 header with SRH, IPv6 header, UDP header
@@ -508,11 +542,12 @@ class TestSRv6AdFlow(VppTestCase):
UDP source port and destination port are 1234
"""
- p = IPv6(src=srcaddr, dst=sidlist[segleft]) / \
- IPv6ExtHdrSegmentRouting(addresses=sidlist,
- segleft=segleft, nh=41) / \
- IPv6(src=insrc, dst=indst) / \
- UDP(sport=sport, dport=dport)
+ p = (
+ IPv6(src=srcaddr, dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=41)
+ / IPv6(src=insrc, dst=indst)
+ / UDP(sport=sport, dport=dport)
+ )
return p
def create_packet_header_IPv4(self):
@@ -525,7 +560,7 @@ class TestSRv6AdFlow(VppTestCase):
UDP source port and destination port are 1234
"""
- p = IP(src='123.1.1.1', dst='124.1.1.1') / UDP(sport=1234, dport=1234)
+ p = IP(src="123.1.1.1", dst="124.1.1.1") / UDP(sport=1234, dport=1234)
return p
def create_packet_header_IPv6_SRH_IPv4(self, srcaddr, sidlist, segleft):
@@ -543,16 +578,16 @@ class TestSRv6AdFlow(VppTestCase):
UDP source port and destination port are 1234
"""
- p = IPv6(src=srcaddr, dst=sidlist[segleft]) / \
- IPv6ExtHdrSegmentRouting(addresses=sidlist,
- segleft=segleft, nh=4) / \
- IP(src='123.1.1.1', dst='124.1.1.1') / \
- UDP(sport=1234, dport=1234)
+ p = (
+ IPv6(src=srcaddr, dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=4)
+ / IP(src="123.1.1.1", dst="124.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ )
return p
def get_payload_info(self, packet):
- """ Extract the payload_info from the packet
- """
+ """Extract the payload_info from the packet"""
# in most cases, payload_info is in packet[Raw]
# but packet[Raw] gives the complete payload
# (incl L2 header) for the T.Encaps L2 case
@@ -564,7 +599,8 @@ class TestSRv6AdFlow(VppTestCase):
# take packet[Raw], convert it to an Ether layer
# and then extract Raw from it
payload_info = self.payload_to_info(
- Ether(scapy.compat.raw(packet[Raw]))[Raw])
+ Ether(scapy.compat.raw(packet[Raw]))[Raw]
+ )
return payload_info
@@ -577,8 +613,10 @@ class TestSRv6AdFlow(VppTestCase):
:param capture: captured packets
:param compare_func: function to compare in and out packet
"""
- self.logger.info("Verifying capture on interface %s using function %s"
- % (dst_if.name, compare_func.__name__))
+ self.logger.info(
+ "Verifying capture on interface %s using function %s"
+ % (dst_if.name, compare_func.__name__)
+ )
last_info = dict()
for i in self.pg_interfaces:
@@ -591,19 +629,19 @@ class TestSRv6AdFlow(VppTestCase):
payload_info = self.get_payload_info(packet)
packet_index = payload_info.index
- self.logger.debug("Verifying packet with index %d"
- % (packet_index))
+ self.logger.debug("Verifying packet with index %d" % (packet_index))
# packet should have arrived on the expected interface
self.assertEqual(payload_info.dst, dst_sw_if_index)
self.logger.debug(
- "Got packet on interface %s: src=%u (idx=%u)" %
- (dst_if.name, payload_info.src, packet_index))
+ "Got packet on interface %s: src=%u (idx=%u)"
+ % (dst_if.name, payload_info.src, packet_index)
+ )
# search for payload_info with same src and dst if_index
# this will give us the transmitted packet
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
# next_info should not be None
self.assertTrue(next_info is not None)
@@ -612,8 +650,9 @@ class TestSRv6AdFlow(VppTestCase):
# data field of next_info contains the tx packet
txed_packet = next_info.data
- self.logger.debug(ppp("Transmitted packet:",
- txed_packet)) # ppp=Pretty Print Packet
+ self.logger.debug(
+ ppp("Transmitted packet:", txed_packet)
+ ) # ppp=Pretty Print Packet
self.logger.debug(ppp("Received packet:", packet))
@@ -627,11 +666,14 @@ class TestSRv6AdFlow(VppTestCase):
# have all expected packets arrived?
for i in self.pg_interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index])
- self.assertTrue(remaining_packet is None,
- "Interface %s: Packet expected from interface %s "
- "didn't arrive" % (dst_if.name, i.name))
+ i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]
+ )
+ self.assertTrue(
+ remaining_packet is None,
+ "Interface %s: Packet expected from interface %s "
+ "didn't arrive" % (dst_if.name, i.name),
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_srv6_as.py b/test/test_srv6_as.py
index 947633e7fab..87cafd1e5ed 100644
--- a/test/test_srv6_as.py
+++ b/test/test_srv6_as.py
@@ -6,8 +6,14 @@ from socket import AF_INET6
from framework import VppTestCase, VppTestRunner
from vpp_ip_route import VppIpRoute, VppRoutePath, FibPathProto, VppIpTable
-from vpp_srv6 import SRv6LocalSIDBehaviors, VppSRv6LocalSID, VppSRv6Policy, \
- SRv6PolicyType, VppSRv6Steering, SRv6PolicySteeringTypes
+from vpp_srv6 import (
+ SRv6LocalSIDBehaviors,
+ VppSRv6LocalSID,
+ VppSRv6Policy,
+ SRv6PolicyType,
+ VppSRv6Steering,
+ SRv6PolicySteeringTypes,
+)
import scapy.compat
from scapy.packet import Raw
@@ -19,7 +25,7 @@ from util import ppp
class TestSRv6As(VppTestCase):
- """ SRv6 Static Proxy plugin Test Case """
+ """SRv6 Static Proxy plugin Test Case"""
@classmethod
def setUpClass(self):
@@ -30,8 +36,7 @@ class TestSRv6As(VppTestCase):
super(TestSRv6As, cls).tearDownClass()
def setUp(self):
- """ Perform test setup before each test case.
- """
+ """Perform test setup before each test case."""
super(TestSRv6As, self).setUp()
# packet sizes, inclusive L2 overhead
@@ -41,17 +46,15 @@ class TestSRv6As(VppTestCase):
self.reset_packet_infos()
def tearDown(self):
- """ Clean up test setup after each test case.
- """
+ """Clean up test setup after each test case."""
self.teardown_interfaces()
super(TestSRv6As, self).tearDown()
- def configure_interface(self,
- interface,
- ipv6=False, ipv4=False,
- ipv6_table_id=0, ipv4_table_id=0):
- """ Configure interface.
+ def configure_interface(
+ self, interface, ipv6=False, ipv4=False, ipv6_table_id=0, ipv4_table_id=0
+ ):
+ """Configure interface.
:param ipv6: configure IPv6 on interface
:param ipv4: configure IPv4 on interface
:param ipv6_table_id: FIB table_id for IPv6
@@ -70,9 +73,8 @@ class TestSRv6As(VppTestCase):
interface.resolve_arp()
interface.admin_up()
- def setup_interfaces(self, ipv6=[], ipv4=[],
- ipv6_table_id=[], ipv4_table_id=[]):
- """ Create and configure interfaces.
+ def setup_interfaces(self, ipv6=[], ipv4=[], ipv6_table_id=[], ipv4_table_id=[]):
+ """Create and configure interfaces.
:param ipv6: list of interface IPv6 capabilities
:param ipv4: list of interface IPv4 capabilities
@@ -107,9 +109,9 @@ class TestSRv6As(VppTestCase):
# setup all interfaces
for i in range(count):
intf = self.pg_interfaces[i]
- self.configure_interface(intf,
- ipv6[i], ipv4[i],
- ipv6_table_id[i], ipv4_table_id[i])
+ self.configure_interface(
+ intf, ipv6[i], ipv4[i], ipv6_table_id[i], ipv4_table_id[i]
+ )
if any(ipv6):
self.logger.debug(self.vapi.cli("show ip6 neighbors"))
@@ -121,8 +123,7 @@ class TestSRv6As(VppTestCase):
return self.pg_interfaces
def teardown_interfaces(self):
- """ Unconfigure and bring down interface.
- """
+ """Unconfigure and bring down interface."""
self.logger.debug("Tearing down interfaces")
# tear down all interfaces
# AFAIK they cannot be deleted
@@ -134,75 +135,83 @@ class TestSRv6As(VppTestCase):
i.set_table_ip6(0)
def test_SRv6_End_AS_IPv6_noSRH(self):
- """ Test SRv6 End.AS behavior with IPv6 traffic and no SRH rewrite.
- """
+ """Test SRv6 End.AS behavior with IPv6 traffic and no SRH rewrite."""
self.run_SRv6_End_AS_IPv6(
- sid_list=['a1::', 'a2::a6', 'a3::'],
+ sid_list=["a1::", "a2::a6", "a3::"],
test_sid_index=1,
- rewrite_src_addr='a2::')
+ rewrite_src_addr="a2::",
+ )
def test_SRv6_End_AS_IPv6_SRH(self):
- """ Test SRv6 End.AS behavior with IPv6 traffic and SRH rewrite.
- """
+ """Test SRv6 End.AS behavior with IPv6 traffic and SRH rewrite."""
self.run_SRv6_End_AS_IPv6(
- sid_list=['a1::a6', 'a2::', 'a3::'],
+ sid_list=["a1::a6", "a2::", "a3::"],
test_sid_index=0,
- rewrite_src_addr='a1::')
+ rewrite_src_addr="a1::",
+ )
def test_SRv6_End_AS_IPv4_noSRH(self):
- """ Test SRv6 End.AS behavior with IPv4 traffic and no SRH rewrite.
- """
+ """Test SRv6 End.AS behavior with IPv4 traffic and no SRH rewrite."""
self.run_SRv6_End_AS_IPv4(
- sid_list=['a1::', 'a2::a6', 'a3::'],
+ sid_list=["a1::", "a2::a6", "a3::"],
test_sid_index=1,
- rewrite_src_addr='a2::')
+ rewrite_src_addr="a2::",
+ )
def test_SRv6_End_AS_IPv4_SRH(self):
- """ Test SRv6 End.AS behavior with IPv4 traffic and SRH rewrite.
- """
+ """Test SRv6 End.AS behavior with IPv4 traffic and SRH rewrite."""
self.run_SRv6_End_AS_IPv4(
- sid_list=['a1::a6', 'a2::', 'a3::'],
+ sid_list=["a1::a6", "a2::", "a3::"],
test_sid_index=0,
- rewrite_src_addr='a1::')
+ rewrite_src_addr="a1::",
+ )
def test_SRv6_End_AS_L2_noSRH(self):
- """ Test SRv6 End.AS behavior with L2 traffic and no SRH rewrite.
- """
+ """Test SRv6 End.AS behavior with L2 traffic and no SRH rewrite."""
self.run_SRv6_End_AS_L2(
- sid_list=['a1::', 'a2::a6', 'a3::'],
+ sid_list=["a1::", "a2::a6", "a3::"],
test_sid_index=1,
- rewrite_src_addr='a2::')
+ rewrite_src_addr="a2::",
+ )
def test_SRv6_End_AS_L2_SRH(self):
- """ Test SRv6 End.AS behavior with L2 traffic and SRH rewrite.
- """
+ """Test SRv6 End.AS behavior with L2 traffic and SRH rewrite."""
self.run_SRv6_End_AS_L2(
- sid_list=['a1::a6', 'a2::', 'a3::'],
+ sid_list=["a1::a6", "a2::", "a3::"],
test_sid_index=0,
- rewrite_src_addr='a1::')
+ rewrite_src_addr="a1::",
+ )
def run_SRv6_End_AS_L2(self, sid_list, test_sid_index, rewrite_src_addr):
- """ Run SRv6 End.AS test with L2 traffic.
- """
+ """Run SRv6 End.AS test with L2 traffic."""
self.rewrite_src_addr = rewrite_src_addr
- self.rewrite_sid_list = sid_list[test_sid_index + 1::]
+ self.rewrite_sid_list = sid_list[test_sid_index + 1 : :]
# send traffic to one destination interface
# source and destination interfaces are IPv6 only
self.setup_interfaces(ipv6=[True, False])
# configure route to next segment
- route = VppIpRoute(self, sid_list[test_sid_index + 1], 128,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index)])
+ route = VppIpRoute(
+ self,
+ sid_list[test_sid_index + 1],
+ 128,
+ [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)],
+ )
route.add_vpp_config()
# configure SRv6 localSID behavior
- cli_str = "sr localsid address " + sid_list[test_sid_index] \
- + " behavior end.as" \
- + " oif " + self.pg1.name \
- + " iif " + self.pg1.name \
- + " src " + self.rewrite_src_addr
+ cli_str = (
+ "sr localsid address "
+ + sid_list[test_sid_index]
+ + " behavior end.as"
+ + " oif "
+ + self.pg1.name
+ + " iif "
+ + self.pg1.name
+ + " src "
+ + self.rewrite_src_addr
+ )
for s in self.rewrite_sid_list:
cli_str += " next " + s
self.vapi.cli(cli_str)
@@ -215,17 +224,18 @@ class TestSRv6As(VppTestCase):
# prepare L2 in SRv6 headers
packet_header1 = self.create_packet_header_IPv6_SRH_L2(
- sidlist=sid_list[::-1],
- segleft=len(sid_list) - test_sid_index - 1,
- vlan=0)
+ sidlist=sid_list[::-1], segleft=len(sid_list) - test_sid_index - 1, vlan=0
+ )
# generate packets (pg0->pg1)
- pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1,
- self.pg_packet_sizes, count)
+ pkts1 = self.create_stream(
+ self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts1, self.pg1,
- self.compare_rx_tx_packet_End_AS_L2_out)
+ self.send_and_verify_pkts(
+ self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AS_L2_out
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -234,12 +244,14 @@ class TestSRv6As(VppTestCase):
packet_header2 = self.create_packet_header_L2()
# generate returning packets (pg1->pg0)
- pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2,
- self.pg_packet_sizes, count)
+ pkts2 = self.create_stream(
+ self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg1, pkts2, self.pg0,
- self.compare_rx_tx_packet_End_AS_L2_in)
+ self.send_and_verify_pkts(
+ self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AS_L2_in
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -251,28 +263,37 @@ class TestSRv6As(VppTestCase):
self.teardown_interfaces()
def run_SRv6_End_AS_IPv6(self, sid_list, test_sid_index, rewrite_src_addr):
- """ Run SRv6 End.AS test with IPv6 traffic.
- """
+ """Run SRv6 End.AS test with IPv6 traffic."""
self.rewrite_src_addr = rewrite_src_addr
- self.rewrite_sid_list = sid_list[test_sid_index + 1::]
+ self.rewrite_sid_list = sid_list[test_sid_index + 1 : :]
# send traffic to one destination interface
# source and destination interfaces are IPv6 only
self.setup_interfaces(ipv6=[True, True])
# configure route to next segment
- route = VppIpRoute(self, sid_list[test_sid_index + 1], 128,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index)])
+ route = VppIpRoute(
+ self,
+ sid_list[test_sid_index + 1],
+ 128,
+ [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)],
+ )
route.add_vpp_config()
# configure SRv6 localSID behavior
- cli_str = "sr localsid address " + sid_list[test_sid_index] \
- + " behavior end.as" \
- + " nh " + self.pg1.remote_ip6 \
- + " oif " + self.pg1.name \
- + " iif " + self.pg1.name \
- + " src " + self.rewrite_src_addr
+ cli_str = (
+ "sr localsid address "
+ + sid_list[test_sid_index]
+ + " behavior end.as"
+ + " nh "
+ + self.pg1.remote_ip6
+ + " oif "
+ + self.pg1.name
+ + " iif "
+ + self.pg1.name
+ + " src "
+ + self.rewrite_src_addr
+ )
for s in self.rewrite_sid_list:
cli_str += " next " + s
self.vapi.cli(cli_str)
@@ -285,16 +306,18 @@ class TestSRv6As(VppTestCase):
# prepare IPv6 in SRv6 headers
packet_header1 = self.create_packet_header_IPv6_SRH_IPv6(
- sidlist=sid_list[::-1],
- segleft=len(sid_list) - test_sid_index - 1)
+ sidlist=sid_list[::-1], segleft=len(sid_list) - test_sid_index - 1
+ )
# generate packets (pg0->pg1)
- pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1,
- self.pg_packet_sizes, count)
+ pkts1 = self.create_stream(
+ self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts1, self.pg1,
- self.compare_rx_tx_packet_End_AS_IPv6_out)
+ self.send_and_verify_pkts(
+ self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AS_IPv6_out
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -303,12 +326,14 @@ class TestSRv6As(VppTestCase):
packet_header2 = self.create_packet_header_IPv6()
# generate returning packets (pg1->pg0)
- pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2,
- self.pg_packet_sizes, count)
+ pkts2 = self.create_stream(
+ self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg1, pkts2, self.pg0,
- self.compare_rx_tx_packet_End_AS_IPv6_in)
+ self.send_and_verify_pkts(
+ self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AS_IPv6_in
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -320,28 +345,37 @@ class TestSRv6As(VppTestCase):
self.teardown_interfaces()
def run_SRv6_End_AS_IPv4(self, sid_list, test_sid_index, rewrite_src_addr):
- """ Run SRv6 End.AS test with IPv4 traffic.
- """
+ """Run SRv6 End.AS test with IPv4 traffic."""
self.rewrite_src_addr = rewrite_src_addr
- self.rewrite_sid_list = sid_list[test_sid_index + 1::]
+ self.rewrite_sid_list = sid_list[test_sid_index + 1 : :]
# send traffic to one destination interface
# source and destination interfaces are IPv6 only
self.setup_interfaces(ipv6=[True, False], ipv4=[True, True])
# configure route to next segment
- route = VppIpRoute(self, sid_list[test_sid_index + 1], 128,
- [VppRoutePath(self.pg0.remote_ip6,
- self.pg0.sw_if_index)])
+ route = VppIpRoute(
+ self,
+ sid_list[test_sid_index + 1],
+ 128,
+ [VppRoutePath(self.pg0.remote_ip6, self.pg0.sw_if_index)],
+ )
route.add_vpp_config()
# configure SRv6 localSID behavior
- cli_str = "sr localsid address " + sid_list[test_sid_index] \
- + " behavior end.as" \
- + " nh " + self.pg1.remote_ip4 \
- + " oif " + self.pg1.name \
- + " iif " + self.pg1.name \
- + " src " + self.rewrite_src_addr
+ cli_str = (
+ "sr localsid address "
+ + sid_list[test_sid_index]
+ + " behavior end.as"
+ + " nh "
+ + self.pg1.remote_ip4
+ + " oif "
+ + self.pg1.name
+ + " iif "
+ + self.pg1.name
+ + " src "
+ + self.rewrite_src_addr
+ )
for s in self.rewrite_sid_list:
cli_str += " next " + s
self.vapi.cli(cli_str)
@@ -354,16 +388,18 @@ class TestSRv6As(VppTestCase):
# prepare IPv4 in SRv6 headers
packet_header1 = self.create_packet_header_IPv6_SRH_IPv4(
- sidlist=sid_list[::-1],
- segleft=len(sid_list) - test_sid_index - 1)
+ sidlist=sid_list[::-1], segleft=len(sid_list) - test_sid_index - 1
+ )
# generate packets (pg0->pg1)
- pkts1 = self.create_stream(self.pg0, self.pg1, packet_header1,
- self.pg_packet_sizes, count)
+ pkts1 = self.create_stream(
+ self.pg0, self.pg1, packet_header1, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg0, pkts1, self.pg1,
- self.compare_rx_tx_packet_End_AS_IPv4_out)
+ self.send_and_verify_pkts(
+ self.pg0, pkts1, self.pg1, self.compare_rx_tx_packet_End_AS_IPv4_out
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -372,12 +408,14 @@ class TestSRv6As(VppTestCase):
packet_header2 = self.create_packet_header_IPv4()
# generate returning packets (pg1->pg0)
- pkts2 = self.create_stream(self.pg1, self.pg0, packet_header2,
- self.pg_packet_sizes, count)
+ pkts2 = self.create_stream(
+ self.pg1, self.pg0, packet_header2, self.pg_packet_sizes, count
+ )
# send packets and verify received packets
- self.send_and_verify_pkts(self.pg1, pkts2, self.pg0,
- self.compare_rx_tx_packet_End_AS_IPv4_in)
+ self.send_and_verify_pkts(
+ self.pg1, pkts2, self.pg0, self.compare_rx_tx_packet_End_AS_IPv4_in
+ )
# log the localsid counters
self.logger.info(self.vapi.cli("show sr localsid"))
@@ -389,7 +427,7 @@ class TestSRv6As(VppTestCase):
self.teardown_interfaces()
def compare_rx_tx_packet_End_AS_IPv6_in(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AS
+ """Compare input and output packet after passing End.AS
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -417,7 +455,7 @@ class TestSRv6As(VppTestCase):
# rx'ed seglist should be equal to expected seglist
self.assertEqual(rx_srh.addresses, tx_seglist)
# segleft should be equal to size expected seglist-1
- self.assertEqual(rx_srh.segleft, len(tx_seglist)-1)
+ self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1)
# segleft should be equal to lastentry
self.assertEqual(rx_srh.segleft, rx_srh.lastentry)
# get payload
@@ -438,7 +476,7 @@ class TestSRv6As(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_AS_IPv4_in(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AS
+ """Compare input and output packet after passing End.AS
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -467,7 +505,7 @@ class TestSRv6As(VppTestCase):
# rx'ed seglist should be equal to seglist
self.assertEqual(rx_srh.addresses, tx_seglist)
# segleft should be equal to size seglist-1
- self.assertEqual(rx_srh.segleft, len(tx_seglist)-1)
+ self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1)
# segleft should be equal to lastentry
self.assertEqual(rx_srh.segleft, rx_srh.lastentry)
payload = rx_srh.payload
@@ -492,7 +530,7 @@ class TestSRv6As(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_AS_L2_in(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AS
+ """Compare input and output packet after passing End.AS
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -520,7 +558,7 @@ class TestSRv6As(VppTestCase):
# rx'ed seglist should be equal to seglist
self.assertEqual(rx_srh.addresses, tx_seglist)
# segleft should be equal to size seglist-1
- self.assertEqual(rx_srh.segleft, len(tx_seglist)-1)
+ self.assertEqual(rx_srh.segleft, len(tx_seglist) - 1)
# segleft should be equal to lastentry
self.assertEqual(rx_srh.segleft, rx_srh.lastentry)
# nh should be "No Next Header" (143)
@@ -539,7 +577,7 @@ class TestSRv6As(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_AS_IPv6_out(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AS with IPv6
+ """Compare input and output packet after passing End.AS with IPv6
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -564,7 +602,7 @@ class TestSRv6As(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_AS_IPv4_out(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AS with IPv4
+ """Compare input and output packet after passing End.AS with IPv4
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -594,7 +632,7 @@ class TestSRv6As(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
def compare_rx_tx_packet_End_AS_L2_out(self, tx_pkt, rx_pkt):
- """ Compare input and output packet after passing End.AS with L2
+ """Compare input and output packet after passing End.AS with L2
:param tx_pkt: transmitted packet
:param rx_pkt: received packet
@@ -616,8 +654,7 @@ class TestSRv6As(VppTestCase):
self.logger.debug("packet verification: SUCCESS")
- def create_stream(self, src_if, dst_if, packet_header, packet_sizes,
- count):
+ def create_stream(self, src_if, dst_if, packet_header, packet_sizes, count):
"""Create SRv6 input packet stream for defined interface.
:param VppInterface src_if: Interface to create packet stream for
@@ -632,19 +669,19 @@ class TestSRv6As(VppTestCase):
"""
self.logger.info("Creating packets")
pkts = []
- for i in range(0, count-1):
+ for i in range(0, count - 1):
payload_info = self.create_packet_info(src_if, dst_if)
- self.logger.debug(
- "Creating packet with index %d" % (payload_info.index))
+ self.logger.debug("Creating packet with index %d" % (payload_info.index))
payload = self.info_to_payload(payload_info)
# add L2 header if not yet provided in packet_header
- if packet_header.getlayer(0).name == 'Ethernet':
- p = (packet_header /
- Raw(payload))
+ if packet_header.getlayer(0).name == "Ethernet":
+ p = packet_header / Raw(payload)
else:
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- packet_header /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / packet_header
+ / Raw(payload)
+ )
size = packet_sizes[i % len(packet_sizes)]
self.logger.debug("Packet size %d" % (size))
self.extend_packet(p, size)
@@ -697,8 +734,7 @@ class TestSRv6As(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IPv6(src='1234::1', dst='4321::1') /
- UDP(sport=1234, dport=1234))
+ p = IPv6(src="1234::1", dst="4321::1") / UDP(sport=1234, dport=1234)
return p
def create_packet_header_IPv6_SRH_IPv6(self, sidlist, segleft):
@@ -715,11 +751,12 @@ class TestSRv6As(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IPv6(src='5678::1', dst=sidlist[segleft]) /
- IPv6ExtHdrSegmentRouting(addresses=sidlist,
- segleft=segleft, nh=41) /
- IPv6(src='1234::1', dst='4321::1') /
- UDP(sport=1234, dport=1234))
+ p = (
+ IPv6(src="5678::1", dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=41)
+ / IPv6(src="1234::1", dst="4321::1")
+ / UDP(sport=1234, dport=1234)
+ )
return p
def create_packet_header_IPv4(self):
@@ -732,8 +769,7 @@ class TestSRv6As(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IP(src='123.1.1.1', dst='124.1.1.1') /
- UDP(sport=1234, dport=1234))
+ p = IP(src="123.1.1.1", dst="124.1.1.1") / UDP(sport=1234, dport=1234)
return p
def create_packet_header_IPv6_SRH_IPv4(self, sidlist, segleft):
@@ -751,11 +787,12 @@ class TestSRv6As(VppTestCase):
UDP source port and destination port are 1234
"""
- p = (IPv6(src='1234::1', dst=sidlist[segleft]) /
- IPv6ExtHdrSegmentRouting(addresses=sidlist,
- segleft=segleft, nh=4) /
- IP(src='123.1.1.1', dst='124.1.1.1') /
- UDP(sport=1234, dport=1234))
+ p = (
+ IPv6(src="1234::1", dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=4)
+ / IP(src="123.1.1.1", dst="124.1.1.1")
+ / UDP(sport=1234, dport=1234)
+ )
return p
def create_packet_header_L2(self, vlan=0):
@@ -766,7 +803,7 @@ class TestSRv6As(VppTestCase):
# Note: the dst addr ('00:55:44:33:22:11') is used in
# the compare function compare_rx_tx_packet_T_Encaps_L2
# to detect presence of L2 in SRH payload
- p = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11')
+ p = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11")
etype = 0x8137 # IPX
if vlan:
# add 802.1q layer
@@ -786,7 +823,7 @@ class TestSRv6As(VppTestCase):
Outer IPv6 destination address is set to sidlist[segleft]
IPv6 source address is 1234::1
"""
- eth = Ether(src='00:11:22:33:44:55', dst='00:55:44:33:22:11')
+ eth = Ether(src="00:11:22:33:44:55", dst="00:55:44:33:22:11")
etype = 0x8137 # IPX
if vlan:
# add 802.1q layer
@@ -794,15 +831,15 @@ class TestSRv6As(VppTestCase):
else:
eth.type = etype
- p = (IPv6(src='1234::1', dst=sidlist[segleft]) /
- IPv6ExtHdrSegmentRouting(addresses=sidlist,
- segleft=segleft, nh=143) /
- eth)
+ p = (
+ IPv6(src="1234::1", dst=sidlist[segleft])
+ / IPv6ExtHdrSegmentRouting(addresses=sidlist, segleft=segleft, nh=143)
+ / eth
+ )
return p
def get_payload_info(self, packet):
- """ Extract the payload_info from the packet
- """
+ """Extract the payload_info from the packet"""
# in most cases, payload_info is in packet[Raw]
# but packet[Raw] gives the complete payload
# (incl L2 header) for the T.Encaps L2 case
@@ -814,7 +851,8 @@ class TestSRv6As(VppTestCase):
# take packet[Raw], convert it to an Ether layer
# and then extract Raw from it
payload_info = self.payload_to_info(
- Ether(scapy.compat.raw(packet[Raw]))[Raw])
+ Ether(scapy.compat.raw(packet[Raw]))[Raw]
+ )
return payload_info
@@ -827,8 +865,10 @@ class TestSRv6As(VppTestCase):
:param capture: captured packets
:param compare_func: function to compare in and out packet
"""
- self.logger.info("Verifying capture on interface %s using function %s"
- % (dst_if.name, compare_func.__name__))
+ self.logger.info(
+ "Verifying capture on interface %s using function %s"
+ % (dst_if.name, compare_func.__name__)
+ )
last_info = dict()
for i in self.pg_interfaces:
@@ -841,19 +881,19 @@ class TestSRv6As(VppTestCase):
payload_info = self.get_payload_info(packet)
packet_index = payload_info.index
- self.logger.debug("Verifying packet with index %d"
- % (packet_index))
+ self.logger.debug("Verifying packet with index %d" % (packet_index))
# packet should have arrived on the expected interface
self.assertEqual(payload_info.dst, dst_sw_if_index)
self.logger.debug(
- "Got packet on interface %s: src=%u (idx=%u)" %
- (dst_if.name, payload_info.src, packet_index))
+ "Got packet on interface %s: src=%u (idx=%u)"
+ % (dst_if.name, payload_info.src, packet_index)
+ )
# search for payload_info with same src and dst if_index
# this will give us the transmitted packet
next_info = self.get_next_packet_info_for_interface2(
- payload_info.src, dst_sw_if_index,
- last_info[payload_info.src])
+ payload_info.src, dst_sw_if_index, last_info[payload_info.src]
+ )
last_info[payload_info.src] = next_info
# next_info should not be None
self.assertTrue(next_info is not None)
@@ -862,8 +902,9 @@ class TestSRv6As(VppTestCase):
# data field of next_info contains the tx packet
txed_packet = next_info.data
- self.logger.debug(ppp("Transmitted packet:",
- txed_packet)) # ppp=Pretty Print Packet
+ self.logger.debug(
+ ppp("Transmitted packet:", txed_packet)
+ ) # ppp=Pretty Print Packet
self.logger.debug(ppp("Received packet:", packet))
@@ -877,11 +918,14 @@ class TestSRv6As(VppTestCase):
# have all expected packets arrived?
for i in self.pg_interfaces:
remaining_packet = self.get_next_packet_info_for_interface2(
- i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index])
- self.assertTrue(remaining_packet is None,
- "Interface %s: Packet expected from interface %s "
- "didn't arrive" % (dst_if.name, i.name))
+ i.sw_if_index, dst_sw_if_index, last_info[i.sw_if_index]
+ )
+ self.assertTrue(
+ remaining_packet is None,
+ "Interface %s: Packet expected from interface %s "
+ "didn't arrive" % (dst_if.name, i.name),
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_srv6_mobile.py b/test/test_srv6_mobile.py
index e617acef9ab..33190b84ba0 100644
--- a/test/test_srv6_mobile.py
+++ b/test/test_srv6_mobile.py
@@ -8,7 +8,7 @@ from scapy.all import *
class TestSRv6EndMGTP4E(VppTestCase):
- """ SRv6 End.M.GTP4.E (SRv6 -> GTP-U) """
+ """SRv6 End.M.GTP4.E (SRv6 -> GTP-U)"""
@classmethod
def setUpClass(cls):
@@ -37,14 +37,12 @@ class TestSRv6EndMGTP4E(VppTestCase):
ip4_dst = IPv4Address(str(self.ip4_dst))
# 32bit prefix + 32bit IPv4 DA + 8bit + 32bit TEID + 24bit
- dst = b'\xaa' * 4 + ip4_dst.packed + \
- b'\x11' + b'\xbb' * 4 + b'\x11' * 3
+ dst = b"\xaa" * 4 + ip4_dst.packed + b"\x11" + b"\xbb" * 4 + b"\x11" * 3
ip6_dst = IPv6Address(dst)
ip4_src = IPv4Address(str(self.ip4_src))
# 64bit prefix + 32bit IPv4 SA + 16 bit port + 16bit
- src = b'\xcc' * 8 + ip4_src.packed + \
- b'\xdd' * 2 + b'\x11' * 2
+ src = b"\xcc" * 8 + ip4_src.packed + b"\xdd" * 2 + b"\x11" * 2
ip6_src = IPv6Address(src)
self.logger.info("ip4 dst: {}".format(ip4_dst))
@@ -54,24 +52,26 @@ class TestSRv6EndMGTP4E(VppTestCase):
pkts = list()
for d, s in inner:
- pkt = (Ether() /
- IPv6(dst=str(ip6_dst), src=str(ip6_src)) /
- IPv6ExtHdrSegmentRouting() /
- IPv6(dst=d, src=s) /
- UDP(sport=1000, dport=23))
+ pkt = (
+ Ether()
+ / IPv6(dst=str(ip6_dst), src=str(ip6_src))
+ / IPv6ExtHdrSegmentRouting()
+ / IPv6(dst=d, src=s)
+ / UDP(sport=1000, dport=23)
+ )
self.logger.info(pkt.show2(dump=True))
pkts.append(pkt)
return pkts
def test_srv6_mobile(self):
- """ test_srv6_mobile """
+ """test_srv6_mobile"""
pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")])
self.vapi.cli(
- "sr localsid address {} behavior end.m.gtp4.e "
- .format(pkts[0]['IPv6'].dst) +
- "v4src_position 64 fib-table 0")
+ "sr localsid address {} behavior end.m.gtp4.e ".format(pkts[0]["IPv6"].dst)
+ + "v4src_position 64 fib-table 0"
+ )
self.logger.info(self.vapi.cli("show sr localsid"))
self.vapi.cli("clear errors")
@@ -89,11 +89,11 @@ class TestSRv6EndMGTP4E(VppTestCase):
self.logger.info(pkt.show2(dump=True))
self.assertEqual(pkt[IP].dst, self.ip4_dst)
self.assertEqual(pkt[IP].src, self.ip4_src)
- self.assertEqual(pkt[GTP_U_Header].teid, 0xbbbbbbbb)
+ self.assertEqual(pkt[GTP_U_Header].teid, 0xBBBBBBBB)
class TestSRv6TMGTP4D(VppTestCase):
- """ SRv6 T.M.GTP4.D (GTP-U -> SRv6) """
+ """SRv6 T.M.GTP4.D (GTP-U -> SRv6)"""
@classmethod
def setUpClass(cls):
@@ -133,26 +133,29 @@ class TestSRv6TMGTP4D(VppTestCase):
pkts = list()
for d, s in inner:
- pkt = (Ether() /
- IP(dst=str(ip4_dst), src=str(ip4_src)) /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- IPv6(dst=d, src=s) /
- UDP(sport=1000, dport=23))
+ pkt = (
+ Ether()
+ / IP(dst=str(ip4_dst), src=str(ip4_src))
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / IPv6(dst=d, src=s)
+ / UDP(sport=1000, dport=23)
+ )
self.logger.info(pkt.show2(dump=True))
pkts.append(pkt)
return pkts
def test_srv6_mobile(self):
- """ test_srv6_mobile """
+ """test_srv6_mobile"""
pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")])
self.vapi.cli("set sr encaps source addr A1::1")
self.vapi.cli("sr policy add bsid D4:: next D2:: next D3::")
self.vapi.cli(
- "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 " +
- "v6src_prefix C1::/64 nhtype ipv6 fib-table 0 drop-in")
+ "sr policy add bsid D5:: behavior t.m.gtp4.d D4::/32 "
+ + "v6src_prefix C1::/64 nhtype ipv6 fib-table 0 drop-in"
+ )
self.vapi.cli("sr steer l3 {}/32 via bsid D5::".format(self.ip4_dst))
self.vapi.cli("ip route add D2::/32 via {}".format(self.ip6_dst))
@@ -172,15 +175,18 @@ class TestSRv6TMGTP4D(VppTestCase):
for pkt in capture:
self.logger.info(pkt.show2(dump=True))
- self.logger.info("GTP4.D Address={}".format(
- str(pkt[IPv6ExtHdrSegmentRouting].addresses[0])))
+ self.logger.info(
+ "GTP4.D Address={}".format(
+ str(pkt[IPv6ExtHdrSegmentRouting].addresses[0])
+ )
+ )
self.assertEqual(
- str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]),
- "d4:0:101:101::c800:0")
+ str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]), "d4:0:101:101::c800:0"
+ )
class TestSRv6EndMGTP6E(VppTestCase):
- """ SRv6 End.M.GTP6.E """
+ """SRv6 End.M.GTP6.E"""
@classmethod
def setUpClass(cls):
@@ -205,42 +211,42 @@ class TestSRv6EndMGTP6E(VppTestCase):
def create_packets(self, inner):
# 64bit prefix + 8bit QFI + 32bit TEID + 24bit
- dst = b'\xaa' * 8 + b'\x00' + \
- b'\xbb' * 4 + b'\x00' * 3
+ dst = b"\xaa" * 8 + b"\x00" + b"\xbb" * 4 + b"\x00" * 3
ip6_dst = IPv6Address(dst)
self.ip6_dst = ip6_dst
- src = b'\xcc' * 8 + \
- b'\xdd' * 4 + b'\x11' * 4
+ src = b"\xcc" * 8 + b"\xdd" * 4 + b"\x11" * 4
ip6_src = IPv6Address(src)
self.ip6_src = ip6_src
pkts = list()
for d, s in inner:
- pkt = (Ether() /
- IPv6(dst=str(ip6_dst),
- src=str(ip6_src)) /
- IPv6ExtHdrSegmentRouting(segleft=1,
- lastentry=0,
- tag=0,
- addresses=["a1::1"]) /
- IPv6(dst=d, src=s) / UDP(sport=1000, dport=23))
+ pkt = (
+ Ether()
+ / IPv6(dst=str(ip6_dst), src=str(ip6_src))
+ / IPv6ExtHdrSegmentRouting(
+ segleft=1, lastentry=0, tag=0, addresses=["a1::1"]
+ )
+ / IPv6(dst=d, src=s)
+ / UDP(sport=1000, dport=23)
+ )
self.logger.info(pkt.show2(dump=True))
pkts.append(pkt)
return pkts
def test_srv6_mobile(self):
- """ test_srv6_mobile """
+ """test_srv6_mobile"""
pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")])
self.vapi.cli(
- "sr localsid prefix {}/64 behavior end.m.gtp6.e fib-table 0"
- .format(pkts[0]['IPv6'].dst))
- self.vapi.cli(
- "ip route add a1::/64 via {}".format(self.ip6_nhop))
+ "sr localsid prefix {}/64 behavior end.m.gtp6.e fib-table 0".format(
+ pkts[0]["IPv6"].dst
+ )
+ )
+ self.vapi.cli("ip route add a1::/64 via {}".format(self.ip6_nhop))
self.logger.info(self.vapi.cli("show sr localsid"))
self.vapi.cli("clear errors")
@@ -258,11 +264,11 @@ class TestSRv6EndMGTP6E(VppTestCase):
self.logger.info(pkt.show2(dump=True))
self.assertEqual(pkt[IPv6].dst, "a1::1")
self.assertEqual(pkt[IPv6].src, str(self.ip6_src))
- self.assertEqual(pkt[GTP_U_Header].teid, 0xbbbbbbbb)
+ self.assertEqual(pkt[GTP_U_Header].teid, 0xBBBBBBBB)
class TestSRv6EndMGTP6D(VppTestCase):
- """ SRv6 End.M.GTP6.D """
+ """SRv6 End.M.GTP6.D"""
@classmethod
def setUpClass(cls):
@@ -299,26 +305,29 @@ class TestSRv6EndMGTP6D(VppTestCase):
pkts = list()
for d, s in inner:
- pkt = (Ether() /
- IPv6(dst=str(ip6_dst), src=str(ip6_src)) /
- UDP(sport=2152, dport=2152) /
- GTP_U_Header(gtp_type="g_pdu", teid=200) /
- IPv6(dst=d, src=s) /
- UDP(sport=1000, dport=23))
+ pkt = (
+ Ether()
+ / IPv6(dst=str(ip6_dst), src=str(ip6_src))
+ / UDP(sport=2152, dport=2152)
+ / GTP_U_Header(gtp_type="g_pdu", teid=200)
+ / IPv6(dst=d, src=s)
+ / UDP(sport=1000, dport=23)
+ )
self.logger.info(pkt.show2(dump=True))
pkts.append(pkt)
return pkts
def test_srv6_mobile(self):
- """ test_srv6_mobile """
+ """test_srv6_mobile"""
pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")])
self.vapi.cli("set sr encaps source addr A1::1")
self.vapi.cli("sr policy add bsid D4:: next D2:: next D3::")
self.vapi.cli(
- "sr localsid prefix 2001::/64 behavior end.m.gtp6.d " +
- "D4::/64 fib-table 0 drop-in")
+ "sr localsid prefix 2001::/64 behavior end.m.gtp6.d "
+ + "D4::/64 fib-table 0 drop-in"
+ )
self.vapi.cli("ip route add D2::/64 via {}".format(self.ip6_nhop))
self.logger.info(self.vapi.cli("show sr policies"))
@@ -337,11 +346,13 @@ class TestSRv6EndMGTP6D(VppTestCase):
for pkt in capture:
self.logger.info(pkt.show2(dump=True))
- self.logger.info("GTP6.D SID0={}".format(
- str(pkt[IPv6ExtHdrSegmentRouting].addresses[0])))
- self.logger.info("GTP6.D SID1={}".format(
- str(pkt[IPv6ExtHdrSegmentRouting].addresses[1])))
- self.assertEqual(
- str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]), "2001::1")
+ self.logger.info(
+ "GTP6.D SID0={}".format(str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]))
+ )
+ self.logger.info(
+ "GTP6.D SID1={}".format(str(pkt[IPv6ExtHdrSegmentRouting].addresses[1]))
+ )
+ self.assertEqual(str(pkt[IPv6ExtHdrSegmentRouting].addresses[0]), "2001::1")
self.assertEqual(
- str(pkt[IPv6ExtHdrSegmentRouting].addresses[1]), "d4::c800:0")
+ str(pkt[IPv6ExtHdrSegmentRouting].addresses[1]), "d4::c800:0"
+ )
diff --git a/test/test_srv6_un.py b/test/test_srv6_un.py
index 73285bbac87..22a3c486584 100644
--- a/test/test_srv6_un.py
+++ b/test/test_srv6_un.py
@@ -8,7 +8,7 @@ from scapy.all import *
class TestSRv6uSIDSRH(VppTestCase):
- """ SRv6 End.uSID w/ SRH """
+ """SRv6 End.uSID w/ SRH"""
@classmethod
def setUpClass(cls):
@@ -45,30 +45,30 @@ class TestSRv6uSIDSRH(VppTestCase):
pkts = list()
for d, s in inner:
- pkt = (Ether() /
- IPv6(dst=str(ip6_dst), src=str(ip6_src)) /
- IPv6ExtHdrSegmentRouting(segleft=1,
- lastentry=0,
- tag=0,
- addresses=[
- "a1::1",
- "1111:2222:aaaa:bbbb::"]) /
- IPv6(dst=d, src=s) /
- UDP(sport=1000, dport=23))
+ pkt = (
+ Ether()
+ / IPv6(dst=str(ip6_dst), src=str(ip6_src))
+ / IPv6ExtHdrSegmentRouting(
+ segleft=1,
+ lastentry=0,
+ tag=0,
+ addresses=["a1::1", "1111:2222:aaaa:bbbb::"],
+ )
+ / IPv6(dst=d, src=s)
+ / UDP(sport=1000, dport=23)
+ )
self.logger.info(pkt.show2(dump=True))
pkts.append(pkt)
return pkts
def test_srv6_usid_srh(self):
- """ test_srv6_usid_srh """
+ """test_srv6_usid_srh"""
pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")])
self.vapi.cli("set sr encaps source addr A1::1")
- self.vapi.cli(
- "sr localsid prefix 1111:2222:aaaa::/48 behavior un 16")
- self.vapi.cli(
- "ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop))
+ self.vapi.cli("sr localsid prefix 1111:2222:aaaa::/48 behavior un 16")
+ self.vapi.cli("ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop))
self.logger.info(self.vapi.cli("show sr localsids"))
@@ -85,12 +85,11 @@ class TestSRv6uSIDSRH(VppTestCase):
for pkt in capture:
self.logger.info(pkt.show2(dump=True))
- self.assertEqual(
- pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0")
+ self.assertEqual(pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0")
class TestSRv6uSID(VppTestCase):
- """ SRv6 End.uSID w/o SRH """
+ """SRv6 End.uSID w/o SRH"""
@classmethod
def setUpClass(cls):
@@ -127,24 +126,24 @@ class TestSRv6uSID(VppTestCase):
pkts = list()
for d, s in inner:
- pkt = (Ether() /
- IPv6(dst=str(ip6_dst), src=str(ip6_src)) /
- IPv6(dst=d, src=s) /
- UDP(sport=1000, dport=23))
+ pkt = (
+ Ether()
+ / IPv6(dst=str(ip6_dst), src=str(ip6_src))
+ / IPv6(dst=d, src=s)
+ / UDP(sport=1000, dport=23)
+ )
self.logger.info(pkt.show2(dump=True))
pkts.append(pkt)
return pkts
def test_srv6_usid(self):
- """ test_srv6_usid """
+ """test_srv6_usid"""
pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")])
self.vapi.cli("set sr encaps source addr A1::1")
- self.vapi.cli(
- "sr localsid prefix 1111:2222:aaaa::/48 behavior un 16")
- self.vapi.cli(
- "ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop))
+ self.vapi.cli("sr localsid prefix 1111:2222:aaaa::/48 behavior un 16")
+ self.vapi.cli("ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop))
self.logger.info(self.vapi.cli("show sr localsids"))
@@ -161,12 +160,11 @@ class TestSRv6uSID(VppTestCase):
for pkt in capture:
self.logger.info(pkt.show2(dump=True))
- self.assertEqual(
- pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0")
+ self.assertEqual(pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0")
class TestSRv6uSIDFlexSRH(VppTestCase):
- """ SRv6 End.uSID.Flex w/ SRH """
+ """SRv6 End.uSID.Flex w/ SRH"""
@classmethod
def setUpClass(cls):
@@ -203,30 +201,30 @@ class TestSRv6uSIDFlexSRH(VppTestCase):
pkts = list()
for d, s in inner:
- pkt = (Ether() /
- IPv6(dst=str(ip6_dst), src=str(ip6_src)) /
- IPv6ExtHdrSegmentRouting(segleft=1,
- lastentry=0,
- tag=0,
- addresses=[
- "a1::1",
- "1111:2222:aaaa:bbbb::"]) /
- IPv6(dst=d, src=s) /
- UDP(sport=1000, dport=23))
+ pkt = (
+ Ether()
+ / IPv6(dst=str(ip6_dst), src=str(ip6_src))
+ / IPv6ExtHdrSegmentRouting(
+ segleft=1,
+ lastentry=0,
+ tag=0,
+ addresses=["a1::1", "1111:2222:aaaa:bbbb::"],
+ )
+ / IPv6(dst=d, src=s)
+ / UDP(sport=1000, dport=23)
+ )
self.logger.info(pkt.show2(dump=True))
pkts.append(pkt)
return pkts
def test_srv6_usid_flex_srh(self):
- """ test_srv6_usid_flex_srh """
+ """test_srv6_usid_flex_srh"""
pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")])
self.vapi.cli("set sr encaps source addr A1::1")
- self.vapi.cli(
- "sr localsid prefix 1111:2222:aaaa::/48 behavior un.flex 16")
- self.vapi.cli(
- "ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop))
+ self.vapi.cli("sr localsid prefix 1111:2222:aaaa::/48 behavior un.flex 16")
+ self.vapi.cli("ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop))
self.logger.info(self.vapi.cli("show sr localsids"))
@@ -243,12 +241,11 @@ class TestSRv6uSIDFlexSRH(VppTestCase):
for pkt in capture:
self.logger.info(pkt.show2(dump=True))
- self.assertEqual(
- pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0")
+ self.assertEqual(pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0")
class TestSRv6uSIDFlex(VppTestCase):
- """ SRv6 End.uSID.Flex w/o SRH """
+ """SRv6 End.uSID.Flex w/o SRH"""
@classmethod
def setUpClass(cls):
@@ -285,24 +282,24 @@ class TestSRv6uSIDFlex(VppTestCase):
pkts = list()
for d, s in inner:
- pkt = (Ether() /
- IPv6(dst=str(ip6_dst), src=str(ip6_src)) /
- IPv6(dst=d, src=s) /
- UDP(sport=1000, dport=23))
+ pkt = (
+ Ether()
+ / IPv6(dst=str(ip6_dst), src=str(ip6_src))
+ / IPv6(dst=d, src=s)
+ / UDP(sport=1000, dport=23)
+ )
self.logger.info(pkt.show2(dump=True))
pkts.append(pkt)
return pkts
def test_srv6_usid_flex(self):
- """ test_srv6_usid_flex """
+ """test_srv6_usid_flex"""
pkts = self.create_packets([("A::1", "B::1"), ("C::1", "D::1")])
self.vapi.cli("set sr encaps source addr A1::1")
- self.vapi.cli(
- "sr localsid prefix 1111:2222:aaaa::/48 behavior un.flex 16")
- self.vapi.cli(
- "ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop))
+ self.vapi.cli("sr localsid prefix 1111:2222:aaaa::/48 behavior un.flex 16")
+ self.vapi.cli("ip route add 1111:2222:bbbb::/48 via {}".format(self.ip6_nhop))
self.logger.info(self.vapi.cli("show sr localsids"))
@@ -319,5 +316,4 @@ class TestSRv6uSIDFlex(VppTestCase):
for pkt in capture:
self.logger.info(pkt.show2(dump=True))
- self.assertEqual(
- pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0")
+ self.assertEqual(pkt[IPv6].dst, "1111:2222:bbbb:cccc:dddd:eeee:ffff:0")
diff --git a/test/test_stats_client.py b/test/test_stats_client.py
index f3db2ef3b2e..7b62b292853 100644
--- a/test/test_stats_client.py
+++ b/test/test_stats_client.py
@@ -32,7 +32,8 @@ class StatsClientTestCase(VppTestCase):
"""Test set errors"""
self.assertEqual(self.statistics.set_errors(), {})
self.assertEqual(
- self.statistics.get_counter('/err/ethernet-input/no error'), [0])
+ self.statistics.get_counter("/err/ethernet-input/no error"), [0]
+ )
def test_client_fd_leak(self):
"""Test file descriptor count - VPP-1486"""
@@ -46,11 +47,13 @@ class StatsClientTestCase(VppTestCase):
stats.disconnect()
ending_fds = p.num_fds()
- self.assertEqual(initial_fds, ending_fds,
- "initial client side file descriptor count: %s "
- "is not equal to "
- "ending client side file descriptor count: %s" % (
- initial_fds, ending_fds))
+ self.assertEqual(
+ initial_fds,
+ ending_fds,
+ "initial client side file descriptor count: %s "
+ "is not equal to "
+ "ending client side file descriptor count: %s" % (initial_fds, ending_fds),
+ )
def test_symlink_values(self):
"""Test symlinks reported values"""
@@ -63,16 +66,16 @@ class StatsClientTestCase(VppTestCase):
p = list()
for i in range(5):
- packet = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4))
+ packet = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(
+ src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4
+ )
p.append(packet)
self.send_and_expect(self.pg0, p, self.pg1)
- pg1_tx = self.statistics.get_counter('/interfaces/pg1/tx')
- if_tx = self.statistics.get_counter('/if/tx')
+ pg1_tx = self.statistics.get_counter("/interfaces/pg1/tx")
+ if_tx = self.statistics.get_counter("/if/tx")
- self.assertEqual(pg1_tx[0]['bytes'],
- if_tx[0][self.pg1.sw_if_index]['bytes'])
+ self.assertEqual(pg1_tx[0]["bytes"], if_tx[0][self.pg1.sw_if_index]["bytes"])
for i in self.pg_interfaces:
i.unconfig()
i.admin_down()
@@ -93,31 +96,28 @@ class StatsClientTestCase(VppTestCase):
p = list()
bytes_to_send = 0
for i in range(5):
- packet = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4))
+ packet = Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) / IP(
+ src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4
+ )
bytes_to_send += len(packet)
p.append(packet)
- tx_before_sending = self.statistics.get_counter('/interfaces/pg1/tx')
- rx_before_sending = self.statistics.get_counter('/interfaces/pg0/rx')
+ tx_before_sending = self.statistics.get_counter("/interfaces/pg1/tx")
+ rx_before_sending = self.statistics.get_counter("/interfaces/pg0/rx")
self.send_and_expect(self.pg0, p, self.pg1)
- tx = self.statistics.get_counter('/interfaces/pg1/tx')
- rx = self.statistics.get_counter('/interfaces/pg0/rx')
+ tx = self.statistics.get_counter("/interfaces/pg1/tx")
+ rx = self.statistics.get_counter("/interfaces/pg0/rx")
# We wait for nodes symlinks to update (interfaces created/deleted).
# ... and packets to be sent
self.sleep(0.1)
- vectors = self.statistics.get_counter('/nodes/pg1-tx/vectors')
-
- self.assertEqual(tx[0]['bytes'] - tx_before_sending[0]['bytes'],
- bytes_to_send)
- self.assertEqual(tx[0]['packets'] - tx_before_sending[0]['packets'],
- 5)
- self.assertEqual(rx[0]['bytes'] - rx_before_sending[0]['bytes'],
- bytes_to_send)
- self.assertEqual(rx[0]['packets'] - rx_before_sending[0]['packets'],
- 5)
- self.assertEqual(vectors[0], rx[0]['packets'])
+ vectors = self.statistics.get_counter("/nodes/pg1-tx/vectors")
+
+ self.assertEqual(tx[0]["bytes"] - tx_before_sending[0]["bytes"], bytes_to_send)
+ self.assertEqual(tx[0]["packets"] - tx_before_sending[0]["packets"], 5)
+ self.assertEqual(rx[0]["bytes"] - rx_before_sending[0]["bytes"], bytes_to_send)
+ self.assertEqual(rx[0]["packets"] - rx_before_sending[0]["packets"], 5)
+ self.assertEqual(vectors[0], rx[0]["packets"])
for i in self.pg_interfaces:
i.unconfig()
@@ -125,7 +125,7 @@ class StatsClientTestCase(VppTestCase):
def test_index_consistency(self):
"""Test index consistency despite changes in the stats"""
- d = self.statistics.ls(['/if/names'])
+ d = self.statistics.ls(["/if/names"])
self.create_loopback_interfaces(10)
for i in range(10):
try:
@@ -142,22 +142,21 @@ class StatsClientTestCase(VppTestCase):
@unittest.skip("Manual only")
def test_mem_leak(self):
def loop():
- print('Running loop')
+ print("Running loop")
for i in range(50):
rv = self.vapi.papi.tap_create_v2(id=i, use_random_mac=1)
self.assertEqual(rv.retval, 0)
rv = self.vapi.papi.tap_delete_v2(sw_if_index=rv.sw_if_index)
self.assertEqual(rv.retval, 0)
- before = self.statistics.get_counter('/mem/statseg/used')
+ before = self.statistics.get_counter("/mem/statseg/used")
loop()
self.vapi.cli("memory-trace on stats-segment")
for j in range(100):
loop()
print(self.vapi.cli("show memory stats-segment verbose"))
- print('AFTER', before,
- self.statistics.get_counter('/mem/statseg/used'))
+ print("AFTER", before, self.statistics.get_counter("/mem/statseg/used"))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_string.py b/test/test_string.py
index c507c7559ca..866a6597107 100644
--- a/test/test_string.py
+++ b/test/test_string.py
@@ -7,7 +7,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
class TestString(VppTestCase):
- """ String Test Cases """
+ """String Test Cases"""
@classmethod
def setUpClass(cls):
@@ -24,15 +24,30 @@ class TestString(VppTestCase):
super(TestString, self).tearDown()
def test_string_unittest(self):
- """ String unit tests """
- names = ["memcpy_s",
- "clib_memcmp", "clib_memcpy", "clib_memset",
- "clib_strcmp", "clib_strncmp", "clib_strncpy",
- "clib_strnlen", "clib_strtok",
- "memcmp_s", "memcpy_s", "memset_s ",
- "strcat_s", "strcmp_s", "strcpy_s",
- "strncat_s", "strncmp_s", "strncpy_s",
- "strnlen_s", "strstr_s", "strtok_s"]
+ """String unit tests"""
+ names = [
+ "memcpy_s",
+ "clib_memcmp",
+ "clib_memcpy",
+ "clib_memset",
+ "clib_strcmp",
+ "clib_strncmp",
+ "clib_strncpy",
+ "clib_strnlen",
+ "clib_strtok",
+ "memcmp_s",
+ "memcpy_s",
+ "memset_s ",
+ "strcat_s",
+ "strcmp_s",
+ "strcpy_s",
+ "strncat_s",
+ "strncmp_s",
+ "strncpy_s",
+ "strnlen_s",
+ "strstr_s",
+ "strtok_s",
+ ]
for name in names:
error = self.vapi.cli("test string " + name)
@@ -41,5 +56,5 @@ class TestString(VppTestCase):
self.assertNotIn("failed", error)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_svs.py b/test/test_svs.py
index db4ad8078e0..91603966453 100644
--- a/test/test_svs.py
+++ b/test/test_svs.py
@@ -16,7 +16,7 @@ NUM_PKTS = 67
class TestSVS(VppTestCase):
- """ SVS Test Case """
+ """SVS Test Case"""
@classmethod
def setUpClass(cls):
@@ -61,35 +61,51 @@ class TestSVS(VppTestCase):
super(TestSVS, self).tearDown()
def test_svs4(self):
- """ Source VRF Select IP4 """
+ """Source VRF Select IP4"""
#
# packets destined out of the 3 non-default table interfaces
#
- pkts_0 = [(Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src="1.1.1.1", dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src="2.2.2.2", dst=self.pg2.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src="3.3.3.3", dst=self.pg3.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
- pkts_1 = [(Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src="1.1.1.1", dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src="2.2.2.2", dst=self.pg2.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src="3.3.3.3", dst=self.pg3.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
+ pkts_0 = [
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src="1.1.1.1", dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src="2.2.2.2", dst=self.pg2.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src="3.3.3.3", dst=self.pg3.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
+ pkts_1 = [
+ (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src="1.1.1.1", dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src="2.2.2.2", dst=self.pg2.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src="3.3.3.3", dst=self.pg3.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
#
# before adding the SVS config all these packets are dropped when
@@ -108,7 +124,8 @@ class TestSVS(VppTestCase):
self.vapi.svs_table_add_del(
is_add=1,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP4,
- table_id=table_id)
+ table_id=table_id,
+ )
#
# map X.0.0.0/8 to each SVS table for lookup in table X
@@ -118,7 +135,8 @@ class TestSVS(VppTestCase):
is_add=1,
prefix="%d.0.0.0/8" % i,
table_id=table_id,
- source_table_id=i)
+ source_table_id=i,
+ )
#
# Enable SVS on pg0/pg1 using table 1001/1002
@@ -127,12 +145,14 @@ class TestSVS(VppTestCase):
is_enable=1,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP4,
table_id=table_ids[0],
- sw_if_index=self.pg0.sw_if_index)
+ sw_if_index=self.pg0.sw_if_index,
+ )
self.vapi.svs_enable_disable(
is_enable=1,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP4,
table_id=table_ids[1],
- sw_if_index=self.pg1.sw_if_index)
+ sw_if_index=self.pg1.sw_if_index,
+ )
#
# now all the packets should be delivered out the respective interface
@@ -148,16 +168,20 @@ class TestSVS(VppTestCase):
# check that if the SVS lookup does not match a route the packet
# is forwarded using the interface's routing table
#
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg0)
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect(self.pg1, p * NUM_PKTS, self.pg1)
#
@@ -179,12 +203,14 @@ class TestSVS(VppTestCase):
is_enable=0,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP4,
table_id=table_ids[0],
- sw_if_index=self.pg0.sw_if_index)
+ sw_if_index=self.pg0.sw_if_index,
+ )
self.vapi.svs_enable_disable(
is_enable=0,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP4,
table_id=table_ids[1],
- sw_if_index=self.pg1.sw_if_index)
+ sw_if_index=self.pg1.sw_if_index,
+ )
for table_id in table_ids:
for i in range(1, 4):
@@ -192,43 +218,61 @@ class TestSVS(VppTestCase):
is_add=0,
prefix="%d.0.0.0/8" % i,
table_id=table_id,
- source_table_id=0)
+ source_table_id=0,
+ )
self.vapi.svs_table_add_del(
is_add=0,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP4,
- table_id=table_id)
+ table_id=table_id,
+ )
def test_svs6(self):
- """ Source VRF Select IP6 """
+ """Source VRF Select IP6"""
#
# packets destined out of the 3 non-default table interfaces
#
- pkts_0 = [(Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src="2001:1::1", dst=self.pg1.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src="2001:2::1", dst=self.pg2.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src="2001:3::1", dst=self.pg3.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
- pkts_1 = [(Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src="2001:1::1", dst=self.pg1.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src="2001:2::1", dst=self.pg2.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)),
- (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src="2001:3::1", dst=self.pg3.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))]
+ pkts_0 = [
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src="2001:1::1", dst=self.pg1.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src="2001:2::1", dst=self.pg2.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src="2001:3::1", dst=self.pg3.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
+ pkts_1 = [
+ (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src="2001:1::1", dst=self.pg1.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src="2001:2::1", dst=self.pg2.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src="2001:3::1", dst=self.pg3.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ),
+ ]
#
# before adding the SVS config all these packets are dropped when
@@ -247,7 +291,8 @@ class TestSVS(VppTestCase):
self.vapi.svs_table_add_del(
is_add=1,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP6,
- table_id=table_id)
+ table_id=table_id,
+ )
#
# map X.0.0.0/8 to each SVS table for lookup in table X
@@ -257,7 +302,8 @@ class TestSVS(VppTestCase):
is_add=1,
prefix="2001:%d::/32" % i,
table_id=table_id,
- source_table_id=i)
+ source_table_id=i,
+ )
#
# Enable SVS on pg0/pg1 using table 1001/1002
@@ -266,12 +312,14 @@ class TestSVS(VppTestCase):
is_enable=1,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP6,
table_id=table_ids[0],
- sw_if_index=self.pg0.sw_if_index)
+ sw_if_index=self.pg0.sw_if_index,
+ )
self.vapi.svs_enable_disable(
is_enable=1,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP6,
table_id=table_ids[1],
- sw_if_index=self.pg1.sw_if_index)
+ sw_if_index=self.pg1.sw_if_index,
+ )
#
# now all the packets should be delivered out the respective interface
@@ -287,16 +335,20 @@ class TestSVS(VppTestCase):
# check that if the SVS lookup does not match a route the packet
# is forwarded using the interface's routing table
#
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect(self.pg0, p * NUM_PKTS, self.pg0)
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
self.send_and_expect(self.pg1, p * NUM_PKTS, self.pg1)
#
@@ -318,12 +370,14 @@ class TestSVS(VppTestCase):
is_enable=0,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP6,
table_id=table_ids[0],
- sw_if_index=self.pg0.sw_if_index)
+ sw_if_index=self.pg0.sw_if_index,
+ )
self.vapi.svs_enable_disable(
is_enable=0,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP6,
table_id=table_ids[1],
- sw_if_index=self.pg1.sw_if_index)
+ sw_if_index=self.pg1.sw_if_index,
+ )
for table_id in table_ids:
for i in range(1, 4):
@@ -331,12 +385,15 @@ class TestSVS(VppTestCase):
is_add=0,
prefix="2001:%d::/32" % i,
table_id=table_id,
- source_table_id=0)
+ source_table_id=0,
+ )
self.vapi.svs_table_add_del(
is_add=0,
af=VppEnum.vl_api_address_family_t.ADDRESS_IP6,
- table_id=table_id)
+ table_id=table_id,
+ )
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_syslog.py b/test/test_syslog.py
index b084a1d1846..b84c89c57d0 100644
--- a/test/test_syslog.py
+++ b/test/test_syslog.py
@@ -11,7 +11,7 @@ from vpp_papi import VppEnum
class TestSyslog(VppTestCase):
- """ Syslog Protocol Test Cases """
+ """Syslog Protocol Test Cases"""
@property
def SYSLOG_SEVERITY(self):
@@ -22,7 +22,7 @@ class TestSyslog(VppTestCase):
super(TestSyslog, cls).setUpClass()
try:
- cls.pg0, = cls.create_pg_interfaces(range(1))
+ (cls.pg0,) = cls.create_pg_interfaces(range(1))
cls.pg0.admin_up()
cls.pg0.config_ip4()
cls.pg0.resolve_arp()
@@ -35,8 +35,7 @@ class TestSyslog(VppTestCase):
def tearDownClass(cls):
super(TestSyslog, cls).tearDownClass()
- def syslog_generate(self, facility, severity, appname, msgid, sd=None,
- msg=None):
+ def syslog_generate(self, facility, severity, appname, msgid, sd=None, msg=None):
"""
Generate syslog message
@@ -47,20 +46,50 @@ class TestSyslog(VppTestCase):
:param sd: structured data (optional)
:param msg: free-form message (optional)
"""
- facility_str = ['kernel', 'user-level', 'mail-system',
- 'system-daemons', 'security-authorization', 'syslogd',
- 'line-printer', 'network-news', 'uucp', 'clock-daemon',
- '', 'ftp-daemon', 'ntp-subsystem', 'log-audit',
- 'log-alert', '', 'local0', 'local1', 'local2',
- 'local3', 'local4', 'local5', 'local6', 'local7']
-
- severity_str = ['emergency', 'alert', 'critical', 'error', 'warning',
- 'notice', 'informational', 'debug']
-
- cli_str = "test syslog %s %s %s %s" % (facility_str[facility],
- severity_str[severity],
- appname,
- msgid)
+ facility_str = [
+ "kernel",
+ "user-level",
+ "mail-system",
+ "system-daemons",
+ "security-authorization",
+ "syslogd",
+ "line-printer",
+ "network-news",
+ "uucp",
+ "clock-daemon",
+ "",
+ "ftp-daemon",
+ "ntp-subsystem",
+ "log-audit",
+ "log-alert",
+ "",
+ "local0",
+ "local1",
+ "local2",
+ "local3",
+ "local4",
+ "local5",
+ "local6",
+ "local7",
+ ]
+
+ severity_str = [
+ "emergency",
+ "alert",
+ "critical",
+ "error",
+ "warning",
+ "notice",
+ "informational",
+ "debug",
+ ]
+
+ cli_str = "test syslog %s %s %s %s" % (
+ facility_str[facility],
+ severity_str[severity],
+ appname,
+ msgid,
+ )
if sd is not None:
for sd_id, sd_params in sd.items():
cli_str += " sd-id %s" % (sd_id)
@@ -70,8 +99,9 @@ class TestSyslog(VppTestCase):
cli_str += " %s" % (msg)
self.vapi.cli(cli_str)
- def syslog_verify(self, data, facility, severity, appname, msgid, sd=None,
- msg=None):
+ def syslog_verify(
+ self, data, facility, severity, appname, msgid, sd=None, msg=None
+ ):
"""
Verify syslog message
@@ -83,7 +113,7 @@ class TestSyslog(VppTestCase):
:param sd: structured data (optional)
:param msg: free-form message (optional)
"""
- message = data.decode('utf-8')
+ message = data.decode("utf-8")
if sd is None:
sd = {}
try:
@@ -102,35 +132,32 @@ class TestSyslog(VppTestCase):
self.assertEqual(message.hostname, self.pg0.local_ip4)
def test_syslog(self):
- """ Syslog Protocol test """
- self.vapi.syslog_set_sender(src_address=self.pg0.local_ip4,
- collector_address=self.pg0.remote_ip4)
+ """Syslog Protocol test"""
+ self.vapi.syslog_set_sender(
+ src_address=self.pg0.local_ip4, collector_address=self.pg0.remote_ip4
+ )
config = self.vapi.syslog_get_sender()
- self.assertEqual(str(config.collector_address),
- self.pg0.remote_ip4)
+ self.assertEqual(str(config.collector_address), self.pg0.remote_ip4)
self.assertEqual(config.collector_port, 514)
self.assertEqual(str(config.src_address), self.pg0.local_ip4)
self.assertEqual(config.vrf_id, 0)
self.assertEqual(config.max_msg_size, 480)
- appname = 'test'
- msgid = 'testMsg'
- msg = 'this is message'
- sd1 = {'exampleSDID@32473': {'iut': '3',
- 'eventSource': 'App',
- 'eventID': '1011'}}
- sd2 = {'exampleSDID@32473': {'iut': '3',
- 'eventSource': 'App',
- 'eventID': '1011'},
- 'examplePriority@32473': {'class': 'high'}}
+ appname = "test"
+ msgid = "testMsg"
+ msg = "this is message"
+ sd1 = {
+ "exampleSDID@32473": {"iut": "3", "eventSource": "App", "eventID": "1011"}
+ }
+ sd2 = {
+ "exampleSDID@32473": {"iut": "3", "eventSource": "App", "eventID": "1011"},
+ "examplePriority@32473": {"class": "high"},
+ }
self.pg_enable_capture(self.pg_interfaces)
- self.syslog_generate(SyslogFacility.local7,
- SyslogSeverity.info,
- appname,
- msgid,
- None,
- msg)
+ self.syslog_generate(
+ SyslogFacility.local7, SyslogSeverity.info, appname, msgid, None, msg
+ )
capture = self.pg0.get_capture(1)
try:
self.assertEqual(capture[0][IP].src, self.pg0.local_ip4)
@@ -140,71 +167,66 @@ class TestSyslog(VppTestCase):
except:
self.logger.error(ppp("invalid packet:", capture[0]))
raise
- self.syslog_verify(capture[0][Raw].load,
- SyslogFacility.local7,
- SyslogSeverity.info,
- appname,
- msgid,
- None,
- msg)
+ self.syslog_verify(
+ capture[0][Raw].load,
+ SyslogFacility.local7,
+ SyslogSeverity.info,
+ appname,
+ msgid,
+ None,
+ msg,
+ )
self.pg_enable_capture(self.pg_interfaces)
- self.vapi.syslog_set_filter(
- self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_WARN)
+ self.vapi.syslog_set_filter(self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_WARN)
filter = self.vapi.syslog_get_filter()
- self.assertEqual(filter.severity,
- self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_WARN)
- self.syslog_generate(SyslogFacility.local7,
- SyslogSeverity.info,
- appname,
- msgid,
- None,
- msg)
+ self.assertEqual(filter.severity, self.SYSLOG_SEVERITY.SYSLOG_API_SEVERITY_WARN)
+ self.syslog_generate(
+ SyslogFacility.local7, SyslogSeverity.info, appname, msgid, None, msg
+ )
self.pg0.assert_nothing_captured()
self.pg_enable_capture(self.pg_interfaces)
- self.syslog_generate(SyslogFacility.local6,
- SyslogSeverity.warning,
- appname,
- msgid,
- sd1,
- msg)
+ self.syslog_generate(
+ SyslogFacility.local6, SyslogSeverity.warning, appname, msgid, sd1, msg
+ )
capture = self.pg0.get_capture(1)
- self.syslog_verify(capture[0][Raw].load,
- SyslogFacility.local6,
- SyslogSeverity.warning,
- appname,
- msgid,
- sd1,
- msg)
-
- self.vapi.syslog_set_sender(self.pg0.local_ip4,
- self.pg0.remote_ip4,
- collector_port=12345)
+ self.syslog_verify(
+ capture[0][Raw].load,
+ SyslogFacility.local6,
+ SyslogSeverity.warning,
+ appname,
+ msgid,
+ sd1,
+ msg,
+ )
+
+ self.vapi.syslog_set_sender(
+ self.pg0.local_ip4, self.pg0.remote_ip4, collector_port=12345
+ )
config = self.vapi.syslog_get_sender()
self.assertEqual(config.collector_port, 12345)
self.pg_enable_capture(self.pg_interfaces)
- self.syslog_generate(SyslogFacility.local5,
- SyslogSeverity.err,
- appname,
- msgid,
- sd2,
- None)
+ self.syslog_generate(
+ SyslogFacility.local5, SyslogSeverity.err, appname, msgid, sd2, None
+ )
capture = self.pg0.get_capture(1)
try:
self.assertEqual(capture[0][UDP].dport, 12345)
except:
self.logger.error(ppp("invalid packet:", capture[0]))
raise
- self.syslog_verify(capture[0][Raw].load,
- SyslogFacility.local5,
- SyslogSeverity.err,
- appname,
- msgid,
- sd2,
- None)
-
-
-if __name__ == '__main__':
+ self.syslog_verify(
+ capture[0][Raw].load,
+ SyslogFacility.local5,
+ SyslogSeverity.err,
+ appname,
+ msgid,
+ sd2,
+ None,
+ )
+
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_tap.py b/test/test_tap.py
index 0e5b315963e..57014e4ecb3 100644
--- a/test/test_tap.py
+++ b/test/test_tap.py
@@ -11,7 +11,7 @@ def check_tuntap_driver_access():
@unittest.skip("Requires root")
class TestTAP(VppTestCase):
- """ TAP Test Case """
+ """TAP Test Case"""
def test_tap_add_del(self):
"""Create TAP interface"""
@@ -20,7 +20,7 @@ class TestTAP(VppTestCase):
self.assertTrue(tap0.query_vpp_config())
def test_tap_dump(self):
- """ Test api dump w/ and w/o sw_if_index filtering"""
+ """Test api dump w/ and w/o sw_if_index filtering"""
MAX_INSTANCES = 10
tap_instances = []
for instance in range(MAX_INSTANCES):
@@ -29,10 +29,9 @@ class TestTAP(VppTestCase):
tap_instances.append(i)
details = self.vapi.sw_interface_tap_v2_dump()
self.assertEqual(MAX_INSTANCES, len(details))
- details = self.vapi.sw_interface_tap_v2_dump(
- tap_instances[5].sw_if_index)
+ details = self.vapi.sw_interface_tap_v2_dump(tap_instances[5].sw_if_index)
self.assertEqual(1, len(details))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_tcp.py b/test/test_tcp.py
index f8e51057d38..de126362107 100644
--- a/test/test_tcp.py
+++ b/test/test_tcp.py
@@ -7,7 +7,7 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
class TestTCP(VppTestCase):
- """ TCP Test Case """
+ """TCP Test Case"""
@classmethod
def setUpClass(cls):
@@ -36,10 +36,12 @@ class TestTCP(VppTestCase):
table_id += 1
# Configure namespaces
- self.vapi.app_namespace_add_del(namespace_id="0",
- sw_if_index=self.loop0.sw_if_index)
- self.vapi.app_namespace_add_del(namespace_id="1",
- sw_if_index=self.loop1.sw_if_index)
+ self.vapi.app_namespace_add_del(
+ namespace_id="0", sw_if_index=self.loop0.sw_if_index
+ )
+ self.vapi.app_namespace_add_del(
+ namespace_id="1", sw_if_index=self.loop1.sw_if_index
+ )
def tearDown(self):
for i in self.lo_interfaces:
@@ -50,31 +52,38 @@ class TestTCP(VppTestCase):
super(TestTCP, self).tearDown()
def test_tcp_transfer(self):
- """ TCP echo client/server transfer """
+ """TCP echo client/server transfer"""
# Add inter-table routes
- ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=1)])
- ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=0)], table_id=1)
+ ip_t01 = VppIpRoute(
+ self,
+ self.loop1.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)],
+ )
+ ip_t10 = VppIpRoute(
+ self,
+ self.loop0.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)],
+ table_id=1,
+ )
ip_t01.add_vpp_config()
ip_t10.add_vpp_config()
# Start builtin server and client
uri = "tcp://" + self.loop0.local_ip4 + "/1234"
- error = self.vapi.cli("test echo server appns 0 fifo-size 4 uri " +
- uri)
+ error = self.vapi.cli("test echo server appns 0 fifo-size 4 uri " + uri)
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
- error = self.vapi.cli("test echo client mbytes 10 appns 1 " +
- "fifo-size 4 no-output test-bytes " +
- "syn-timeout 2 uri " + uri)
+ error = self.vapi.cli(
+ "test echo client mbytes 10 appns 1 "
+ + "fifo-size 4 no-output test-bytes "
+ + "syn-timeout 2 uri "
+ + uri
+ )
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
@@ -104,12 +113,13 @@ class TestTCPUnitTests(VppTestCase):
self.vapi.session_enable_disable(is_enable=0)
def test_tcp_unittest(self):
- """ TCP Unit Tests """
+ """TCP Unit Tests"""
error = self.vapi.cli("test tcp all")
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_tls.py b/test/test_tls.py
index 2f8edd4e0e2..301cddf5082 100644
--- a/test/test_tls.py
+++ b/test/test_tls.py
@@ -23,8 +23,9 @@ def checkOpenSSLVersion():
r = "OPENSSL_ROOT_DIR" in os.environ
if r:
ssl = os.environ["OPENSSL_ROOT_DIR"] + "/bin/openssl version"
- p = subprocess.Popen(ssl, stdin=subprocess.PIPE,
- stdout=subprocess.PIPE, shell=True)
+ p = subprocess.Popen(
+ ssl, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True
+ )
p.wait()
output = p.stdout.read()
status = p.returncode
@@ -52,7 +53,7 @@ def checkAll():
class TestTLS(VppTestCase):
- """ TLS Qat Test Case. """
+ """TLS Qat Test Case."""
@classmethod
def setUpClass(cls):
@@ -82,10 +83,12 @@ class TestTLS(VppTestCase):
table_id += 1
# Configure namespaces
- self.vapi.app_namespace_add_del(namespace_id="0",
- sw_if_index=self.loop0.sw_if_index)
- self.vapi.app_namespace_add_del(namespace_id="1",
- sw_if_index=self.loop1.sw_if_index)
+ self.vapi.app_namespace_add_del(
+ namespace_id="0", sw_if_index=self.loop0.sw_if_index
+ )
+ self.vapi.app_namespace_add_del(
+ namespace_id="1", sw_if_index=self.loop1.sw_if_index
+ )
def tearDown(self):
for i in self.lo_interfaces:
@@ -95,46 +98,49 @@ class TestTLS(VppTestCase):
self.vapi.session_enable_disable(is_enable=0)
super(TestTLS, self).tearDown()
- @unittest.skipUnless(checkAll(),
- "QAT or OpenSSL not satisfied,skip.")
+ @unittest.skipUnless(checkAll(), "QAT or OpenSSL not satisfied,skip.")
def test_tls_transfer(self):
- """ TLS qat echo client/server transfer """
+ """TLS qat echo client/server transfer"""
# Add inter-table routes
- ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=1)])
-
- ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=0)], table_id=1)
+ ip_t01 = VppIpRoute(
+ self,
+ self.loop1.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)],
+ )
+
+ ip_t10 = VppIpRoute(
+ self,
+ self.loop0.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)],
+ table_id=1,
+ )
ip_t01.add_vpp_config()
ip_t10.add_vpp_config()
# Enable QAT engine and TLS async
r = self.vapi.tls_openssl_set_engine(
- async_enable=1,
- engine="qat",
- algorithm="RSA,PKEY_CRYPTO",
- ciphers="RSA")
- self.assertIsNotNone(r,
- 'No response msg ')
+ async_enable=1, engine="qat", algorithm="RSA,PKEY_CRYPTO", ciphers="RSA"
+ )
+ self.assertIsNotNone(r, "No response msg ")
# Start builtin server and client
uri = "tls://" + self.loop0.local_ip4 + "/1234"
- error = self.vapi.cli("test echo server appns 0 fifo-size 4 "
- "tls-engine 1 uri " +
- uri)
+ error = self.vapi.cli(
+ "test echo server appns 0 fifo-size 4 tls-engine 1 uri " + uri
+ )
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
- error = self.vapi.cli("test echo client mbytes 10 appns 1 "
- "fifo-size 4 no-output test-bytes "
- "tls-engine 1 "
- "syn-timeout 2 uri " + uri)
+ error = self.vapi.cli(
+ "test echo client mbytes 10 appns 1 "
+ "fifo-size 4 no-output test-bytes "
+ "tls-engine 1 "
+ "syn-timeout 2 uri " + uri
+ )
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
@@ -144,5 +150,5 @@ class TestTLS(VppTestCase):
ip_t10.remove_vpp_config()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_trace_filter.py b/test/test_trace_filter.py
index fa0d74812f5..3c1f778a0f7 100644
--- a/test/test_trace_filter.py
+++ b/test/test_trace_filter.py
@@ -15,7 +15,7 @@ from scapy.utils import rdpcap
class TestTracefilter(VppTestCase):
- """ Packet Tracer Filter Test """
+ """Packet Tracer Filter Test"""
@classmethod
def setUpClass(cls):
@@ -43,8 +43,11 @@ class TestTracefilter(VppTestCase):
def cli(self, cmd):
r = self.vapi.cli_return_response(cmd)
if r.retval != 0:
- s = "reply '%s'" % r.reply if hasattr(
- r, "reply") else "retval '%s'" % r.retval
+ s = (
+ "reply '%s'" % r.reply
+ if hasattr(r, "reply")
+ else "retval '%s'" % r.retval
+ )
raise RuntimeError("cli command '%s' FAIL with %s" % (cmd, s))
return r
@@ -71,26 +74,34 @@ class TestTracefilter(VppTestCase):
self.assertTrue(r.reply.find(s) != -1)
def test_basic(self):
- """ Packet Tracer Filter Test """
+ """Packet Tracer Filter Test"""
self.add_trace_filter(
- "l3 ip4 src",
- "l3 ip4 src %s" %
- self.pg0.remote_hosts[5].ip4)
+ "l3 ip4 src", "l3 ip4 src %s" % self.pg0.remote_hosts[5].ip4
+ )
self.add_trace_filter(
- "l3 ip4 proto l4 src_port",
- "l3 ip4 proto 17 l4 src_port 2345")
+ "l3 ip4 proto l4 src_port", "l3 ip4 proto 17 l4 src_port 2345"
+ )
# the packet we are trying to match
p = list()
for i in range(100):
src = self.pg0.remote_hosts[i % len(self.pg0.remote_hosts)].ip4
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=src, dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=2345) / Raw('\xa5' * 100)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=src, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=2345)
+ / Raw("\xa5" * 100)
+ )
+ )
for i in range(17):
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_hosts[0].ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=2345, dport=1234) / Raw('\xa5' * 100)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_hosts[0].ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=2345, dport=1234)
+ / Raw("\xa5" * 100)
+ )
+ )
self.send_and_expect(self.pg0, p, self.pg1, trace=False)
@@ -108,21 +119,23 @@ class TestTracefilter(VppTestCase):
self.del_trace_filters()
def test_encap(self):
- """ Packet Tracer Filter Test with encap """
+ """Packet Tracer Filter Test with encap"""
# the packet we are trying to match
- p = (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4) /
- UDP() /
- VXLAN() /
- Ether() /
- IP() /
- UDP() /
- GENEVE(vni=1234) /
- Ether() /
- IP(src='192.168.4.167') /
- UDP() /
- Raw('\xa5' * 100))
+ p = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP()
+ / VXLAN()
+ / Ether()
+ / IP()
+ / UDP()
+ / GENEVE(vni=1234)
+ / Ether()
+ / IP(src="192.168.4.167")
+ / UDP()
+ / Raw("\xa5" * 100)
+ )
#
# compute filter mask & value
@@ -130,29 +143,31 @@ class TestTracefilter(VppTestCase):
# we need to set checksums to 0 to make sure scapy will not recompute
# them
#
- tmpl = (Ether() /
- IP(chksum=0) /
- UDP(chksum=0) /
- VXLAN() /
- Ether() /
- IP(chksum=0) /
- UDP(chksum=0) /
- GENEVE(vni=0) /
- Ether() /
- IP(src='0.0.0.0', chksum=0))
+ tmpl = (
+ Ether()
+ / IP(chksum=0)
+ / UDP(chksum=0)
+ / VXLAN()
+ / Ether()
+ / IP(chksum=0)
+ / UDP(chksum=0)
+ / GENEVE(vni=0)
+ / Ether()
+ / IP(src="0.0.0.0", chksum=0)
+ )
ori = raw(tmpl)
# the mask
- tmpl[GENEVE].vni = 0xffffff
+ tmpl[GENEVE].vni = 0xFFFFFF
user = tmpl[GENEVE].payload
- user[IP].src = '255.255.255.255'
+ user[IP].src = "255.255.255.255"
new = raw(tmpl)
mask = "".join(("{:02x}".format(o ^ n) for o, n in zip(ori, new)))
# this does not match (wrong vni)
tmpl[GENEVE].vni = 1
user = tmpl[GENEVE].payload
- user[IP].src = '192.168.4.167'
+ user[IP].src = "192.168.4.167"
new = raw(tmpl)
match = "".join(("{:02x}".format(o ^ n) for o, n in zip(ori, new)))
self.assert_classify(mask, match, [p] * 11, 0)
@@ -164,29 +179,41 @@ class TestTracefilter(VppTestCase):
self.assert_classify(mask, match, [p] * 17)
def test_pcap(self):
- """ Packet Capture Filter Test """
+ """Packet Capture Filter Test"""
self.cli(
- "classify filter pcap mask l3 ip4 src match l3 ip4 src %s" %
- self.pg0.remote_hosts[5].ip4)
+ "classify filter pcap mask l3 ip4 src match l3 ip4 src %s"
+ % self.pg0.remote_hosts[5].ip4
+ )
self.cli(
"classify filter pcap "
"mask l3 ip4 proto l4 src_port "
- "match l3 ip4 proto 17 l4 src_port 2345")
+ "match l3 ip4 proto 17 l4 src_port 2345"
+ )
self.cli(
"pcap trace rx tx max 1000 intfc pg0 "
- "file vpp_test_trace_filter_test_pcap.pcap filter")
+ "file vpp_test_trace_filter_test_pcap.pcap filter"
+ )
# the packet we are trying to match
p = list()
for i in range(100):
src = self.pg0.remote_hosts[i % len(self.pg0.remote_hosts)].ip4
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=src, dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=2345) / Raw('\xa5' * 100)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=src, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=2345)
+ / Raw("\xa5" * 100)
+ )
+ )
for i in range(17):
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_hosts[0].ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=2345, dport=1234) / Raw('\xa5' * 100)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_hosts[0].ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=2345, dport=1234)
+ / Raw("\xa5" * 100)
+ )
+ )
self.send_and_expect(self.pg0, p, self.pg1, trace=False)
@@ -208,28 +235,42 @@ class TestTracefilter(VppTestCase):
self.assertEqual(str(pcap[i]), p_)
def test_pcap_drop(self):
- """ Drop Packet Capture Filter Test """
+ """Drop Packet Capture Filter Test"""
self.cli(
"pcap trace drop max 1000 "
"error {ip4-udp-lookup}.{no_listener} "
- "file vpp_test_trace_filter_test_pcap_drop.pcap")
+ "file vpp_test_trace_filter_test_pcap_drop.pcap"
+ )
# the packet we are trying to match
p = list()
for i in range(17):
# this packet should be forwarded
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_hosts[0].ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=2345, dport=1234) / Raw('\xa5' * 100)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_hosts[0].ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=2345, dport=1234)
+ / Raw("\xa5" * 100)
+ )
+ )
# this packet should be captured (no listener)
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_hosts[0].ip4,
- dst=self.pg0.local_ip4) /
- UDP(sport=2345, dport=1234) / Raw('\xa5' * 100)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_hosts[0].ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=2345, dport=1234)
+ / Raw("\xa5" * 100)
+ )
+ )
# this packet will be blackholed but not captured
- p.append((Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_hosts[0].ip4, dst="0.0.0.0") /
- UDP(sport=2345, dport=1234) / Raw('\xa5' * 100)))
+ p.append(
+ (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_hosts[0].ip4, dst="0.0.0.0")
+ / UDP(sport=2345, dport=1234)
+ / Raw("\xa5" * 100)
+ )
+ )
self.send_and_expect(self.pg0, p, self.pg1, n_rx=17, trace=False)
@@ -240,5 +281,5 @@ class TestTracefilter(VppTestCase):
self.assertEqual(len(pcap), 17)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_udp.py b/test/test_udp.py
index 031867cf63d..c7e97c641b8 100644
--- a/test/test_udp.py
+++ b/test/test_udp.py
@@ -5,8 +5,16 @@ from framework import VppTestCase, VppTestRunner
from vpp_udp_encap import find_udp_encap, VppUdpEncap
from vpp_udp_decap import VppUdpDecap
-from vpp_ip_route import VppIpRoute, VppRoutePath, VppIpTable, VppMplsLabel, \
- VppMplsTable, VppMplsRoute, FibPathType, FibPathProto
+from vpp_ip_route import (
+ VppIpRoute,
+ VppRoutePath,
+ VppIpTable,
+ VppMplsLabel,
+ VppMplsTable,
+ VppMplsRoute,
+ FibPathType,
+ FibPathProto,
+)
from vpp_neighbor import VppNeighbor
from vpp_papi import VppEnum
@@ -21,7 +29,7 @@ NUM_PKTS = 67
@tag_fixme_vpp_workers
class TestUdpEncap(VppTestCase):
- """ UDP Encap Test Case """
+ """UDP Encap Test Case"""
@classmethod
def setUpClass(cls):
@@ -99,8 +107,7 @@ class TestUdpEncap(VppTestCase):
self.assertEqual(rx.hlim, tx[IPv6].hlim)
def test_udp_encap(self):
- """ UDP Encap test
- """
+ """UDP Encap test"""
#
# construct a UDP encap object through each of the peers
@@ -109,29 +116,21 @@ class TestUdpEncap(VppTestCase):
# where 2 different udp encap objects are processed at the
# same time
#
- udp_encap_0 = VppUdpEncap(self,
- self.pg0.local_ip4,
- self.pg0.remote_ip4,
- 330, 440)
- udp_encap_1 = VppUdpEncap(self,
- self.pg1.local_ip4,
- self.pg1.remote_ip4,
- 331, 441,
- table_id=1)
- udp_encap_2 = VppUdpEncap(self,
- self.pg2.local_ip6,
- self.pg2.remote_ip6,
- 332, 442,
- table_id=2)
- udp_encap_3 = VppUdpEncap(self,
- self.pg3.local_ip6,
- self.pg3.remote_ip6,
- 333, 443,
- table_id=3)
- udp_encap_4 = VppUdpEncap(self,
- self.pg0.local_ip4,
- self.pg0.remote_ip4,
- 334, 444)
+ udp_encap_0 = VppUdpEncap(
+ self, self.pg0.local_ip4, self.pg0.remote_ip4, 330, 440
+ )
+ udp_encap_1 = VppUdpEncap(
+ self, self.pg1.local_ip4, self.pg1.remote_ip4, 331, 441, table_id=1
+ )
+ udp_encap_2 = VppUdpEncap(
+ self, self.pg2.local_ip6, self.pg2.remote_ip6, 332, 442, table_id=2
+ )
+ udp_encap_3 = VppUdpEncap(
+ self, self.pg3.local_ip6, self.pg3.remote_ip6, 333, 443, table_id=3
+ )
+ udp_encap_4 = VppUdpEncap(
+ self, self.pg0.local_ip4, self.pg0.remote_ip4, 334, 444
+ )
udp_encap_0.add_vpp_config()
udp_encap_1.add_vpp_config()
udp_encap_2.add_vpp_config()
@@ -150,44 +149,79 @@ class TestUdpEncap(VppTestCase):
# Routes via each UDP encap object - all combinations of v4 and v6.
#
route_4o4 = VppIpRoute(
- self, "1.1.0.1", 24,
- [VppRoutePath("0.0.0.0",
- 0xFFFFFFFF,
- type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
- next_hop_id=udp_encap_0.id,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)],
- table_id=1)
+ self,
+ "1.1.0.1",
+ 24,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
+ next_hop_id=udp_encap_0.id,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ )
+ ],
+ table_id=1,
+ )
# specific route to match encap4, to test encap of 2 packets using 2
# different encap
route_4o4_2 = VppIpRoute(
- self, "1.1.0.2", 32,
- [VppRoutePath("0.0.0.0",
- 0xFFFFFFFF,
- type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
- next_hop_id=udp_encap_4.id,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)],
- table_id=1)
+ self,
+ "1.1.0.2",
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
+ next_hop_id=udp_encap_4.id,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ )
+ ],
+ table_id=1,
+ )
route_4o6 = VppIpRoute(
- self, "1.1.2.1", 32,
- [VppRoutePath("0.0.0.0",
- 0xFFFFFFFF,
- type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
- next_hop_id=udp_encap_2.id,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)])
+ self,
+ "1.1.2.1",
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
+ next_hop_id=udp_encap_2.id,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ )
+ ],
+ )
route_6o4 = VppIpRoute(
- self, "2001::1", 128,
- [VppRoutePath("0.0.0.0",
- 0xFFFFFFFF,
- type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
- next_hop_id=udp_encap_1.id,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ self,
+ "2001::1",
+ 128,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
+ next_hop_id=udp_encap_1.id,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
+ ],
+ )
route_6o6 = VppIpRoute(
- self, "2001::3", 128,
- [VppRoutePath("0.0.0.0",
- 0xFFFFFFFF,
- type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
- next_hop_id=udp_encap_3.id,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP6)])
+ self,
+ "2001::3",
+ 128,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
+ next_hop_id=udp_encap_3.id,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP6,
+ )
+ ],
+ )
route_4o6.add_vpp_config()
route_6o6.add_vpp_config()
route_6o4.add_vpp_config()
@@ -200,104 +234,117 @@ class TestUdpEncap(VppTestCase):
# the packet vector so that we encap 2 packets with different udp
# encap object at the same time
#
- p_4o4 = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IP(src="2.2.2.2", dst="1.1.0.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- p_4o4_2 = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IP(src="2.2.2.2", dst="1.1.0.2") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
+ p_4o4 = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src="2.2.2.2", dst="1.1.0.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ p_4o4_2 = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IP(src="2.2.2.2", dst="1.1.0.2")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
rx = self.send_and_expect(
- self.pg1, p_4o4_2 * 1 + p_4o4 * (NUM_PKTS - 1), self.pg0)
+ self.pg1, p_4o4_2 * 1 + p_4o4 * (NUM_PKTS - 1), self.pg0
+ )
# checking encap4 magic packet
p = rx.pop(0)
self.validate_outer4(p, udp_encap_4)
p = IP(p["UDP"].payload.load)
self.validate_inner4(p, p_4o4_2)
- self.assertEqual(udp_encap_4.get_stats()['packets'], 1)
+ self.assertEqual(udp_encap_4.get_stats()["packets"], 1)
# checking remaining packets for encap0
for p in rx:
self.validate_outer4(p, udp_encap_0)
p = IP(p["UDP"].payload.load)
self.validate_inner4(p, p_4o4)
- self.assertEqual(udp_encap_0.get_stats()['packets'], NUM_PKTS - 1)
+ self.assertEqual(udp_encap_0.get_stats()["packets"], NUM_PKTS - 1)
#
# 4o6 encap
#
- p_4o6 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="2.2.2.2", dst="1.1.2.1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- rx = self.send_and_expect(self.pg0, p_4o6*NUM_PKTS, self.pg2)
+ p_4o6 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="2.2.2.2", dst="1.1.2.1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ rx = self.send_and_expect(self.pg0, p_4o6 * NUM_PKTS, self.pg2)
for p in rx:
self.validate_outer6(p, udp_encap_2)
p = IP(p["UDP"].payload.load)
self.validate_inner4(p, p_4o6)
- self.assertEqual(udp_encap_2.get_stats()['packets'], NUM_PKTS)
+ self.assertEqual(udp_encap_2.get_stats()["packets"], NUM_PKTS)
#
# 6o4 encap
#
- p_6o4 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src="2001::100", dst="2001::1") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- rx = self.send_and_expect(self.pg0, p_6o4*NUM_PKTS, self.pg1)
+ p_6o4 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src="2001::100", dst="2001::1")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ rx = self.send_and_expect(self.pg0, p_6o4 * NUM_PKTS, self.pg1)
for p in rx:
self.validate_outer4(p, udp_encap_1)
p = IPv6(p["UDP"].payload.load)
self.validate_inner6(p, p_6o4)
- self.assertEqual(udp_encap_1.get_stats()['packets'], NUM_PKTS)
+ self.assertEqual(udp_encap_1.get_stats()["packets"], NUM_PKTS)
#
# 6o6 encap
#
- p_6o6 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IPv6(src="2001::100", dst="2001::3") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- rx = self.send_and_expect(self.pg0, p_6o6*NUM_PKTS, self.pg3)
+ p_6o6 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src="2001::100", dst="2001::3")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ rx = self.send_and_expect(self.pg0, p_6o6 * NUM_PKTS, self.pg3)
for p in rx:
self.validate_outer6(p, udp_encap_3)
p = IPv6(p["UDP"].payload.load)
self.validate_inner6(p, p_6o6)
- self.assertEqual(udp_encap_3.get_stats()['packets'], NUM_PKTS)
+ self.assertEqual(udp_encap_3.get_stats()["packets"], NUM_PKTS)
#
# A route with an output label
# the TTL of the inner packet is decremented on LSP ingress
#
route_4oMPLSo4 = VppIpRoute(
- self, "1.1.2.22", 32,
- [VppRoutePath("0.0.0.0",
- 0xFFFFFFFF,
- type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
- next_hop_id=1,
- labels=[VppMplsLabel(66)])])
+ self,
+ "1.1.2.22",
+ 32,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ type=FibPathType.FIB_PATH_TYPE_UDP_ENCAP,
+ next_hop_id=1,
+ labels=[VppMplsLabel(66)],
+ )
+ ],
+ )
route_4oMPLSo4.add_vpp_config()
- p_4omo4 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src="2.2.2.2", dst="1.1.2.22") /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100))
- rx = self.send_and_expect(self.pg0, p_4omo4*NUM_PKTS, self.pg1)
+ p_4omo4 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src="2.2.2.2", dst="1.1.2.22")
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ )
+ rx = self.send_and_expect(self.pg0, p_4omo4 * NUM_PKTS, self.pg1)
for p in rx:
self.validate_outer4(p, udp_encap_1)
p = MPLS(p["UDP"].payload.load)
self.validate_inner4(p, p_4omo4, ttl=63)
- self.assertEqual(udp_encap_1.get_stats()['packets'], 2*NUM_PKTS)
+ self.assertEqual(udp_encap_1.get_stats()["packets"], 2 * NUM_PKTS)
def test_udp_decap(self):
- """ UDP Decap test
- """
+ """UDP Decap test"""
#
# construct a UDP decap object for each type of protocol
#
@@ -323,19 +370,24 @@ class TestUdpEncap(VppTestCase):
# Routes via the corresponding pg after the UDP decap
#
route_4 = VppIpRoute(
- self, "1.1.1.1", 32,
+ self,
+ "1.1.1.1",
+ 32,
[VppRoutePath("0.0.0.0", self.pg0.sw_if_index)],
- table_id=0)
+ table_id=0,
+ )
route_6 = VppIpRoute(
- self, "2001::1", 128,
- [VppRoutePath("::", self.pg1.sw_if_index)],
- table_id=1)
+ self, "2001::1", 128, [VppRoutePath("::", self.pg1.sw_if_index)], table_id=1
+ )
route_mo4 = VppIpRoute(
- self, "3.3.3.3", 32,
+ self,
+ "3.3.3.3",
+ 32,
[VppRoutePath("0.0.0.0", self.pg2.sw_if_index)],
- table_id=2)
+ table_id=2,
+ )
route_4.add_vpp_config()
route_6.add_vpp_config()
@@ -344,18 +396,9 @@ class TestUdpEncap(VppTestCase):
#
# Adding neighbors to route the packets
#
- n_4 = VppNeighbor(self,
- self.pg0.sw_if_index,
- "00:11:22:33:44:55",
- "1.1.1.1")
- n_6 = VppNeighbor(self,
- self.pg1.sw_if_index,
- "11:22:33:44:55:66",
- "2001::1")
- n_mo4 = VppNeighbor(self,
- self.pg2.sw_if_index,
- "22:33:44:55:66:77",
- "3.3.3.3")
+ n_4 = VppNeighbor(self, self.pg0.sw_if_index, "00:11:22:33:44:55", "1.1.1.1")
+ n_6 = VppNeighbor(self, self.pg1.sw_if_index, "11:22:33:44:55:66", "2001::1")
+ n_mo4 = VppNeighbor(self, self.pg2.sw_if_index, "22:33:44:55:66:77", "3.3.3.3")
n_4.add_vpp_config()
n_6.add_vpp_config()
@@ -367,25 +410,33 @@ class TestUdpEncap(VppTestCase):
mpls_table = VppMplsTable(self, 0)
mpls_table.add_vpp_config()
mpls_route = VppMplsRoute(
- self, 77, 1,
- [VppRoutePath("0.0.0.0",
- 0xFFFFFFFF,
- nh_table_id=2,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4)])
+ self,
+ 77,
+ 1,
+ [
+ VppRoutePath(
+ "0.0.0.0",
+ 0xFFFFFFFF,
+ nh_table_id=2,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ )
+ ],
+ )
mpls_route.add_vpp_config()
#
# UDP over ipv4 decap
#
- p_4 = (Ether(src=self.pg0.remote_mac,
- dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=1111, dport=220) /
- IP(src="2.2.2.2", dst="1.1.1.1") /
- UDP(sport=1234, dport=4321) /
- Raw(b'\xa5' * 100))
-
- rx = self.send_and_expect(self.pg0, p_4*NUM_PKTS, self.pg0)
+ p_4 = (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=1111, dport=220)
+ / IP(src="2.2.2.2", dst="1.1.1.1")
+ / UDP(sport=1234, dport=4321)
+ / Raw(b"\xa5" * 100)
+ )
+
+ rx = self.send_and_expect(self.pg0, p_4 * NUM_PKTS, self.pg0)
p_4 = IP(p_4["UDP"].payload)
for p in rx:
p = IP(p["Ether"].payload)
@@ -394,15 +445,16 @@ class TestUdpEncap(VppTestCase):
#
# UDP over ipv6 decap
#
- p_6 = (Ether(src=self.pg1.remote_mac,
- dst=self.pg1.local_mac) /
- IPv6(src=self.pg1.remote_ip6, dst=self.pg1.local_ip6) /
- UDP(sport=2222, dport=221) /
- IPv6(src="2001::100", dst="2001::1") /
- UDP(sport=1234, dport=4321) /
- Raw(b'\xa5' * 100))
-
- rx = self.send_and_expect(self.pg1, p_6*NUM_PKTS, self.pg1)
+ p_6 = (
+ Ether(src=self.pg1.remote_mac, dst=self.pg1.local_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.local_ip6)
+ / UDP(sport=2222, dport=221)
+ / IPv6(src="2001::100", dst="2001::1")
+ / UDP(sport=1234, dport=4321)
+ / Raw(b"\xa5" * 100)
+ )
+
+ rx = self.send_and_expect(self.pg1, p_6 * NUM_PKTS, self.pg1)
p_6 = IPv6(p_6["UDP"].payload)
p = IPv6(rx[0]["Ether"].payload)
for p in rx:
@@ -412,17 +464,18 @@ class TestUdpEncap(VppTestCase):
#
# UDP over mpls decap
#
- p_mo4 = (Ether(src=self.pg2.remote_mac,
- dst=self.pg2.local_mac) /
- IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4) /
- UDP(sport=3333, dport=222) /
- MPLS(label=77, ttl=1) /
- IP(src="4.4.4.4", dst="3.3.3.3") /
- UDP(sport=1234, dport=4321) /
- Raw(b'\xa5' * 100))
+ p_mo4 = (
+ Ether(src=self.pg2.remote_mac, dst=self.pg2.local_mac)
+ / IP(src=self.pg2.remote_ip4, dst=self.pg2.local_ip4)
+ / UDP(sport=3333, dport=222)
+ / MPLS(label=77, ttl=1)
+ / IP(src="4.4.4.4", dst="3.3.3.3")
+ / UDP(sport=1234, dport=4321)
+ / Raw(b"\xa5" * 100)
+ )
self.pg2.enable_mpls()
- rx = self.send_and_expect(self.pg2, p_mo4*NUM_PKTS, self.pg2)
+ rx = self.send_and_expect(self.pg2, p_mo4 * NUM_PKTS, self.pg2)
self.pg2.disable_mpls()
p_mo4 = IP(MPLS(p_mo4["UDP"].payload).payload)
for p in rx:
@@ -432,7 +485,7 @@ class TestUdpEncap(VppTestCase):
@tag_fixme_vpp_workers
class TestUDP(VppTestCase):
- """ UDP Test Case """
+ """UDP Test Case"""
@classmethod
def setUpClass(cls):
@@ -461,10 +514,12 @@ class TestUDP(VppTestCase):
table_id += 1
# Configure namespaces
- self.vapi.app_namespace_add_del(namespace_id="0",
- sw_if_index=self.loop0.sw_if_index)
- self.vapi.app_namespace_add_del(namespace_id="1",
- sw_if_index=self.loop1.sw_if_index)
+ self.vapi.app_namespace_add_del(
+ namespace_id="0", sw_if_index=self.loop0.sw_if_index
+ )
+ self.vapi.app_namespace_add_del(
+ namespace_id="1", sw_if_index=self.loop1.sw_if_index
+ )
def tearDown(self):
for i in self.lo_interfaces:
@@ -475,31 +530,40 @@ class TestUDP(VppTestCase):
super(TestUDP, self).tearDown()
def test_udp_transfer(self):
- """ UDP echo client/server transfer """
+ """UDP echo client/server transfer"""
# Add inter-table routes
- ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=1)])
- ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=0)], table_id=1)
+ ip_t01 = VppIpRoute(
+ self,
+ self.loop1.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)],
+ )
+ ip_t10 = VppIpRoute(
+ self,
+ self.loop0.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=0)],
+ table_id=1,
+ )
ip_t01.add_vpp_config()
ip_t10.add_vpp_config()
# Start builtin server and client
uri = "udp://" + self.loop0.local_ip4 + "/1234"
- error = self.vapi.cli("test echo server appns 0 fifo-size 4 no-echo" +
- "uri " + uri)
+ error = self.vapi.cli(
+ "test echo server appns 0 fifo-size 4 no-echo" + "uri " + uri
+ )
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
- error = self.vapi.cli("test echo client mbytes 10 appns 1 " +
- "fifo-size 4 no-output test-bytes " +
- "syn-timeout 2 no-return uri " + uri)
+ error = self.vapi.cli(
+ "test echo client mbytes 10 appns 1 "
+ + "fifo-size 4 no-output test-bytes "
+ + "syn-timeout 2 no-return uri "
+ + uri
+ )
if error:
self.logger.critical(error)
self.assertNotIn("failed", error)
@@ -511,5 +575,5 @@ class TestUDP(VppTestCase):
ip_t10.remove_vpp_config()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_urpf.py b/test/test_urpf.py
index 8f4e563f8bc..e0dc1210bfc 100644
--- a/test/test_urpf.py
+++ b/test/test_urpf.py
@@ -15,7 +15,7 @@ N_PKTS = 63
class TestURPF(VppTestCase):
- """ Unicast Reverse Path Forwarding Test Case """
+ """Unicast Reverse Path Forwarding Test Case"""
@classmethod
def setUpClass(cls):
@@ -47,26 +47,27 @@ class TestURPF(VppTestCase):
super(TestURPF, self).tearDown()
def test_urpf4(self):
- """ uRPF IP4 """
+ """uRPF IP4"""
e = VppEnum
- p_spoof_loose = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src="3.3.3.3", dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)) * N_PKTS
- p_spoof_strict = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=self.pg2.remote_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)) * N_PKTS
- p_good = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)) * N_PKTS
+ p_spoof_loose = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src="3.3.3.3", dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ) * N_PKTS
+ p_spoof_strict = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg2.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ) * N_PKTS
+ p_good = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ) * N_PKTS
#
# before adding the uRPF, ensure all packets are forwarded
@@ -78,10 +79,12 @@ class TestURPF(VppTestCase):
#
# apply loose uRPF check on pg0 rx
#
- self.vapi.urpf_update(is_input=True,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE,
- af=e.vl_api_address_family_t.ADDRESS_IP4,
- sw_if_index=self.pg0.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=True,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE,
+ af=e.vl_api_address_family_t.ADDRESS_IP4,
+ sw_if_index=self.pg0.sw_if_index,
+ )
# good packets still pass
self.send_and_expect(self.pg0, p_good, self.pg1)
@@ -90,16 +93,17 @@ class TestURPF(VppTestCase):
# packets from address to which there is no route are dropped
self.send_and_assert_no_replies(self.pg0, p_spoof_loose)
- self.assert_error_counter_equal("/err/ip4-rx-urpf-loose/uRPF Drop",
- N_PKTS)
+ self.assert_error_counter_equal("/err/ip4-rx-urpf-loose/uRPF Drop", N_PKTS)
#
# crank it up to strict mode
#
- self.vapi.urpf_update(is_input=True,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT,
- af=e.vl_api_address_family_t.ADDRESS_IP4,
- sw_if_index=self.pg0.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=True,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT,
+ af=e.vl_api_address_family_t.ADDRESS_IP4,
+ sw_if_index=self.pg0.sw_if_index,
+ )
# good packets still pass
self.send_and_expect(self.pg0, p_good, self.pg1)
@@ -107,16 +111,17 @@ class TestURPF(VppTestCase):
self.send_and_assert_no_replies(self.pg0, p_spoof_strict)
self.send_and_assert_no_replies(self.pg0, p_spoof_loose)
- self.assert_error_counter_equal("/err/ip4-rx-urpf-strict/uRPF Drop",
- 2 * N_PKTS)
+ self.assert_error_counter_equal("/err/ip4-rx-urpf-strict/uRPF Drop", 2 * N_PKTS)
#
# disable uRPF, all traffic should pass
#
- self.vapi.urpf_update(is_input=True,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF,
- af=e.vl_api_address_family_t.ADDRESS_IP4,
- sw_if_index=self.pg0.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=True,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF,
+ af=e.vl_api_address_family_t.ADDRESS_IP4,
+ sw_if_index=self.pg0.sw_if_index,
+ )
self.send_and_expect(self.pg0, p_good, self.pg1)
self.send_and_expect(self.pg0, p_spoof_strict, self.pg1)
@@ -129,22 +134,25 @@ class TestURPF(VppTestCase):
# for strict they should not be forwarded if they would be
# forwarded thru that interface.
#
- self.vapi.urpf_update(is_input=False,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE,
- af=e.vl_api_address_family_t.ADDRESS_IP4,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=False,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE,
+ af=e.vl_api_address_family_t.ADDRESS_IP4,
+ sw_if_index=self.pg1.sw_if_index,
+ )
self.send_and_expect(self.pg0, p_good, self.pg1)
self.send_and_expect(self.pg0, p_spoof_strict, self.pg1)
self.send_and_assert_no_replies(self.pg0, p_spoof_loose)
- self.assert_error_counter_equal("/err/ip4-tx-urpf-loose/uRPF Drop",
- N_PKTS)
+ self.assert_error_counter_equal("/err/ip4-tx-urpf-loose/uRPF Drop", N_PKTS)
- self.vapi.urpf_update(is_input=False,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT,
- af=e.vl_api_address_family_t.ADDRESS_IP4,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=False,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT,
+ af=e.vl_api_address_family_t.ADDRESS_IP4,
+ sw_if_index=self.pg1.sw_if_index,
+ )
self.send_and_expect(self.pg0, p_good, self.pg1)
# the strict packet, from a peer is allowed, since it does
@@ -152,48 +160,49 @@ class TestURPF(VppTestCase):
self.send_and_expect(self.pg0, p_spoof_strict, self.pg1)
self.send_and_assert_no_replies(self.pg0, p_spoof_loose)
- self.assert_error_counter_equal("/err/ip4-tx-urpf-strict/uRPF Drop",
- N_PKTS)
+ self.assert_error_counter_equal("/err/ip4-tx-urpf-strict/uRPF Drop", N_PKTS)
# change the strict packet so that it would forward through pg1
- p_spoof_strict = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IP(src=self.pg1.remote_ip4,
- dst=self.pg1.remote_ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(b'\xa5' * 100)) * N_PKTS
+ p_spoof_strict = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg1.remote_ip4, dst=self.pg1.remote_ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(b"\xa5" * 100)
+ ) * N_PKTS
self.send_and_assert_no_replies(self.pg0, p_spoof_strict)
- self.assert_error_counter_equal("/err/ip4-tx-urpf-strict/uRPF Drop",
- 2 * N_PKTS)
+ self.assert_error_counter_equal("/err/ip4-tx-urpf-strict/uRPF Drop", 2 * N_PKTS)
# cleanup
- self.vapi.urpf_update(is_input=False,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF,
- af=e.vl_api_address_family_t.ADDRESS_IP4,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=False,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF,
+ af=e.vl_api_address_family_t.ADDRESS_IP4,
+ sw_if_index=self.pg1.sw_if_index,
+ )
def test_urpf6(self):
- """ uRPF IP6 """
+ """uRPF IP6"""
e = VppEnum
- p_spoof_loose = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src="3::3", dst=self.pg1.remote_ip6) /
- UDP(sport=1236, dport=1236) /
- Raw(b'\xa5' * 100)) * N_PKTS
- p_spoof_strict = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg2.remote_ip6,
- dst=self.pg1.remote_ip6) /
- UDP(sport=1236, dport=1236) /
- Raw(b'\xa5' * 100)) * N_PKTS
- p_good = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6,
- dst=self.pg1.remote_ip6) /
- UDP(sport=1236, dport=1236) /
- Raw(b'\xa5' * 100)) * N_PKTS
+ p_spoof_loose = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src="3::3", dst=self.pg1.remote_ip6)
+ / UDP(sport=1236, dport=1236)
+ / Raw(b"\xa5" * 100)
+ ) * N_PKTS
+ p_spoof_strict = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg2.remote_ip6, dst=self.pg1.remote_ip6)
+ / UDP(sport=1236, dport=1236)
+ / Raw(b"\xa5" * 100)
+ ) * N_PKTS
+ p_good = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg1.remote_ip6)
+ / UDP(sport=1236, dport=1236)
+ / Raw(b"\xa5" * 100)
+ ) * N_PKTS
#
# before adding the uRPF, ensure all packets are forwarded
@@ -205,10 +214,12 @@ class TestURPF(VppTestCase):
#
# apply loose uRPF check on pg0 rx
#
- self.vapi.urpf_update(is_input=True,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE,
- af=e.vl_api_address_family_t.ADDRESS_IP6,
- sw_if_index=self.pg0.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=True,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE,
+ af=e.vl_api_address_family_t.ADDRESS_IP6,
+ sw_if_index=self.pg0.sw_if_index,
+ )
# good packets still pass
self.send_and_expect(self.pg0, p_good, self.pg1)
@@ -217,16 +228,17 @@ class TestURPF(VppTestCase):
# packets from address to which there is no route are dropped
self.send_and_assert_no_replies(self.pg0, p_spoof_loose)
- self.assert_error_counter_equal("/err/ip6-rx-urpf-loose/uRPF Drop",
- N_PKTS)
+ self.assert_error_counter_equal("/err/ip6-rx-urpf-loose/uRPF Drop", N_PKTS)
#
# crank it up to strict mode
#
- self.vapi.urpf_update(is_input=True,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT,
- af=e.vl_api_address_family_t.ADDRESS_IP6,
- sw_if_index=self.pg0.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=True,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT,
+ af=e.vl_api_address_family_t.ADDRESS_IP6,
+ sw_if_index=self.pg0.sw_if_index,
+ )
# good packets still pass
self.send_and_expect(self.pg0, p_good, self.pg1)
@@ -234,16 +246,17 @@ class TestURPF(VppTestCase):
self.send_and_assert_no_replies(self.pg0, p_spoof_strict)
self.send_and_assert_no_replies(self.pg0, p_spoof_loose)
- self.assert_error_counter_equal("/err/ip6-rx-urpf-strict/uRPF Drop",
- 2 * N_PKTS)
+ self.assert_error_counter_equal("/err/ip6-rx-urpf-strict/uRPF Drop", 2 * N_PKTS)
#
# disable uRPF, all traffic should pass
#
- self.vapi.urpf_update(is_input=True,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF,
- af=e.vl_api_address_family_t.ADDRESS_IP6,
- sw_if_index=self.pg0.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=True,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF,
+ af=e.vl_api_address_family_t.ADDRESS_IP6,
+ sw_if_index=self.pg0.sw_if_index,
+ )
self.send_and_expect(self.pg0, p_good, self.pg1)
self.send_and_expect(self.pg0, p_spoof_strict, self.pg1)
@@ -256,22 +269,25 @@ class TestURPF(VppTestCase):
# for strict they should not be forwarded if they would be
# forwarded thru that interface.
#
- self.vapi.urpf_update(is_input=False,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE,
- af=e.vl_api_address_family_t.ADDRESS_IP6,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=False,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_LOOSE,
+ af=e.vl_api_address_family_t.ADDRESS_IP6,
+ sw_if_index=self.pg1.sw_if_index,
+ )
self.send_and_expect(self.pg0, p_good, self.pg1)
self.send_and_expect(self.pg0, p_spoof_strict, self.pg1)
self.send_and_assert_no_replies(self.pg0, p_spoof_loose)
- self.assert_error_counter_equal("/err/ip6-tx-urpf-loose/uRPF Drop",
- N_PKTS)
+ self.assert_error_counter_equal("/err/ip6-tx-urpf-loose/uRPF Drop", N_PKTS)
- self.vapi.urpf_update(is_input=False,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT,
- af=e.vl_api_address_family_t.ADDRESS_IP6,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=False,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_STRICT,
+ af=e.vl_api_address_family_t.ADDRESS_IP6,
+ sw_if_index=self.pg1.sw_if_index,
+ )
self.send_and_expect(self.pg0, p_good, self.pg1)
# the strict packet, from a peer is allowed, since it does
@@ -279,27 +295,27 @@ class TestURPF(VppTestCase):
self.send_and_expect(self.pg0, p_spoof_strict, self.pg1)
self.send_and_assert_no_replies(self.pg0, p_spoof_loose)
- self.assert_error_counter_equal("/err/ip6-tx-urpf-strict/uRPF Drop",
- N_PKTS)
+ self.assert_error_counter_equal("/err/ip6-tx-urpf-strict/uRPF Drop", N_PKTS)
# change the strict packet so that it would forward through pg1
- p_spoof_strict = (Ether(dst=self.pg0.local_mac,
- src=self.pg0.remote_mac) /
- IPv6(src=self.pg1.remote_ip6,
- dst=self.pg1.remote_ip6) /
- UDP(sport=1236, dport=1236) /
- Raw(b'\xa5' * 100)) * N_PKTS
+ p_spoof_strict = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg1.remote_ip6, dst=self.pg1.remote_ip6)
+ / UDP(sport=1236, dport=1236)
+ / Raw(b"\xa5" * 100)
+ ) * N_PKTS
self.send_and_assert_no_replies(self.pg0, p_spoof_strict)
- self.assert_error_counter_equal("/err/ip6-tx-urpf-strict/uRPF Drop",
- 2 * N_PKTS)
+ self.assert_error_counter_equal("/err/ip6-tx-urpf-strict/uRPF Drop", 2 * N_PKTS)
# cleanup
- self.vapi.urpf_update(is_input=False,
- mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF,
- af=e.vl_api_address_family_t.ADDRESS_IP6,
- sw_if_index=self.pg1.sw_if_index)
+ self.vapi.urpf_update(
+ is_input=False,
+ mode=e.vl_api_urpf_mode_t.URPF_API_MODE_OFF,
+ af=e.vl_api_address_family_t.ADDRESS_IP6,
+ sw_if_index=self.pg1.sw_if_index,
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_util.py b/test/test_util.py
index 3a61d64b28f..52aeeb1691e 100644
--- a/test/test_util.py
+++ b/test/test_util.py
@@ -6,17 +6,17 @@ from framework import VppTestRunner, CPUInterface
from vpp_papi import mac_pton, mac_ntop
-class TestUtil (CPUInterface, unittest.TestCase):
- """ Test framework utility tests """
+class TestUtil(CPUInterface, unittest.TestCase):
+ """Test framework utility tests"""
@classmethod
def is_tagged_run_solo(cls):
- """ if the test case class is timing-sensitive - return true """
+ """if the test case class is timing-sensitive - return true"""
return False
@classmethod
def has_tag(cls, tag):
- """ if the test case has a given tag - return true """
+ """if the test case has a given tag - return true"""
try:
return tag in cls.test_tags
except AttributeError:
@@ -28,13 +28,13 @@ class TestUtil (CPUInterface, unittest.TestCase):
return 0
def test_mac_to_binary(self):
- """ MAC to binary and back """
- mac = 'aa:bb:cc:dd:ee:ff'
+ """MAC to binary and back"""
+ mac = "aa:bb:cc:dd:ee:ff"
b = mac_pton(mac)
mac2 = mac_ntop(b)
self.assertEqual(type(mac), type(mac2))
self.assertEqual(mac2, mac)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_vapi.py b/test/test_vapi.py
index 5a04abe4de7..6817fae6498 100644
--- a/test/test_vapi.py
+++ b/test/test_vapi.py
@@ -9,7 +9,7 @@ from framework import VppTestCase, VppTestRunner, Worker
class VAPITestCase(VppTestCase):
- """ VAPI test """
+ """VAPI test"""
@classmethod
def setUpClass(cls):
@@ -20,10 +20,11 @@ class VAPITestCase(VppTestCase):
super(VAPITestCase, cls).tearDownClass()
def test_vapi_c(self):
- """ run C VAPI tests """
+ """run C VAPI tests"""
executable = f"{config.vpp_build_dir}/vpp/bin/vapi_c_test"
- worker = Worker([executable, "vapi client",
- self.get_api_segment_prefix()], self.logger)
+ worker = Worker(
+ [executable, "vapi client", self.get_api_segment_prefix()], self.logger
+ )
worker.start()
timeout = 60
worker.join(timeout)
@@ -32,23 +33,22 @@ class VAPITestCase(VppTestCase):
if worker.result is None:
try:
error = True
- self.logger.error(
- "Timeout! Worker did not finish in %ss" % timeout)
+ self.logger.error("Timeout! Worker did not finish in %ss" % timeout)
os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM)
worker.join()
except:
self.logger.debug("Couldn't kill worker-spawned process")
raise
if error:
- raise Exception(
- "Timeout! Worker did not finish in %ss" % timeout)
+ raise Exception("Timeout! Worker did not finish in %ss" % timeout)
self.assert_equal(worker.result, 0, "Binary test return code")
def test_vapi_cpp(self):
- """ run C++ VAPI tests """
+ """run C++ VAPI tests"""
executable = f"{config.vpp_build_dir}/vpp/bin/vapi_cpp_test"
- worker = Worker([executable, "vapi client",
- self.get_api_segment_prefix()], self.logger)
+ worker = Worker(
+ [executable, "vapi client", self.get_api_segment_prefix()], self.logger
+ )
worker.start()
timeout = 120
worker.join(timeout)
@@ -57,17 +57,15 @@ class VAPITestCase(VppTestCase):
if worker.result is None:
try:
error = True
- self.logger.error(
- "Timeout! Worker did not finish in %ss" % timeout)
+ self.logger.error("Timeout! Worker did not finish in %ss" % timeout)
os.killpg(os.getpgid(worker.process.pid), signal.SIGTERM)
worker.join()
except:
raise Exception("Couldn't kill worker-spawned process")
if error:
- raise Exception(
- "Timeout! Worker did not finish in %ss" % timeout)
+ raise Exception("Timeout! Worker did not finish in %ss" % timeout)
self.assert_equal(worker.result, 0, "Binary test return code")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_vcl.py b/test/test_vcl.py
index 3875114c3b2..bf139fe0537 100644
--- a/test/test_vcl.py
+++ b/test/test_vcl.py
@@ -10,12 +10,12 @@ from config import config
from framework import VppTestCase, VppTestRunner, Worker
from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath, FibPathProto
-iperf3 = '/usr/bin/iperf3'
+iperf3 = "/usr/bin/iperf3"
def have_app(app):
try:
- subprocess.check_output([app, '-v'])
+ subprocess.check_output([app, "-v"])
except (subprocess.CalledProcessError, OSError):
return False
return True
@@ -25,22 +25,22 @@ _have_iperf3 = have_app(iperf3)
class VCLAppWorker(Worker):
- """ VCL Test Application Worker """
+ """VCL Test Application Worker"""
libname = "libvcl_ldpreload.so"
class LibraryNotFound(Exception):
pass
- def __init__(self, appname, executable_args, logger, env=None,
- role=None, *args, **kwargs):
+ def __init__(
+ self, appname, executable_args, logger, env=None, role=None, *args, **kwargs
+ ):
self.role = role
vcl_ldpreload_glob = f"{config.vpp_install_dir}/**/{self.libname}"
vcl_ldpreload_so = glob.glob(vcl_ldpreload_glob, recursive=True)
if len(vcl_ldpreload_so) < 1:
- raise LibraryNotFound("cannot locate library: {}".format(
- self.libname))
+ raise LibraryNotFound("cannot locate library: {}".format(self.libname))
vcl_ldpreload_so = vcl_ldpreload_so[0]
@@ -48,19 +48,19 @@ class VCLAppWorker(Worker):
env = {}
if "iperf" in appname:
app = appname
- env.update({'LD_PRELOAD': vcl_ldpreload_so})
+ env.update({"LD_PRELOAD": vcl_ldpreload_so})
elif "sock" in appname:
app = f"{config.vpp_build_dir}/vpp/bin/{appname}"
- env.update({'LD_PRELOAD': vcl_ldpreload_so})
+ env.update({"LD_PRELOAD": vcl_ldpreload_so})
else:
app = f"{config.vpp_build_dir}/vpp/bin/{appname}"
self.args = [app] + executable_args
- super(VCLAppWorker, self).__init__(self.args, logger, env,
- *args, **kwargs)
+ super(VCLAppWorker, self).__init__(self.args, logger, env, *args, **kwargs)
class VCLTestCase(VppTestCase):
- """ VCL Test Class """
+ """VCL Test Class"""
+
session_startup = ["poll-main"]
@classmethod
@@ -75,7 +75,7 @@ class VCLTestCase(VppTestCase):
super(VCLTestCase, cls).tearDownClass()
def setUp(self):
- self.vppDebug = 'vpp_debug' in config.vpp_install_dir
+ self.vppDebug = "vpp_debug" in config.vpp_install_dir
self.server_addr = "127.0.0.1"
self.server_port = "22000"
self.server_args = [self.server_port]
@@ -95,26 +95,26 @@ class VCLTestCase(VppTestCase):
def update_vcl_app_env(self, ns_id, ns_secret, attach_sock):
if not ns_id:
- if 'VCL_APP_NAMESPACE_ID' in self.vcl_app_env:
- del self.vcl_app_env['VCL_APP_NAMESPACE_ID']
+ if "VCL_APP_NAMESPACE_ID" in self.vcl_app_env:
+ del self.vcl_app_env["VCL_APP_NAMESPACE_ID"]
else:
- self.vcl_app_env['VCL_APP_NAMESPACE_ID'] = ns_id
+ self.vcl_app_env["VCL_APP_NAMESPACE_ID"] = ns_id
if not ns_secret:
- if 'VCL_APP_NAMESPACE_SECRET' in self.vcl_app_env:
- del self.vcl_app_env['VCL_APP_NAMESPACE_SECRET']
+ if "VCL_APP_NAMESPACE_SECRET" in self.vcl_app_env:
+ del self.vcl_app_env["VCL_APP_NAMESPACE_SECRET"]
else:
- self.vcl_app_env['VCL_APP_NAMESPACE_SECRET'] = ns_secret
+ self.vcl_app_env["VCL_APP_NAMESPACE_SECRET"] = ns_secret
if not attach_sock:
- self.vcl_app_env['VCL_VPP_API_SOCKET'] = self.get_api_sock_path()
- if 'VCL_VPP_SAPI_SOCKET' in self.vcl_app_env:
- del self.vcl_app_env['VCL_VPP_SAPI_SOCKET']
+ self.vcl_app_env["VCL_VPP_API_SOCKET"] = self.get_api_sock_path()
+ if "VCL_VPP_SAPI_SOCKET" in self.vcl_app_env:
+ del self.vcl_app_env["VCL_VPP_SAPI_SOCKET"]
else:
sapi_sock = "%s/app_ns_sockets/%s" % (self.tempdir, attach_sock)
- self.vcl_app_env['VCL_VPP_SAPI_SOCKET'] = sapi_sock
- if 'VCL_VPP_API_SOCKET' in self.vcl_app_env:
- del self.vcl_app_env['VCL_VPP_API_SOCKET']
+ self.vcl_app_env["VCL_VPP_SAPI_SOCKET"] = sapi_sock
+ if "VCL_VPP_API_SOCKET" in self.vcl_app_env:
+ del self.vcl_app_env["VCL_VPP_API_SOCKET"]
def cut_thru_setup(self):
self.vapi.session_enable_disable(is_enable=1)
@@ -123,17 +123,19 @@ class VCLTestCase(VppTestCase):
self.vapi.session_enable_disable(is_enable=0)
def cut_thru_test(self, server_app, server_args, client_app, client_args):
- self.vcl_app_env = {'VCL_APP_SCOPE_LOCAL': "true"}
+ self.vcl_app_env = {"VCL_APP_SCOPE_LOCAL": "true"}
self.update_vcl_app_env("", "", self.sapi_server_sock)
- worker_server = VCLAppWorker(server_app, server_args,
- self.logger, self.vcl_app_env, "server")
+ worker_server = VCLAppWorker(
+ server_app, server_args, self.logger, self.vcl_app_env, "server"
+ )
worker_server.start()
self.sleep(self.pre_test_sleep)
self.update_vcl_app_env("", "", self.sapi_client_sock)
- worker_client = VCLAppWorker(client_app, client_args,
- self.logger, self.vcl_app_env, "client")
+ worker_client = VCLAppWorker(
+ client_app, client_args, self.logger, self.vcl_app_env, "client"
+ )
worker_client.start()
worker_client.join(self.timeout)
try:
@@ -160,20 +162,28 @@ class VCLTestCase(VppTestCase):
table_id += 1
# Configure namespaces
- self.vapi.app_namespace_add_del(namespace_id="1", secret=1234,
- sw_if_index=self.loop0.sw_if_index)
- self.vapi.app_namespace_add_del(namespace_id="2", secret=5678,
- sw_if_index=self.loop1.sw_if_index)
+ self.vapi.app_namespace_add_del(
+ namespace_id="1", secret=1234, sw_if_index=self.loop0.sw_if_index
+ )
+ self.vapi.app_namespace_add_del(
+ namespace_id="2", secret=5678, sw_if_index=self.loop1.sw_if_index
+ )
# Add inter-table routes
- ip_t01 = VppIpRoute(self, self.loop1.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=2)], table_id=1)
- ip_t10 = VppIpRoute(self, self.loop0.local_ip4, 32,
- [VppRoutePath("0.0.0.0",
- 0xffffffff,
- nh_table_id=1)], table_id=2)
+ ip_t01 = VppIpRoute(
+ self,
+ self.loop1.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=2)],
+ table_id=1,
+ )
+ ip_t10 = VppIpRoute(
+ self,
+ self.loop0.local_ip4,
+ 32,
+ [VppRoutePath("0.0.0.0", 0xFFFFFFFF, nh_table_id=1)],
+ table_id=2,
+ )
ip_t01.add_vpp_config()
ip_t10.add_vpp_config()
self.logger.debug(self.vapi.cli("show ip fib"))
@@ -201,20 +211,28 @@ class VCLTestCase(VppTestCase):
table_id += 1
# Configure namespaces
- self.vapi.app_namespace_add_del(namespace_id="1", secret=1234,
- sw_if_index=self.loop0.sw_if_index)
- self.vapi.app_namespace_add_del(namespace_id="2", secret=5678,
- sw_if_index=self.loop1.sw_if_index)
+ self.vapi.app_namespace_add_del(
+ namespace_id="1", secret=1234, sw_if_index=self.loop0.sw_if_index
+ )
+ self.vapi.app_namespace_add_del(
+ namespace_id="2", secret=5678, sw_if_index=self.loop1.sw_if_index
+ )
# Add inter-table routes
- ip_t01 = VppIpRoute(self, self.loop1.local_ip6, 128,
- [VppRoutePath("::0", 0xffffffff,
- nh_table_id=2)],
- table_id=1)
- ip_t10 = VppIpRoute(self, self.loop0.local_ip6, 128,
- [VppRoutePath("::0", 0xffffffff,
- nh_table_id=1)],
- table_id=2)
+ ip_t01 = VppIpRoute(
+ self,
+ self.loop1.local_ip6,
+ 128,
+ [VppRoutePath("::0", 0xFFFFFFFF, nh_table_id=2)],
+ table_id=1,
+ )
+ ip_t10 = VppIpRoute(
+ self,
+ self.loop0.local_ip6,
+ 128,
+ [VppRoutePath("::0", 0xFFFFFFFF, nh_table_id=1)],
+ table_id=2,
+ )
ip_t01.add_vpp_config()
ip_t10.add_vpp_config()
self.logger.debug(self.vapi.cli("show interface addr"))
@@ -229,19 +247,20 @@ class VCLTestCase(VppTestCase):
self.vapi.session_enable_disable(is_enable=0)
@unittest.skipUnless(_have_iperf3, "'%s' not found, Skipping.")
- def thru_host_stack_test(self, server_app, server_args,
- client_app, client_args):
- self.vcl_app_env = {'VCL_APP_SCOPE_GLOBAL': "true"}
+ def thru_host_stack_test(self, server_app, server_args, client_app, client_args):
+ self.vcl_app_env = {"VCL_APP_SCOPE_GLOBAL": "true"}
self.update_vcl_app_env("1", "1234", self.sapi_server_sock)
- worker_server = VCLAppWorker(server_app, server_args,
- self.logger, self.vcl_app_env, "server")
+ worker_server = VCLAppWorker(
+ server_app, server_args, self.logger, self.vcl_app_env, "server"
+ )
worker_server.start()
self.sleep(self.pre_test_sleep)
self.update_vcl_app_env("2", "5678", self.sapi_client_sock)
- worker_client = VCLAppWorker(client_app, client_args,
- self.logger, self.vcl_app_env, "client")
+ worker_client = VCLAppWorker(
+ client_app, client_args, self.logger, self.vcl_app_env, "client"
+ )
worker_client.start()
worker_client.join(self.timeout)
@@ -253,10 +272,11 @@ class VCLTestCase(VppTestCase):
def validateResults(self, worker_client, worker_server, timeout):
if worker_server.process is None:
- raise RuntimeError('worker_server is not running.')
- if os.path.isdir('/proc/{}'.format(worker_server.process.pid)):
- self.logger.info("Killing server worker process (pid %d)" %
- worker_server.process.pid)
+ raise RuntimeError("worker_server is not running.")
+ if os.path.isdir("/proc/{}".format(worker_server.process.pid)):
+ self.logger.info(
+ "Killing server worker process (pid %d)" % worker_server.process.pid
+ )
os.killpg(os.getpgid(worker_server.process.pid), signal.SIGTERM)
worker_server.join()
self.logger.info("Client worker result is `%s'" % worker_client.result)
@@ -265,23 +285,21 @@ class VCLTestCase(VppTestCase):
try:
error = True
self.logger.error(
- "Timeout: %ss! Killing client worker process (pid %d)" %
- (timeout, worker_client.process.pid))
- os.killpg(os.getpgid(worker_client.process.pid),
- signal.SIGKILL)
+ "Timeout: %ss! Killing client worker process (pid %d)"
+ % (timeout, worker_client.process.pid)
+ )
+ os.killpg(os.getpgid(worker_client.process.pid), signal.SIGKILL)
worker_client.join()
except OSError:
- self.logger.debug(
- "Couldn't kill client worker process")
+ self.logger.debug("Couldn't kill client worker process")
raise
if error:
- raise RuntimeError(
- "Timeout! Client worker did not finish in %ss" % timeout)
+ raise RuntimeError("Timeout! Client worker did not finish in %ss" % timeout)
self.assert_equal(worker_client.result, 0, "Binary test return code")
class LDPCutThruTestCase(VCLTestCase):
- """ LDP Cut Thru Tests """
+ """LDP Cut Thru Tests"""
@classmethod
def setUpClass(cls):
@@ -296,21 +314,38 @@ class LDPCutThruTestCase(VCLTestCase):
super(LDPCutThruTestCase, self).setUp()
self.cut_thru_setup()
- self.client_echo_test_args = ["-E", self.echo_phrase, "-X",
- self.server_addr, self.server_port]
+ self.client_echo_test_args = [
+ "-E",
+ self.echo_phrase,
+ "-X",
+ self.server_addr,
+ self.server_port,
+ ]
self.client_iperf3_timeout = 20
self.client_iperf3_args = ["-4", "-t 2", "-c", self.server_addr]
self.server_iperf3_args = ["-4", "-s"]
self.client_uni_dir_nsock_timeout = 20
- self.client_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X",
- "-I", "2",
- self.server_addr,
- self.server_port]
+ self.client_uni_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-U",
+ "-X",
+ "-I",
+ "2",
+ self.server_addr,
+ self.server_port,
+ ]
self.client_bi_dir_nsock_timeout = 20
- self.client_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X",
- "-I", "2",
- self.server_addr,
- self.server_port]
+ self.client_bi_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-B",
+ "-X",
+ "-I",
+ "2",
+ self.server_addr,
+ self.server_port,
+ ]
self.sapi_client_sock = "default"
self.sapi_server_sock = "default"
@@ -324,40 +359,51 @@ class LDPCutThruTestCase(VCLTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_ldp_cut_thru_echo(self):
- """ run LDP cut thru echo test """
+ """run LDP cut thru echo test"""
- self.cut_thru_test("sock_test_server", self.server_args,
- "sock_test_client", self.client_echo_test_args)
+ self.cut_thru_test(
+ "sock_test_server",
+ self.server_args,
+ "sock_test_client",
+ self.client_echo_test_args,
+ )
def test_ldp_cut_thru_iperf3(self):
- """ run LDP cut thru iperf3 test """
+ """run LDP cut thru iperf3 test"""
self.timeout = self.client_iperf3_timeout
- self.cut_thru_test(iperf3, self.server_iperf3_args,
- iperf3, self.client_iperf3_args)
+ self.cut_thru_test(
+ iperf3, self.server_iperf3_args, iperf3, self.client_iperf3_args
+ )
@unittest.skipUnless(config.extended, "part of extended tests")
def test_ldp_cut_thru_uni_dir_nsock(self):
- """ run LDP cut thru uni-directional (multiple sockets) test """
+ """run LDP cut thru uni-directional (multiple sockets) test"""
self.timeout = self.client_uni_dir_nsock_timeout
- self.cut_thru_test("sock_test_server", self.server_args,
- "sock_test_client",
- self.client_uni_dir_nsock_test_args)
+ self.cut_thru_test(
+ "sock_test_server",
+ self.server_args,
+ "sock_test_client",
+ self.client_uni_dir_nsock_test_args,
+ )
@unittest.skipUnless(config.extended, "part of extended tests")
@unittest.skip("sock test apps need to be improved")
def test_ldp_cut_thru_bi_dir_nsock(self):
- """ run LDP cut thru bi-directional (multiple sockets) test """
+ """run LDP cut thru bi-directional (multiple sockets) test"""
self.timeout = self.client_bi_dir_nsock_timeout
- self.cut_thru_test("sock_test_server", self.server_args,
- "sock_test_client",
- self.client_bi_dir_nsock_test_args)
+ self.cut_thru_test(
+ "sock_test_server",
+ self.server_args,
+ "sock_test_client",
+ self.client_bi_dir_nsock_test_args,
+ )
class VCLCutThruTestCase(VCLTestCase):
- """ VCL Cut Thru Tests """
+ """VCL Cut Thru Tests"""
@classmethod
def setUpClass(cls):
@@ -371,19 +417,36 @@ class VCLCutThruTestCase(VCLTestCase):
super(VCLCutThruTestCase, self).setUp()
self.cut_thru_setup()
- self.client_echo_test_args = ["-E", self.echo_phrase, "-X",
- self.server_addr, self.server_port]
+ self.client_echo_test_args = [
+ "-E",
+ self.echo_phrase,
+ "-X",
+ self.server_addr,
+ self.server_port,
+ ]
self.client_uni_dir_nsock_timeout = 20
- self.client_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X",
- "-I", "2",
- self.server_addr,
- self.server_port]
+ self.client_uni_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-U",
+ "-X",
+ "-I",
+ "2",
+ self.server_addr,
+ self.server_port,
+ ]
self.client_bi_dir_nsock_timeout = 20
- self.client_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X",
- "-I", "2",
- self.server_addr,
- self.server_port]
+ self.client_bi_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-B",
+ "-X",
+ "-I",
+ "2",
+ self.server_addr,
+ self.server_port,
+ ]
def tearDown(self):
super(VCLCutThruTestCase, self).tearDown()
@@ -393,30 +456,40 @@ class VCLCutThruTestCase(VCLTestCase):
self.logger.debug(self.vapi.cli("show app mq"))
def test_vcl_cut_thru_echo(self):
- """ run VCL cut thru echo test """
+ """run VCL cut thru echo test"""
- self.cut_thru_test("vcl_test_server", self.server_args,
- "vcl_test_client", self.client_echo_test_args)
+ self.cut_thru_test(
+ "vcl_test_server",
+ self.server_args,
+ "vcl_test_client",
+ self.client_echo_test_args,
+ )
def test_vcl_cut_thru_uni_dir_nsock(self):
- """ run VCL cut thru uni-directional (multiple sockets) test """
+ """run VCL cut thru uni-directional (multiple sockets) test"""
self.timeout = self.client_uni_dir_nsock_timeout
- self.cut_thru_test("vcl_test_server", self.server_args,
- "vcl_test_client",
- self.client_uni_dir_nsock_test_args)
+ self.cut_thru_test(
+ "vcl_test_server",
+ self.server_args,
+ "vcl_test_client",
+ self.client_uni_dir_nsock_test_args,
+ )
def test_vcl_cut_thru_bi_dir_nsock(self):
- """ run VCL cut thru bi-directional (multiple sockets) test """
+ """run VCL cut thru bi-directional (multiple sockets) test"""
self.timeout = self.client_bi_dir_nsock_timeout
- self.cut_thru_test("vcl_test_server", self.server_args,
- "vcl_test_client",
- self.client_bi_dir_nsock_test_args)
+ self.cut_thru_test(
+ "vcl_test_server",
+ self.server_args,
+ "vcl_test_client",
+ self.client_bi_dir_nsock_test_args,
+ )
class VCLThruHostStackEcho(VCLTestCase):
- """ VCL Thru Host Stack Echo """
+ """VCL Thru Host Stack Echo"""
@classmethod
def setUpClass(cls):
@@ -431,25 +504,37 @@ class VCLThruHostStackEcho(VCLTestCase):
self.thru_host_stack_setup()
self.client_bi_dir_nsock_timeout = 20
- self.client_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X",
- "-I", "2",
- self.loop0.local_ip4,
- self.server_port]
- self.client_echo_test_args = ["-E", self.echo_phrase, "-X",
- self.loop0.local_ip4,
- self.server_port]
+ self.client_bi_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-B",
+ "-X",
+ "-I",
+ "2",
+ self.loop0.local_ip4,
+ self.server_port,
+ ]
+ self.client_echo_test_args = [
+ "-E",
+ self.echo_phrase,
+ "-X",
+ self.loop0.local_ip4,
+ self.server_port,
+ ]
def tearDown(self):
self.thru_host_stack_tear_down()
super(VCLThruHostStackEcho, self).tearDown()
def test_vcl_thru_host_stack_echo(self):
- """ run VCL IPv4 thru host stack echo test """
+ """run VCL IPv4 thru host stack echo test"""
- self.thru_host_stack_test("vcl_test_server",
- self.server_args,
- "vcl_test_client",
- self.client_echo_test_args)
+ self.thru_host_stack_test(
+ "vcl_test_server",
+ self.server_args,
+ "vcl_test_client",
+ self.client_echo_test_args,
+ )
def show_commands_at_teardown(self):
self.logger.debug(self.vapi.cli("show app server"))
@@ -458,7 +543,7 @@ class VCLThruHostStackEcho(VCLTestCase):
class VCLThruHostStackTLS(VCLTestCase):
- """ VCL Thru Host Stack TLS """
+ """VCL Thru Host Stack TLS"""
@classmethod
def setUpClass(cls):
@@ -475,19 +560,28 @@ class VCLThruHostStackTLS(VCLTestCase):
self.thru_host_stack_setup()
self.client_uni_dir_tls_timeout = 20
self.server_tls_args = ["-L", self.server_port]
- self.client_uni_dir_tls_test_args = ["-N", "1000", "-U", "-X", "-L",
- self.loop0.local_ip4,
- self.server_port]
+ self.client_uni_dir_tls_test_args = [
+ "-N",
+ "1000",
+ "-U",
+ "-X",
+ "-L",
+ self.loop0.local_ip4,
+ self.server_port,
+ ]
self.sapi_server_sock = "1"
self.sapi_client_sock = "2"
def test_vcl_thru_host_stack_tls_uni_dir(self):
- """ run VCL thru host stack uni-directional TLS test """
+ """run VCL thru host stack uni-directional TLS test"""
self.timeout = self.client_uni_dir_tls_timeout
- self.thru_host_stack_test("vcl_test_server", self.server_tls_args,
- "vcl_test_client",
- self.client_uni_dir_tls_test_args)
+ self.thru_host_stack_test(
+ "vcl_test_server",
+ self.server_tls_args,
+ "vcl_test_client",
+ self.client_uni_dir_tls_test_args,
+ )
def tearDown(self):
self.thru_host_stack_tear_down()
@@ -500,7 +594,7 @@ class VCLThruHostStackTLS(VCLTestCase):
class VCLThruHostStackDTLS(VCLTestCase):
- """ VCL Thru Host Stack DTLS """
+ """VCL Thru Host Stack DTLS"""
@classmethod
def setUpClass(cls):
@@ -516,18 +610,28 @@ class VCLThruHostStackDTLS(VCLTestCase):
self.thru_host_stack_setup()
self.client_uni_dir_dtls_timeout = 20
self.server_dtls_args = ["-p", "dtls", self.server_port]
- self.client_uni_dir_dtls_test_args = ["-N", "1000", "-U", "-X",
- "-p", "dtls", "-T 1400",
- self.loop0.local_ip4,
- self.server_port]
+ self.client_uni_dir_dtls_test_args = [
+ "-N",
+ "1000",
+ "-U",
+ "-X",
+ "-p",
+ "dtls",
+ "-T 1400",
+ self.loop0.local_ip4,
+ self.server_port,
+ ]
def test_vcl_thru_host_stack_dtls_uni_dir(self):
- """ run VCL thru host stack uni-directional DTLS test """
+ """run VCL thru host stack uni-directional DTLS test"""
self.timeout = self.client_uni_dir_dtls_timeout
- self.thru_host_stack_test("vcl_test_server", self.server_dtls_args,
- "vcl_test_client",
- self.client_uni_dir_dtls_test_args)
+ self.thru_host_stack_test(
+ "vcl_test_server",
+ self.server_dtls_args,
+ "vcl_test_client",
+ self.client_uni_dir_dtls_test_args,
+ )
def tearDown(self):
self.thru_host_stack_tear_down()
@@ -540,7 +644,7 @@ class VCLThruHostStackDTLS(VCLTestCase):
class VCLThruHostStackQUIC(VCLTestCase):
- """ VCL Thru Host Stack QUIC """
+ """VCL Thru Host Stack QUIC"""
@classmethod
def setUpClass(cls):
@@ -557,19 +661,28 @@ class VCLThruHostStackQUIC(VCLTestCase):
self.thru_host_stack_setup()
self.client_uni_dir_quic_timeout = 20
self.server_quic_args = ["-p", "quic", self.server_port]
- self.client_uni_dir_quic_test_args = ["-N", "1000", "-U", "-X",
- "-p", "quic",
- self.loop0.local_ip4,
- self.server_port]
+ self.client_uni_dir_quic_test_args = [
+ "-N",
+ "1000",
+ "-U",
+ "-X",
+ "-p",
+ "quic",
+ self.loop0.local_ip4,
+ self.server_port,
+ ]
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vcl_thru_host_stack_quic_uni_dir(self):
- """ run VCL thru host stack uni-directional QUIC test """
+ """run VCL thru host stack uni-directional QUIC test"""
self.timeout = self.client_uni_dir_quic_timeout
- self.thru_host_stack_test("vcl_test_server", self.server_quic_args,
- "vcl_test_client",
- self.client_uni_dir_quic_test_args)
+ self.thru_host_stack_test(
+ "vcl_test_server",
+ self.server_quic_args,
+ "vcl_test_client",
+ self.client_uni_dir_quic_test_args,
+ )
def tearDown(self):
self.thru_host_stack_tear_down()
@@ -582,7 +695,7 @@ class VCLThruHostStackQUIC(VCLTestCase):
class VCLThruHostStackBidirNsock(VCLTestCase):
- """ VCL Thru Host Stack Bidir Nsock """
+ """VCL Thru Host Stack Bidir Nsock"""
@classmethod
def setUpClass(cls):
@@ -597,13 +710,23 @@ class VCLThruHostStackBidirNsock(VCLTestCase):
self.thru_host_stack_setup()
self.client_bi_dir_nsock_timeout = 20
- self.client_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X",
- "-I", "2",
- self.loop0.local_ip4,
- self.server_port]
- self.client_echo_test_args = ["-E", self.echo_phrase, "-X",
- self.loop0.local_ip4,
- self.server_port]
+ self.client_bi_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-B",
+ "-X",
+ "-I",
+ "2",
+ self.loop0.local_ip4,
+ self.server_port,
+ ]
+ self.client_echo_test_args = [
+ "-E",
+ self.echo_phrase,
+ "-X",
+ self.loop0.local_ip4,
+ self.server_port,
+ ]
def tearDown(self):
self.thru_host_stack_tear_down()
@@ -614,16 +737,19 @@ class VCLThruHostStackBidirNsock(VCLTestCase):
self.logger.debug(self.vapi.cli("show app mq"))
def test_vcl_thru_host_stack_bi_dir_nsock(self):
- """ run VCL thru host stack bi-directional (multiple sockets) test """
+ """run VCL thru host stack bi-directional (multiple sockets) test"""
self.timeout = self.client_bi_dir_nsock_timeout
- self.thru_host_stack_test("vcl_test_server", self.server_args,
- "vcl_test_client",
- self.client_bi_dir_nsock_test_args)
+ self.thru_host_stack_test(
+ "vcl_test_server",
+ self.server_args,
+ "vcl_test_client",
+ self.client_bi_dir_nsock_test_args,
+ )
class LDPThruHostStackBidirNsock(VCLTestCase):
- """ LDP Thru Host Stack Bidir Nsock """
+ """LDP Thru Host Stack Bidir Nsock"""
@classmethod
def setUpClass(cls):
@@ -638,14 +764,19 @@ class LDPThruHostStackBidirNsock(VCLTestCase):
self.thru_host_stack_setup()
self.client_bi_dir_nsock_timeout = 20
- self.client_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X",
- # OUCH! Host Stack Bug?
- # Only fails when running
- # 'make test TEST_JOBS=auto'
- # or TEST_JOBS > 1
- # "-I", "2",
- self.loop0.local_ip4,
- self.server_port]
+ self.client_bi_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-B",
+ "-X",
+ # OUCH! Host Stack Bug?
+ # Only fails when running
+ # 'make test TEST_JOBS=auto'
+ # or TEST_JOBS > 1
+ # "-I", "2",
+ self.loop0.local_ip4,
+ self.server_port,
+ ]
def tearDown(self):
self.thru_host_stack_tear_down()
@@ -656,16 +787,19 @@ class LDPThruHostStackBidirNsock(VCLTestCase):
self.logger.debug(self.vapi.cli("show app mq"))
def test_ldp_thru_host_stack_bi_dir_nsock(self):
- """ run LDP thru host stack bi-directional (multiple sockets) test """
+ """run LDP thru host stack bi-directional (multiple sockets) test"""
self.timeout = self.client_bi_dir_nsock_timeout
- self.thru_host_stack_test("sock_test_server", self.server_args,
- "sock_test_client",
- self.client_bi_dir_nsock_test_args)
+ self.thru_host_stack_test(
+ "sock_test_server",
+ self.server_args,
+ "sock_test_client",
+ self.client_bi_dir_nsock_test_args,
+ )
class LDPThruHostStackNsock(VCLTestCase):
- """ LDP Thru Host Stack Nsock """
+ """LDP Thru Host Stack Nsock"""
@classmethod
def setUpClass(cls):
@@ -686,26 +820,35 @@ class LDPThruHostStackNsock(VCLTestCase):
self.client_uni_dir_nsock_timeout = 20
self.numSockets = "5"
- self.client_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X",
- "-I", self.numSockets,
- self.loop0.local_ip4,
- self.server_port]
+ self.client_uni_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-U",
+ "-X",
+ "-I",
+ self.numSockets,
+ self.loop0.local_ip4,
+ self.server_port,
+ ]
def tearDown(self):
self.thru_host_stack_tear_down()
super(LDPThruHostStackNsock, self).tearDown()
def test_ldp_thru_host_stack_uni_dir_nsock(self):
- """ run LDP thru host stack uni-directional (multiple sockets) test """
+ """run LDP thru host stack uni-directional (multiple sockets) test"""
self.timeout = self.client_uni_dir_nsock_timeout
- self.thru_host_stack_test("sock_test_server", self.server_args,
- "sock_test_client",
- self.client_uni_dir_nsock_test_args)
+ self.thru_host_stack_test(
+ "sock_test_server",
+ self.server_args,
+ "sock_test_client",
+ self.client_uni_dir_nsock_test_args,
+ )
class VCLThruHostStackNsock(VCLTestCase):
- """ VCL Thru Host Stack Nsock """
+ """VCL Thru Host Stack Nsock"""
@classmethod
def setUpClass(cls):
@@ -726,26 +869,35 @@ class VCLThruHostStackNsock(VCLTestCase):
self.client_uni_dir_nsock_timeout = 20
self.numSockets = "5"
- self.client_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X",
- "-I", self.numSockets,
- self.loop0.local_ip4,
- self.server_port]
+ self.client_uni_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-U",
+ "-X",
+ "-I",
+ self.numSockets,
+ self.loop0.local_ip4,
+ self.server_port,
+ ]
def tearDown(self):
self.thru_host_stack_tear_down()
super(VCLThruHostStackNsock, self).tearDown()
def test_vcl_thru_host_stack_uni_dir_nsock(self):
- """ run VCL thru host stack uni-directional (multiple sockets) test """
+ """run VCL thru host stack uni-directional (multiple sockets) test"""
self.timeout = self.client_uni_dir_nsock_timeout
- self.thru_host_stack_test("vcl_test_server", self.server_args,
- "vcl_test_client",
- self.client_uni_dir_nsock_test_args)
+ self.thru_host_stack_test(
+ "vcl_test_server",
+ self.server_args,
+ "vcl_test_client",
+ self.client_uni_dir_nsock_test_args,
+ )
class LDPThruHostStackIperf(VCLTestCase):
- """ LDP Thru Host Stack Iperf """
+ """LDP Thru Host Stack Iperf"""
@classmethod
def setUpClass(cls):
@@ -773,15 +925,16 @@ class LDPThruHostStackIperf(VCLTestCase):
@unittest.skipUnless(_have_iperf3, "'%s' not found, Skipping.")
def test_ldp_thru_host_stack_iperf3(self):
- """ run LDP thru host stack iperf3 test """
+ """run LDP thru host stack iperf3 test"""
self.timeout = self.client_iperf3_timeout
- self.thru_host_stack_test(iperf3, self.server_iperf3_args,
- iperf3, self.client_iperf3_args)
+ self.thru_host_stack_test(
+ iperf3, self.server_iperf3_args, iperf3, self.client_iperf3_args
+ )
class LDPThruHostStackIperfUdp(VCLTestCase):
- """ LDP Thru Host Stack Iperf UDP """
+ """LDP Thru Host Stack Iperf UDP"""
@classmethod
def setUpClass(cls):
@@ -796,8 +949,14 @@ class LDPThruHostStackIperfUdp(VCLTestCase):
self.thru_host_stack_setup()
self.client_iperf3_timeout = 20
- self.client_iperf3_args = ["-4", "-t 2", "-u", "-l 1400",
- "-c", self.loop0.local_ip4]
+ self.client_iperf3_args = [
+ "-4",
+ "-t 2",
+ "-u",
+ "-l 1400",
+ "-c",
+ self.loop0.local_ip4,
+ ]
self.server_iperf3_args = ["-4", "-s"]
def tearDown(self):
@@ -810,15 +969,16 @@ class LDPThruHostStackIperfUdp(VCLTestCase):
@unittest.skipUnless(_have_iperf3, "'%s' not found, Skipping.")
def test_ldp_thru_host_stack_iperf3_udp(self):
- """ run LDP thru host stack iperf3 UDP test """
+ """run LDP thru host stack iperf3 UDP test"""
self.timeout = self.client_iperf3_timeout
- self.thru_host_stack_test(iperf3, self.server_iperf3_args,
- iperf3, self.client_iperf3_args)
+ self.thru_host_stack_test(
+ iperf3, self.server_iperf3_args, iperf3, self.client_iperf3_args
+ )
class LDPIpv6CutThruTestCase(VCLTestCase):
- """ LDP IPv6 Cut Thru Tests """
+ """LDP IPv6 Cut Thru Tests"""
@classmethod
def setUpClass(cls):
@@ -839,22 +999,38 @@ class LDPIpv6CutThruTestCase(VCLTestCase):
self.client_iperf3_timeout = 20
self.client_uni_dir_nsock_timeout = 20
self.client_bi_dir_nsock_timeout = 20
- self.client_ipv6_echo_test_args = ["-6", "-E", self.echo_phrase, "-X",
- self.server_ipv6_addr,
- self.server_port]
- self.client_ipv6_iperf3_args = ["-6", "-t 2", "-c",
- self.server_ipv6_addr]
+ self.client_ipv6_echo_test_args = [
+ "-6",
+ "-E",
+ self.echo_phrase,
+ "-X",
+ self.server_ipv6_addr,
+ self.server_port,
+ ]
+ self.client_ipv6_iperf3_args = ["-6", "-t 2", "-c", self.server_ipv6_addr]
self.server_ipv6_iperf3_args = ["-6", "-s"]
- self.client_ipv6_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X",
- "-6",
- "-I", "2",
- self.server_ipv6_addr,
- self.server_port]
- self.client_ipv6_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X",
- "-6",
- "-I", "2",
- self.server_ipv6_addr,
- self.server_port]
+ self.client_ipv6_uni_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-U",
+ "-X",
+ "-6",
+ "-I",
+ "2",
+ self.server_ipv6_addr,
+ self.server_port,
+ ]
+ self.client_ipv6_bi_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-B",
+ "-X",
+ "-6",
+ "-I",
+ "2",
+ self.server_ipv6_addr,
+ self.server_port,
+ ]
def tearDown(self):
super(LDPIpv6CutThruTestCase, self).tearDown()
@@ -862,43 +1038,52 @@ class LDPIpv6CutThruTestCase(VCLTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_ldp_ipv6_cut_thru_echo(self):
- """ run LDP IPv6 cut thru echo test """
+ """run LDP IPv6 cut thru echo test"""
- self.cut_thru_test("sock_test_server",
- self.server_ipv6_args,
- "sock_test_client",
- self.client_ipv6_echo_test_args)
+ self.cut_thru_test(
+ "sock_test_server",
+ self.server_ipv6_args,
+ "sock_test_client",
+ self.client_ipv6_echo_test_args,
+ )
@unittest.skipUnless(_have_iperf3, "'%s' not found, Skipping.")
def test_ldp_ipv6_cut_thru_iperf3(self):
- """ run LDP IPv6 cut thru iperf3 test """
+ """run LDP IPv6 cut thru iperf3 test"""
self.timeout = self.client_iperf3_timeout
- self.cut_thru_test(iperf3, self.server_ipv6_iperf3_args,
- iperf3, self.client_ipv6_iperf3_args)
+ self.cut_thru_test(
+ iperf3, self.server_ipv6_iperf3_args, iperf3, self.client_ipv6_iperf3_args
+ )
@unittest.skipUnless(config.extended, "part of extended tests")
def test_ldp_ipv6_cut_thru_uni_dir_nsock(self):
- """ run LDP IPv6 cut thru uni-directional (multiple sockets) test """
+ """run LDP IPv6 cut thru uni-directional (multiple sockets) test"""
self.timeout = self.client_uni_dir_nsock_timeout
- self.cut_thru_test("sock_test_server", self.server_ipv6_args,
- "sock_test_client",
- self.client_ipv6_uni_dir_nsock_test_args)
+ self.cut_thru_test(
+ "sock_test_server",
+ self.server_ipv6_args,
+ "sock_test_client",
+ self.client_ipv6_uni_dir_nsock_test_args,
+ )
@unittest.skipUnless(config.extended, "part of extended tests")
@unittest.skip("sock test apps need to be improved")
def test_ldp_ipv6_cut_thru_bi_dir_nsock(self):
- """ run LDP IPv6 cut thru bi-directional (multiple sockets) test """
+ """run LDP IPv6 cut thru bi-directional (multiple sockets) test"""
self.timeout = self.client_bi_dir_nsock_timeout
- self.cut_thru_test("sock_test_server", self.server_ipv6_args,
- "sock_test_client",
- self.client_ipv6_bi_dir_nsock_test_args)
+ self.cut_thru_test(
+ "sock_test_server",
+ self.server_ipv6_args,
+ "sock_test_client",
+ self.client_ipv6_bi_dir_nsock_test_args,
+ )
class VCLIpv6CutThruTestCase(VCLTestCase):
- """ VCL IPv6 Cut Thru Tests """
+ """VCL IPv6 Cut Thru Tests"""
@classmethod
def setUpClass(cls):
@@ -918,19 +1103,36 @@ class VCLIpv6CutThruTestCase(VCLTestCase):
self.cut_thru_setup()
self.client_uni_dir_nsock_timeout = 20
self.client_bi_dir_nsock_timeout = 20
- self.client_ipv6_echo_test_args = ["-6", "-E", self.echo_phrase, "-X",
- self.server_ipv6_addr,
- self.server_port]
- self.client_ipv6_uni_dir_nsock_test_args = ["-N", "1000", "-U", "-X",
- "-6",
- "-I", "2",
- self.server_ipv6_addr,
- self.server_port]
- self.client_ipv6_bi_dir_nsock_test_args = ["-N", "1000", "-B", "-X",
- "-6",
- "-I", "2",
- self.server_ipv6_addr,
- self.server_port]
+ self.client_ipv6_echo_test_args = [
+ "-6",
+ "-E",
+ self.echo_phrase,
+ "-X",
+ self.server_ipv6_addr,
+ self.server_port,
+ ]
+ self.client_ipv6_uni_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-U",
+ "-X",
+ "-6",
+ "-I",
+ "2",
+ self.server_ipv6_addr,
+ self.server_port,
+ ]
+ self.client_ipv6_bi_dir_nsock_test_args = [
+ "-N",
+ "1000",
+ "-B",
+ "-X",
+ "-6",
+ "-I",
+ "2",
+ self.server_ipv6_addr,
+ self.server_port,
+ ]
def tearDown(self):
super(VCLIpv6CutThruTestCase, self).tearDown()
@@ -941,34 +1143,42 @@ class VCLIpv6CutThruTestCase(VCLTestCase):
self.logger.debug(self.vapi.cli("show app mq"))
def test_vcl_ipv6_cut_thru_echo(self):
- """ run VCL IPv6 cut thru echo test """
+ """run VCL IPv6 cut thru echo test"""
- self.cut_thru_test("vcl_test_server",
- self.server_ipv6_args,
- "vcl_test_client",
- self.client_ipv6_echo_test_args)
+ self.cut_thru_test(
+ "vcl_test_server",
+ self.server_ipv6_args,
+ "vcl_test_client",
+ self.client_ipv6_echo_test_args,
+ )
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vcl_ipv6_cut_thru_uni_dir_nsock(self):
- """ run VCL IPv6 cut thru uni-directional (multiple sockets) test """
+ """run VCL IPv6 cut thru uni-directional (multiple sockets) test"""
self.timeout = self.client_uni_dir_nsock_timeout
- self.cut_thru_test("vcl_test_server", self.server_ipv6_args,
- "vcl_test_client",
- self.client_ipv6_uni_dir_nsock_test_args)
+ self.cut_thru_test(
+ "vcl_test_server",
+ self.server_ipv6_args,
+ "vcl_test_client",
+ self.client_ipv6_uni_dir_nsock_test_args,
+ )
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vcl_ipv6_cut_thru_bi_dir_nsock(self):
- """ run VCL IPv6 cut thru bi-directional (multiple sockets) test """
+ """run VCL IPv6 cut thru bi-directional (multiple sockets) test"""
self.timeout = self.client_bi_dir_nsock_timeout
- self.cut_thru_test("vcl_test_server", self.server_ipv6_args,
- "vcl_test_client",
- self.client_ipv6_bi_dir_nsock_test_args)
+ self.cut_thru_test(
+ "vcl_test_server",
+ self.server_ipv6_args,
+ "vcl_test_client",
+ self.client_ipv6_bi_dir_nsock_test_args,
+ )
class VCLIpv6ThruHostStackEcho(VCLTestCase):
- """ VCL IPv6 Thru Host Stack Echo """
+ """VCL IPv6 Thru Host Stack Echo"""
@classmethod
def setUpClass(cls):
@@ -982,22 +1192,29 @@ class VCLIpv6ThruHostStackEcho(VCLTestCase):
super(VCLIpv6ThruHostStackEcho, self).setUp()
self.thru_host_stack_ipv6_setup()
- self.client_ipv6_echo_test_args = ["-6", "-E", self.echo_phrase, "-X",
- self.loop0.local_ip6,
- self.server_port]
+ self.client_ipv6_echo_test_args = [
+ "-6",
+ "-E",
+ self.echo_phrase,
+ "-X",
+ self.loop0.local_ip6,
+ self.server_port,
+ ]
def tearDown(self):
self.thru_host_stack_ipv6_tear_down()
super(VCLIpv6ThruHostStackEcho, self).tearDown()
def test_vcl_ipv6_thru_host_stack_echo(self):
- """ run VCL IPv6 thru host stack echo test """
+ """run VCL IPv6 thru host stack echo test"""
- self.thru_host_stack_test("vcl_test_server",
- self.server_ipv6_args,
- "vcl_test_client",
- self.client_ipv6_echo_test_args)
+ self.thru_host_stack_test(
+ "vcl_test_server",
+ self.server_ipv6_args,
+ "vcl_test_client",
+ self.client_ipv6_echo_test_args,
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_vhost.py b/test/test_vhost.py
index aefae90f2f6..01e2151e67f 100644
--- a/test/test_vhost.py
+++ b/test/test_vhost.py
@@ -8,9 +8,8 @@ from vpp_vhost_interface import VppVhostInterface
class TesVhostInterface(VppTestCase):
- """Vhost User Test Case
+ """Vhost User Test Case"""
- """
@classmethod
def setUpClass(cls):
super(TesVhostInterface, cls).setUpClass()
@@ -27,23 +26,23 @@ class TesVhostInterface(VppTestCase):
self.vapi.delete_vhost_user_if(ifc.sw_if_index)
def test_vhost(self):
- """ Vhost User add/delete interface test """
+ """Vhost User add/delete interface test"""
self.logger.info("Vhost User add interfaces")
# create interface 1 (VirtualEthernet0/0/0)
- vhost_if1 = VppVhostInterface(self, sock_filename='/tmp/sock1')
+ vhost_if1 = VppVhostInterface(self, sock_filename="/tmp/sock1")
vhost_if1.add_vpp_config()
vhost_if1.admin_up()
# create interface 2 (VirtualEthernet0/0/1)
- vhost_if2 = VppVhostInterface(self, sock_filename='/tmp/sock2')
+ vhost_if2 = VppVhostInterface(self, sock_filename="/tmp/sock2")
vhost_if2.add_vpp_config()
vhost_if2.admin_up()
# verify both interfaces in the show
ifs = self.vapi.cli("show interface")
- self.assertIn('VirtualEthernet0/0/0', ifs)
- self.assertIn('VirtualEthernet0/0/1', ifs)
+ self.assertIn("VirtualEthernet0/0/0", ifs)
+ self.assertIn("VirtualEthernet0/0/1", ifs)
# verify they are in the dump also
if_dump = self.vapi.sw_interface_vhost_user_dump()
@@ -58,10 +57,10 @@ class TesVhostInterface(VppTestCase):
ifs = self.vapi.cli("show interface")
# verify VirtualEthernet0/0/0 still in the show
- self.assertIn('VirtualEthernet0/0/0', ifs)
+ self.assertIn("VirtualEthernet0/0/0", ifs)
# verify VirtualEthernet0/0/1 not in the show
- self.assertNotIn('VirtualEthernet0/0/1', ifs)
+ self.assertNotIn("VirtualEthernet0/0/1", ifs)
# verify VirtualEthernet0/0/1 is not in the dump
if_dump = self.vapi.sw_interface_vhost_user_dump()
@@ -78,14 +77,14 @@ class TesVhostInterface(VppTestCase):
# verify VirtualEthernet0/0/0 not in the show
ifs = self.vapi.cli("show interface")
- self.assertNotIn('VirtualEthernet0/0/0', ifs)
+ self.assertNotIn("VirtualEthernet0/0/0", ifs)
# verify VirtualEthernet0/0/0 is not in the dump
if_dump = self.vapi.sw_interface_vhost_user_dump()
self.assertFalse(vhost_if1.is_interface_config_in_dump(if_dump))
def test_vhost_interface_state(self):
- """ Vhost User interface states and events test """
+ """Vhost User interface states and events test"""
self.vapi.want_interface_events()
@@ -93,7 +92,7 @@ class TesVhostInterface(VppTestCase):
# (like delete interface events from other tests)
self.vapi.collect_events()
- vhost_if = VppVhostInterface(self, sock_filename='/tmp/sock1')
+ vhost_if = VppVhostInterface(self, sock_filename="/tmp/sock1")
# create vhost interface
vhost_if.add_vpp_config()
@@ -111,8 +110,7 @@ class TesVhostInterface(VppTestCase):
# delete vhost interface
vhost_if.remove_vpp_config()
event = self.vapi.wait_for_event(timeout=1)
- self.assert_equal(event.sw_if_index, vhost_if.sw_if_index,
- "sw_if_index")
+ self.assert_equal(event.sw_if_index, vhost_if.sw_if_index, "sw_if_index")
self.assert_equal(event.deleted, 1, "deleted flag")
# verify there are no more events
@@ -120,32 +118,28 @@ class TesVhostInterface(VppTestCase):
self.assert_equal(len(events), 0, "number of events")
def test_vhost_interface_custom_mac_addr(self):
- """ Vhost User interface custom mac address test """
+ """Vhost User interface custom mac address test"""
mac_addr = "aa:bb:cc:dd:ee:ff"
- vhost_if = VppVhostInterface(self,
- sock_filename='/tmp/sock1',
- use_custom_mac=1,
- mac_address=mac_addr)
+ vhost_if = VppVhostInterface(
+ self, sock_filename="/tmp/sock1", use_custom_mac=1, mac_address=mac_addr
+ )
# create vhost interface
vhost_if.add_vpp_config()
self.sleep(0.1)
# verify mac in the dump
- if_dump_list = self.vapi.sw_interface_dump(
- sw_if_index=vhost_if.sw_if_index
- )
+ if_dump_list = self.vapi.sw_interface_dump(sw_if_index=vhost_if.sw_if_index)
self.assert_equal(len(if_dump_list), 1, "if dump length")
[if_dump] = if_dump_list
- self.assert_equal(
- if_dump.l2_address.mac_string, mac_addr, "MAC Address"
- )
+ self.assert_equal(if_dump.l2_address.mac_string, mac_addr, "MAC Address")
# delete VirtualEthernet
self.logger.info("Deleting VirtualEthernet")
vhost_if.remove_vpp_config()
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_vlib.py b/test/test_vlib.py
index 242acab4594..76a55e65a03 100644
--- a/test/test_vlib.py
+++ b/test/test_vlib.py
@@ -11,7 +11,8 @@ from vpp_ip_route import VppIpTable, VppIpRoute, VppRoutePath
@unittest.skipUnless(config.gcov, "part of code coverage tests")
class TestVlib(VppTestCase):
- """ Vlib Unit Test Cases """
+ """Vlib Unit Test Cases"""
+
vpp_worker_count = 1
@classmethod
@@ -29,171 +30,174 @@ class TestVlib(VppTestCase):
super(TestVlib, self).tearDown()
def test_vlib_main_unittest(self):
- """ Vlib main.c Code Coverage Test """
-
- cmds = ["loopback create",
- "packet-generator new {\n"
- " name vlib\n"
- " limit 15\n"
- " size 128-128\n"
- " interface loop0\n"
- " node ethernet-input\n"
- " data {\n"
- " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n"
- " ICMP: db00::1 -> db00::2\n"
- " incrementing 30\n"
- " }\n"
- "}\n",
- "event-logger trace dispatch",
- "event-logger stop",
- "event-logger clear",
- "event-logger resize 102400",
- "event-logger restart",
- "pcap dispatch trace on max 100 buffer-trace pg-input 15",
- "pa en",
- "show event-log 100 all",
- "event-log save",
- "event-log save foo",
- "pcap dispatch trace",
- "pcap dispatch trace status",
- "pcap dispatch trace off",
- "show vlib frame-allocation",
- ]
+ """Vlib main.c Code Coverage Test"""
+
+ cmds = [
+ "loopback create",
+ "packet-generator new {\n"
+ " name vlib\n"
+ " limit 15\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " node ethernet-input\n"
+ " data {\n"
+ " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n"
+ " ICMP: db00::1 -> db00::2\n"
+ " incrementing 30\n"
+ " }\n"
+ "}\n",
+ "event-logger trace dispatch",
+ "event-logger stop",
+ "event-logger clear",
+ "event-logger resize 102400",
+ "event-logger restart",
+ "pcap dispatch trace on max 100 buffer-trace pg-input 15",
+ "pa en",
+ "show event-log 100 all",
+ "event-log save",
+ "event-log save foo",
+ "pcap dispatch trace",
+ "pcap dispatch trace status",
+ "pcap dispatch trace off",
+ "show vlib frame-allocation",
+ ]
for cmd in cmds:
r = self.vapi.cli_return_response(cmd)
if r.retval != 0:
- if hasattr(r, 'reply'):
+ if hasattr(r, "reply"):
self.logger.info(cmd + " FAIL reply " + r.reply)
else:
self.logger.info(cmd + " FAIL retval " + str(r.retval))
def test_vlib_node_cli_unittest(self):
- """ Vlib node_cli.c Code Coverage Test """
-
- cmds = ["loopback create",
- "packet-generator new {\n"
- " name vlib\n"
- " limit 15\n"
- " size 128-128\n"
- " interface loop0\n"
- " node ethernet-input\n"
- " data {\n"
- " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n"
- " ICMP: db00::1 -> db00::2\n"
- " incrementing 30\n"
- " }\n"
- "}\n",
- "show vlib graph",
- "show vlib graph ethernet-input",
- "show vlib graphviz",
- "show vlib graphviz graphviz.dot",
- "pa en",
- "show runtime ethernet-input",
- "show runtime brief verbose max summary",
- "clear runtime",
- "show node index 1",
- "show node ethernet-input",
- "show node pg-input",
- "set node function",
- "set node function no-such-node",
- "set node function cdp-input default",
- "set node function ethernet-input default",
- "set node function ethernet-input bozo",
- "set node function ethernet-input",
- "show \t",
- ]
+ """Vlib node_cli.c Code Coverage Test"""
+
+ cmds = [
+ "loopback create",
+ "packet-generator new {\n"
+ " name vlib\n"
+ " limit 15\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " node ethernet-input\n"
+ " data {\n"
+ " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n"
+ " ICMP: db00::1 -> db00::2\n"
+ " incrementing 30\n"
+ " }\n"
+ "}\n",
+ "show vlib graph",
+ "show vlib graph ethernet-input",
+ "show vlib graphviz",
+ "show vlib graphviz graphviz.dot",
+ "pa en",
+ "show runtime ethernet-input",
+ "show runtime brief verbose max summary",
+ "clear runtime",
+ "show node index 1",
+ "show node ethernet-input",
+ "show node pg-input",
+ "set node function",
+ "set node function no-such-node",
+ "set node function cdp-input default",
+ "set node function ethernet-input default",
+ "set node function ethernet-input bozo",
+ "set node function ethernet-input",
+ "show \t",
+ ]
for cmd in cmds:
r = self.vapi.cli_return_response(cmd)
if r.retval != 0:
- if hasattr(r, 'reply'):
+ if hasattr(r, "reply"):
self.logger.info(cmd + " FAIL reply " + r.reply)
else:
self.logger.info(cmd + " FAIL retval " + str(r.retval))
def test_vlib_buffer_c_unittest(self):
- """ Vlib buffer.c Code Coverage Test """
-
- cmds = ["loopback create",
- "packet-generator new {\n"
- " name vlib\n"
- " limit 15\n"
- " size 128-128\n"
- " interface loop0\n"
- " node ethernet-input\n"
- " data {\n"
- " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n"
- " ICMP: db00::1 -> db00::2\n"
- " incrementing 30\n"
- " }\n"
- "}\n",
- "event-logger trace",
- "event-logger trace enable",
- "event-logger trace api cli barrier",
- "pa en",
- "show interface bogus",
- "event-logger trace disable api cli barrier",
- "event-logger trace circuit-node ethernet-input",
- "event-logger trace circuit-node ethernet-input disable",
- "clear interfaces",
- "test vlib",
- "test vlib2",
- "show memory api-segment stats-segment main-heap verbose",
- "leak-check { show memory }",
- "show cpu",
- "memory-trace main-heap",
- "memory-trace main-heap api-segment stats-segment",
- "leak-check { show version }",
- "show version ?",
- "comment { show version }",
- "uncomment { show version }",
- "show memory main-heap",
- "show memory bogus",
- "choices",
- "test heap-validate",
- "memory-trace main-heap disable",
- "show buffers",
- "show eve",
- "show help",
- "show ip ",
- ]
+ """Vlib buffer.c Code Coverage Test"""
+
+ cmds = [
+ "loopback create",
+ "packet-generator new {\n"
+ " name vlib\n"
+ " limit 15\n"
+ " size 128-128\n"
+ " interface loop0\n"
+ " node ethernet-input\n"
+ " data {\n"
+ " IP6: 00:d0:2d:5e:86:85 -> 00:0d:ea:d0:00:00\n"
+ " ICMP: db00::1 -> db00::2\n"
+ " incrementing 30\n"
+ " }\n"
+ "}\n",
+ "event-logger trace",
+ "event-logger trace enable",
+ "event-logger trace api cli barrier",
+ "pa en",
+ "show interface bogus",
+ "event-logger trace disable api cli barrier",
+ "event-logger trace circuit-node ethernet-input",
+ "event-logger trace circuit-node ethernet-input disable",
+ "clear interfaces",
+ "test vlib",
+ "test vlib2",
+ "show memory api-segment stats-segment main-heap verbose",
+ "leak-check { show memory }",
+ "show cpu",
+ "memory-trace main-heap",
+ "memory-trace main-heap api-segment stats-segment",
+ "leak-check { show version }",
+ "show version ?",
+ "comment { show version }",
+ "uncomment { show version }",
+ "show memory main-heap",
+ "show memory bogus",
+ "choices",
+ "test heap-validate",
+ "memory-trace main-heap disable",
+ "show buffers",
+ "show eve",
+ "show help",
+ "show ip ",
+ ]
for cmd in cmds:
r = self.vapi.cli_return_response(cmd)
if r.retval != 0:
- if hasattr(r, 'reply'):
+ if hasattr(r, "reply"):
self.logger.info(cmd + " FAIL reply " + r.reply)
else:
self.logger.info(cmd + " FAIL retval " + str(r.retval))
def test_vlib_format_unittest(self):
- """ Vlib format.c Code Coverage Test """
+ """Vlib format.c Code Coverage Test"""
- cmds = ["loopback create",
- "classify filter pcap mask l2 proto match l2 proto 0x86dd",
- "classify filter pcap del",
- "test format-vlib",
- ]
+ cmds = [
+ "loopback create",
+ "classify filter pcap mask l2 proto match l2 proto 0x86dd",
+ "classify filter pcap del",
+ "test format-vlib",
+ ]
for cmd in cmds:
r = self.vapi.cli_return_response(cmd)
if r.retval != 0:
- if hasattr(r, 'reply'):
+ if hasattr(r, "reply"):
self.logger.info(cmd + " FAIL reply " + r.reply)
else:
self.logger.info(cmd + " FAIL retval " + str(r.retval))
def test_vlib_main_unittest(self):
- """ Private Binary API Segment Test (takes 70 seconds) """
+ """Private Binary API Segment Test (takes 70 seconds)"""
- vat_path = config.vpp + '_api_test'
- vat = pexpect.spawn(vat_path, ['socket-name',
- self.get_api_sock_path()])
+ vat_path = config.vpp + "_api_test"
+ vat = pexpect.spawn(vat_path, ["socket-name", self.get_api_sock_path()])
vat.expect("vat# ", timeout=10)
- vat.sendline('sock_init_shm')
+ vat.sendline("sock_init_shm")
vat.expect("vat# ", timeout=10)
- vat.sendline('sh api cli')
+ vat.sendline("sh api cli")
vat.kill(signal.SIGKILL)
vat.wait()
self.logger.info("vat terminated, 70 second wait for the Reaper")
@@ -201,18 +205,20 @@ class TestVlib(VppTestCase):
self.logger.info("Reaper should be complete...")
def test_pool(self):
- """ Fixed-size Pool Test """
+ """Fixed-size Pool Test"""
- cmds = ["test pool",
- ]
+ cmds = [
+ "test pool",
+ ]
for cmd in cmds:
r = self.vapi.cli_return_response(cmd)
if r.retval != 0:
- if hasattr(r, 'reply'):
+ if hasattr(r, "reply"):
self.logger.info(cmd + " FAIL reply " + r.reply)
else:
self.logger.info(cmd + " FAIL retval " + str(r.retval))
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_vpe_api.py b/test/test_vpe_api.py
index 54f7e41151b..d7d4cc72ff7 100644
--- a/test/test_vpe_api.py
+++ b/test/test_vpe_api.py
@@ -23,33 +23,33 @@ class TestVpeApi(VppTestCase):
"""TestVpeApi"""
def test_log_dump_default(self):
- rv = self.vapi.cli('test log notice fib entry this is a test')
+ rv = self.vapi.cli("test log notice fib entry this is a test")
rv = self.vapi.log_dump()
if enable_print:
- print('\n'.join([str(v) for v in rv]))
+ print("\n".join([str(v) for v in rv]))
self.assertTrue(rv)
def test_log_dump_timestamp_0(self):
- rv = self.vapi.cli('test log notice fib entry this is a test')
+ rv = self.vapi.cli("test log notice fib entry this is a test")
rv = self.vapi.log_dump(start_timestamp=0.0)
if enable_print:
- print('\n'.join([str(v) for v in rv]))
+ print("\n".join([str(v) for v in rv]))
self.assertTrue(rv)
def test_log_dump_timestamp_future(self):
- rv = self.vapi.cli('test log debug fib entry test')
+ rv = self.vapi.cli("test log debug fib entry test")
rv = self.vapi.log_dump(start_timestamp=time.time() + 60.0)
if enable_print:
- print('\n'.join([str(v) for v in rv]))
+ print("\n".join([str(v) for v in rv]))
self.assertFalse(rv)
def test_show_vpe_system_time(self):
local_start_time = datetime.datetime.now()
rv = self.vapi.show_vpe_system_time()
- self.assertTrue(rv.vpe_system_time > local_start_time -
- datetime.timedelta(hours=1.0),
- 'system times differ by more than an hour.')
+ self.assertTrue(
+ rv.vpe_system_time > local_start_time - datetime.timedelta(hours=1.0),
+ "system times differ by more than an hour.",
+ )
if enable_print:
- print('\n'.join([str(v) for v in rv]))
- print('%r %s' % (rv.vpe_system_time,
- rv.vpe_system_time))
+ print("\n".join([str(v) for v in rv]))
+ print("%r %s" % (rv.vpe_system_time, rv.vpe_system_time))
diff --git a/test/test_vppinfra.py b/test/test_vppinfra.py
index 36cd55b3550..3a8f8e96fee 100644
--- a/test/test_vppinfra.py
+++ b/test/test_vppinfra.py
@@ -6,7 +6,8 @@ from framework import VppTestCase, VppTestRunner
class TestVppinfra(VppTestCase):
- """ Vppinfra Unit Test Cases """
+ """Vppinfra Unit Test Cases"""
+
vpp_worker_count = 1
@classmethod
@@ -24,16 +25,17 @@ class TestVppinfra(VppTestCase):
super(TestVppinfra, self).tearDown()
def test_bitmap_unittest(self):
- """ Bitmap Code Coverage Test """
+ """Bitmap Code Coverage Test"""
cmds = ["test bitmap"]
for cmd in cmds:
r = self.vapi.cli_return_response(cmd)
if r.retval != 0:
- if hasattr(r, 'reply'):
+ if hasattr(r, "reply"):
self.logger.info(cmd + " FAIL reply " + r.reply)
else:
self.logger.info(cmd + " FAIL retval " + str(r.retval))
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_vrrp.py b/test/test_vrrp.py
index 6a62a88c2a1..9319b0fa6da 100644
--- a/test/test_vrrp.py
+++ b/test/test_vrrp.py
@@ -17,9 +17,18 @@ from vpp_papi import VppEnum
from scapy.packet import raw
from scapy.layers.l2 import Ether, ARP
from scapy.layers.inet import IP, ICMP, icmptypes
-from scapy.layers.inet6 import IPv6, ipv6nh, IPv6ExtHdrHopByHop, \
- ICMPv6MLReport2, ICMPv6ND_NA, ICMPv6ND_NS, ICMPv6NDOptDstLLAddr, \
- ICMPv6NDOptSrcLLAddr, ICMPv6EchoRequest, ICMPv6EchoReply
+from scapy.layers.inet6 import (
+ IPv6,
+ ipv6nh,
+ IPv6ExtHdrHopByHop,
+ ICMPv6MLReport2,
+ ICMPv6ND_NA,
+ ICMPv6ND_NS,
+ ICMPv6NDOptDstLLAddr,
+ ICMPv6NDOptSrcLLAddr,
+ ICMPv6EchoRequest,
+ ICMPv6EchoReply,
+)
from scapy.contrib.igmpv3 import IGMPv3, IGMPv3mr, IGMPv3gr
from scapy.layers.vrrp import IPPROTO_VRRP, VRRPv3
from scapy.utils6 import in6_getnsma, in6_getnsmac
@@ -37,11 +46,11 @@ VRRP_VR_STATE_BACKUP = 1
VRRP_VR_STATE_MASTER = 2
VRRP_VR_STATE_INTF_DOWN = 3
-VRRP_INDEX_INVALID = 0xffffffff
+VRRP_INDEX_INVALID = 0xFFFFFFFF
def is_non_arp(p):
- """ Want to filter out advertisements, igmp, etc"""
+ """Want to filter out advertisements, igmp, etc"""
if p.haslayer(ARP):
return False
@@ -49,7 +58,7 @@ def is_non_arp(p):
def is_not_adv(p):
- """ Filter out everything but advertisements. E.g. multicast RD/ND """
+ """Filter out everything but advertisements. E.g. multicast RD/ND"""
if p.haslayer(VRRPv3):
return False
@@ -57,7 +66,7 @@ def is_not_adv(p):
def is_not_echo_reply(p):
- """ filter out advertisements and other while waiting for echo reply """
+ """filter out advertisements and other while waiting for echo reply"""
if p.haslayer(IP) and p.haslayer(ICMP):
if icmptypes[p[ICMP].type] == "echo-reply":
return False
@@ -68,15 +77,16 @@ def is_not_echo_reply(p):
class VppVRRPVirtualRouter(VppObject):
-
- def __init__(self,
- test,
- intf,
- vr_id,
- prio=100,
- intvl=100,
- flags=VRRP_VR_FLAG_PREEMPT,
- vips=None):
+ def __init__(
+ self,
+ test,
+ intf,
+ vr_id,
+ prio=100,
+ intvl=100,
+ flags=VRRP_VR_FLAG_PREEMPT,
+ vips=None,
+ ):
self._test = test
self._intf = intf
self._sw_if_index = self._intf.sw_if_index
@@ -84,40 +94,44 @@ class VppVRRPVirtualRouter(VppObject):
self._prio = prio
self._intvl = intvl
self._flags = flags
- if (flags & VRRP_VR_FLAG_IPV6):
+ if flags & VRRP_VR_FLAG_IPV6:
self._is_ipv6 = 1
self._adv_dest_mac = "33:33:00:00:00:12"
self._virtual_mac = "00:00:5e:00:02:%02x" % vr_id
self._adv_dest_ip = "ff02::12"
- self._vips = ([intf.local_ip6] if vips is None else vips)
+ self._vips = [intf.local_ip6] if vips is None else vips
else:
self._is_ipv6 = 0
self._adv_dest_mac = "01:00:5e:00:00:12"
self._virtual_mac = "00:00:5e:00:01:%02x" % vr_id
self._adv_dest_ip = "224.0.0.18"
- self._vips = ([intf.local_ip4] if vips is None else vips)
+ self._vips = [intf.local_ip4] if vips is None else vips
self._tracked_ifs = []
self._vrrp_index = VRRP_INDEX_INVALID
def add_vpp_config(self):
- self._test.vapi.vrrp_vr_add_del(is_add=1,
- sw_if_index=self._intf.sw_if_index,
- vr_id=self._vr_id,
- priority=self._prio,
- interval=self._intvl,
- flags=self._flags,
- n_addrs=len(self._vips),
- addrs=self._vips)
+ self._test.vapi.vrrp_vr_add_del(
+ is_add=1,
+ sw_if_index=self._intf.sw_if_index,
+ vr_id=self._vr_id,
+ priority=self._prio,
+ interval=self._intvl,
+ flags=self._flags,
+ n_addrs=len(self._vips),
+ addrs=self._vips,
+ )
def update_vpp_config(self):
- r = self._test.vapi.vrrp_vr_update(vrrp_index=self._vrrp_index,
- sw_if_index=self._intf.sw_if_index,
- vr_id=self._vr_id,
- priority=self._prio,
- interval=self._intvl,
- flags=self._flags,
- n_addrs=len(self._vips),
- addrs=self._vips)
+ r = self._test.vapi.vrrp_vr_update(
+ vrrp_index=self._vrrp_index,
+ sw_if_index=self._intf.sw_if_index,
+ vr_id=self._vr_id,
+ priority=self._prio,
+ interval=self._intvl,
+ flags=self._flags,
+ n_addrs=len(self._vips),
+ addrs=self._vips,
+ )
self._vrrp_index = r.vrrp_index
def delete_vpp_config(self):
@@ -129,7 +143,7 @@ class VppVRRPVirtualRouter(VppObject):
if vr.config.vr_id != self._vr_id:
continue
- is_ipv6 = (1 if (vr.config.flags & VRRP_VR_FLAG_IPV6) else 0)
+ is_ipv6 = 1 if (vr.config.flags & VRRP_VR_FLAG_IPV6) else 0
if is_ipv6 != self._is_ipv6:
continue
@@ -138,41 +152,45 @@ class VppVRRPVirtualRouter(VppObject):
return None
def remove_vpp_config(self):
- self._test.vapi.vrrp_vr_add_del(is_add=0,
- sw_if_index=self._intf.sw_if_index,
- vr_id=self._vr_id,
- priority=self._prio,
- interval=self._intvl,
- flags=self._flags,
- n_addrs=len(self._vips),
- addrs=self._vips)
+ self._test.vapi.vrrp_vr_add_del(
+ is_add=0,
+ sw_if_index=self._intf.sw_if_index,
+ vr_id=self._vr_id,
+ priority=self._prio,
+ interval=self._intvl,
+ flags=self._flags,
+ n_addrs=len(self._vips),
+ addrs=self._vips,
+ )
def start_stop(self, is_start):
- self._test.vapi.vrrp_vr_start_stop(is_start=is_start,
- sw_if_index=self._intf.sw_if_index,
- vr_id=self._vr_id,
- is_ipv6=self._is_ipv6)
- self._start_time = (time.time() if is_start else None)
+ self._test.vapi.vrrp_vr_start_stop(
+ is_start=is_start,
+ sw_if_index=self._intf.sw_if_index,
+ vr_id=self._vr_id,
+ is_ipv6=self._is_ipv6,
+ )
+ self._start_time = time.time() if is_start else None
def add_del_tracked_interface(self, is_add, sw_if_index, prio):
args = {
- 'sw_if_index': self._intf.sw_if_index,
- 'is_ipv6': self._is_ipv6,
- 'vr_id': self._vr_id,
- 'is_add': is_add,
- 'n_ifs': 1,
- 'ifs': [{'sw_if_index': sw_if_index, 'priority': prio}]
+ "sw_if_index": self._intf.sw_if_index,
+ "is_ipv6": self._is_ipv6,
+ "vr_id": self._vr_id,
+ "is_add": is_add,
+ "n_ifs": 1,
+ "ifs": [{"sw_if_index": sw_if_index, "priority": prio}],
}
self._test.vapi.vrrp_vr_track_if_add_del(**args)
- self._tracked_ifs.append(args['ifs'][0])
+ self._tracked_ifs.append(args["ifs"][0])
def set_unicast_peers(self, addrs):
args = {
- 'sw_if_index': self._intf.sw_if_index,
- 'is_ipv6': self._is_ipv6,
- 'vr_id': self._vr_id,
- 'n_addrs': len(addrs),
- 'addrs': addrs
+ "sw_if_index": self._intf.sw_if_index,
+ "is_ipv6": self._is_ipv6,
+ "vr_id": self._vr_id,
+ "n_addrs": len(addrs),
+ "addrs": addrs,
}
self._test.vapi.vrrp_vr_set_peers(**args)
self._unicast_peers = addrs
@@ -210,21 +228,22 @@ class VppVRRPVirtualRouter(VppObject):
def master_down_seconds(self):
vr_details = self.query_vpp_config()
- return (vr_details.runtime.master_down_int * 0.01)
+ return vr_details.runtime.master_down_int * 0.01
def vrrp_adv_packet(self, prio=None, src_ip=None):
dst_ip = self._adv_dest_ip
if prio is None:
prio = self._prio
eth = Ether(dst=self._adv_dest_mac, src=self._virtual_mac)
- vrrp = VRRPv3(vrid=self._vr_id, priority=prio,
- ipcount=len(self._vips), adv=self._intvl)
+ vrrp = VRRPv3(
+ vrid=self._vr_id, priority=prio, ipcount=len(self._vips), adv=self._intvl
+ )
if self._is_ipv6:
- src_ip = (self._intf.local_ip6_ll if src_ip is None else src_ip)
+ src_ip = self._intf.local_ip6_ll if src_ip is None else src_ip
ip = IPv6(src=src_ip, dst=dst_ip, nh=IPPROTO_VRRP, hlim=255)
vrrp.addrlist = self._vips
else:
- src_ip = (self._intf.local_ip4 if src_ip is None else src_ip)
+ src_ip = self._intf.local_ip4 if src_ip is None else src_ip
ip = IP(src=src_ip, dst=dst_ip, proto=IPPROTO_VRRP, ttl=255, id=0)
vrrp.addrlist = self._vips
@@ -234,7 +253,7 @@ class VppVRRPVirtualRouter(VppObject):
class TestVRRP4(VppTestCase):
- """ IPv4 VRRP Test Case """
+ """IPv4 VRRP Test Case"""
@classmethod
def setUpClass(cls):
@@ -284,8 +303,7 @@ class TestVRRP4(VppTestCase):
self.assertEqual(ip.proto, 2)
igmp = pkt[IGMPv3]
- self.assertEqual(IGMPv3.igmpv3types[igmp.type],
- "Version 3 Membership Report")
+ self.assertEqual(IGMPv3.igmpv3types[igmp.type], "Version 3 Membership Report")
igmpmr = pkt[IGMPv3mr]
self.assertEqual(igmpmr.numgrp, 1)
@@ -330,15 +348,15 @@ class TestVRRP4(VppTestCase):
# become master and start advertising immediately.
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp4_master_adv(self):
- """ IPv4 Master VR advertises """
+ """IPv4 Master VR advertises"""
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
prio = 255
intvl = self._default_adv
- vr = VppVRRPVirtualRouter(self, self.pg0, 100,
- prio=prio, intvl=intvl,
- flags=self._default_flags)
+ vr = VppVRRPVirtualRouter(
+ self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags
+ )
vr.add_vpp_config()
vr.start_stop(is_start=1)
@@ -362,25 +380,30 @@ class TestVRRP4(VppTestCase):
# of parameters to test that too
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp4_master_adv_update(self):
- """ IPv4 Master VR adv + Update to Backup """
+ """IPv4 Master VR adv + Update to Backup"""
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
prio = 255
intvl = self._default_adv
- vr = VppVRRPVirtualRouter(self, self.pg0, 100,
- prio=prio, intvl=intvl,
- flags=self._default_flags)
+ vr = VppVRRPVirtualRouter(
+ self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags
+ )
vr.update_vpp_config()
vr.start_stop(is_start=1)
self.logger.info(self.vapi.cli("show vrrp vr"))
# Update VR with lower prio and larger interval
# we need to keep old VR for the adv checks
- upd_vr = VppVRRPVirtualRouter(self, self.pg0, 100,
- prio=100, intvl=2*intvl,
- flags=self._default_flags,
- vips=[self.pg0.remote_ip4])
+ upd_vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ 100,
+ prio=100,
+ intvl=2 * intvl,
+ flags=self._default_flags,
+ vips=[self.pg0.remote_ip4],
+ )
upd_vr._vrrp_index = vr._vrrp_index
upd_vr.update_vpp_config()
start_time = time.time()
@@ -403,7 +426,7 @@ class TestVRRP4(VppTestCase):
src_ip = self.pg0.remote_ip4
pkts = [upd_vr.vrrp_adv_packet(prio=110, src_ip=src_ip)]
while time.time() < end_time:
- self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl*0.01)
+ self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl * 0.01)
self.logger.info(self.vapi.cli("show trace"))
upd_vr.start_stop(is_start=0)
@@ -413,7 +436,7 @@ class TestVRRP4(VppTestCase):
# long as it receives higher priority advertisements
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp4_backup_noadv(self):
- """ IPv4 Backup VR does not advertise """
+ """IPv4 Backup VR does not advertise"""
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -421,10 +444,15 @@ class TestVRRP4(VppTestCase):
prio = 100
intvl = self._default_adv
intvl_s = intvl * 0.01
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[self.pg0.remote_ip4])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[self.pg0.remote_ip4],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -440,7 +468,7 @@ class TestVRRP4(VppTestCase):
# send higher prio advertisements, should not receive any
src_ip = self.pg0.remote_ip4
- pkts = [vr.vrrp_adv_packet(prio=prio+10, src_ip=src_ip)]
+ pkts = [vr.vrrp_adv_packet(prio=prio + 10, src_ip=src_ip)]
while time.time() < end_time:
self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s)
self.logger.info(self.vapi.cli("show trace"))
@@ -451,16 +479,16 @@ class TestVRRP4(VppTestCase):
self._vrs = []
def test_vrrp4_master_arp(self):
- """ IPv4 Master VR replies to ARP """
+ """IPv4 Master VR replies to ARP"""
self.pg_start()
# VR virtual IP is the default, which is the pg local IP
vr_id = 100
prio = 255
intvl = self._default_adv
- vr = VppVRRPVirtualRouter(self, self.pg0, 100,
- prio=prio, intvl=intvl,
- flags=self._default_flags)
+ vr = VppVRRPVirtualRouter(
+ self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -484,7 +512,7 @@ class TestVRRP4(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp4_backup_noarp(self):
- """ IPv4 Backup VR ignores ARP """
+ """IPv4 Backup VR ignores ARP"""
# We need an address for a virtual IP that is not the IP that
# ARP requests will originate from
@@ -492,16 +520,24 @@ class TestVRRP4(VppTestCase):
prio = 100
intvl = self._default_adv
vip = self.pg0.remote_hosts[1].ip4
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
- arp_req = (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) /
- ARP(op=ARP.who_has, pdst=vip,
- psrc=self.pg0.remote_ip4, hwsrc=self.pg0.remote_mac))
+ arp_req = Ether(dst="ff:ff:ff:ff:ff:ff", src=self.pg0.remote_mac) / ARP(
+ op=ARP.who_has,
+ pdst=vip,
+ psrc=self.pg0.remote_ip4,
+ hwsrc=self.pg0.remote_mac,
+ )
# Before the VR is started make sure no reply to request for VIP
self.pg_start()
@@ -510,7 +546,7 @@ class TestVRRP4(VppTestCase):
# VR should start in backup state and still should not reply to ARP
# send a higher priority adv to make sure it does not become master
- adv = vr.vrrp_adv_packet(prio=prio+10, src_ip=self.pg0.remote_ip4)
+ adv = vr.vrrp_adv_packet(prio=prio + 10, src_ip=self.pg0.remote_ip4)
vr.start_stop(is_start=1)
self.send_and_assert_no_replies(self.pg0, [adv, arp_req], timeout=1)
@@ -520,17 +556,22 @@ class TestVRRP4(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp4_election(self):
- """ IPv4 Backup VR becomes master if no advertisements received """
+ """IPv4 Backup VR becomes master if no advertisements received"""
vr_id = 100
prio = 100
intvl = self._default_adv
intvl_s = intvl * 0.01
vip = self.pg0.remote_ip4
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -557,17 +598,22 @@ class TestVRRP4(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp4_backup_preempts(self):
- """ IPv4 Backup VR preempts lower priority master """
+ """IPv4 Backup VR preempts lower priority master"""
vr_id = 100
prio = 100
intvl = self._default_adv
intvl_s = intvl * 0.01
vip = self.pg0.remote_ip4
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -583,7 +629,7 @@ class TestVRRP4(VppTestCase):
# send lower prio advertisements until timer expires
src_ip = self.pg0.remote_ip4
- pkts = [vr.vrrp_adv_packet(prio=prio-10, src_ip=src_ip)]
+ pkts = [vr.vrrp_adv_packet(prio=prio - 10, src_ip=src_ip)]
while time.time() + intvl_s < end_time:
self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s)
self.logger.info(self.vapi.cli("show trace"))
@@ -595,7 +641,7 @@ class TestVRRP4(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp4_master_preempted(self):
- """ IPv4 Master VR preempted by higher priority backup """
+ """IPv4 Master VR preempted by higher priority backup"""
# A prio 255 VR cannot be preempted so the prio has to be lower and
# we have to wait for it to take over
@@ -603,10 +649,15 @@ class TestVRRP4(VppTestCase):
prio = 100
intvl = self._default_adv
vip = self.pg0.remote_ip4
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -632,7 +683,7 @@ class TestVRRP4(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp4_accept_mode_disabled(self):
- """ IPv4 Master VR does not reply for VIP w/ accept mode off """
+ """IPv4 Master VR does not reply for VIP w/ accept mode off"""
# accept mode only matters when prio < 255, so it will have to
# come up as a backup and take over as master after the timeout
@@ -640,10 +691,15 @@ class TestVRRP4(VppTestCase):
prio = 100
intvl = self._default_adv
vip = self.pg0.remote_hosts[4].ip4
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -661,9 +717,11 @@ class TestVRRP4(VppTestCase):
vr.assert_state_equals(VRRP_VR_STATE_MASTER)
# send an ICMP echo to the VR virtual IP address
- echo = (Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) /
- IP(dst=vip, src=self.pg0.remote_ip4) /
- ICMP(seq=1, id=self.pg0.sw_if_index, type='echo-request'))
+ echo = (
+ Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac)
+ / IP(dst=vip, src=self.pg0.remote_ip4)
+ / ICMP(seq=1, id=self.pg0.sw_if_index, type="echo-request")
+ )
self.pg_send(self.pg0, [echo])
# wait for an echo reply. none should be received
@@ -672,7 +730,7 @@ class TestVRRP4(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp4_accept_mode_enabled(self):
- """ IPv4 Master VR replies for VIP w/ accept mode on """
+ """IPv4 Master VR replies for VIP w/ accept mode on"""
# A prio 255 VR cannot be preempted so the prio has to be lower and
# we have to wait for it to take over
@@ -680,11 +738,10 @@ class TestVRRP4(VppTestCase):
prio = 100
intvl = self._default_adv
vip = self.pg0.remote_hosts[4].ip4
- flags = (VRRP_VR_FLAG_PREEMPT | VRRP_VR_FLAG_ACCEPT)
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=flags,
- vips=[vip])
+ flags = VRRP_VR_FLAG_PREEMPT | VRRP_VR_FLAG_ACCEPT
+ vr = VppVRRPVirtualRouter(
+ self, self.pg0, vr_id, prio=prio, intvl=intvl, flags=flags, vips=[vip]
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -702,15 +759,18 @@ class TestVRRP4(VppTestCase):
vr.assert_state_equals(VRRP_VR_STATE_MASTER)
# send an ICMP echo to the VR virtual IP address
- echo = (Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) /
- IP(dst=vip, src=self.pg0.remote_ip4) /
- ICMP(seq=1, id=self.pg0.sw_if_index, type='echo-request'))
+ echo = (
+ Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac)
+ / IP(dst=vip, src=self.pg0.remote_ip4)
+ / ICMP(seq=1, id=self.pg0.sw_if_index, type="echo-request")
+ )
self.pg_send(self.pg0, [echo])
# wait for an echo reply.
time.sleep(1)
- rx_pkts = self.pg0.get_capture(expected_count=1, timeout=1,
- filter_out_fn=is_not_echo_reply)
+ rx_pkts = self.pg0.get_capture(
+ expected_count=1, timeout=1, filter_out_fn=is_not_echo_reply
+ )
self.assertEqual(rx_pkts[0][IP].src, vip)
self.assertEqual(rx_pkts[0][IP].dst, self.pg0.remote_ip4)
@@ -720,17 +780,22 @@ class TestVRRP4(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp4_intf_tracking(self):
- """ IPv4 Master VR adjusts priority based on tracked interface """
+ """IPv4 Master VR adjusts priority based on tracked interface"""
vr_id = 100
prio = 255
intvl = self._default_adv
intvl_s = intvl * 0.01
vip = self.pg0.local_ip4
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -740,9 +805,9 @@ class TestVRRP4(VppTestCase):
# add pg1 as a tracked interface and start the VR
adjustment = 50
adjusted_prio = prio - adjustment
- vr.add_del_tracked_interface(is_add=1,
- sw_if_index=self.pg1.sw_if_index,
- prio=adjustment)
+ vr.add_del_tracked_interface(
+ is_add=1, sw_if_index=self.pg1.sw_if_index, prio=adjustment
+ )
vr.start_stop(is_start=1)
vr.assert_state_equals(VRRP_VR_STATE_MASTER)
@@ -751,53 +816,47 @@ class TestVRRP4(VppTestCase):
# tracked intf is up -> advertised priority == configured priority
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertEqual(rx, adv_configured)
# take down pg1, verify priority is now being adjusted
self.pg1.admin_down()
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertEqual(rx, adv_adjusted)
# bring up pg1, verify priority now matches configured value
self.pg1.admin_up()
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertEqual(rx, adv_configured)
# remove IP address from pg1, verify priority now being adjusted
self.pg1.unconfig_ip4()
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertEqual(rx, adv_adjusted)
# add IP address to pg1, verify priority now matches configured value
self.pg1.config_ip4()
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertEqual(rx, adv_configured)
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp4_master_adv_unicast(self):
- """ IPv4 Master VR advertises (unicast) """
+ """IPv4 Master VR advertises (unicast)"""
vr_id = 100
prio = 255
intvl = self._default_adv
intvl_s = intvl * 0.01
vip = self.pg0.local_ip4
- flags = (self._default_flags | VRRP_VR_FLAG_UNICAST)
+ flags = self._default_flags | VRRP_VR_FLAG_UNICAST
unicast_peer = self.pg0.remote_hosts[4]
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self, self.pg0, vr_id, prio=prio, intvl=intvl, flags=flags, vips=[vip]
+ )
self._vrs.append(vr)
vr.add_vpp_config()
vr.set_unicast_peers([unicast_peer.ip4])
@@ -810,8 +869,7 @@ class TestVRRP4(VppTestCase):
vr.assert_state_equals(VRRP_VR_STATE_MASTER)
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertTrue(rx.haslayer(Ether))
self.assertTrue(rx.haslayer(IP))
@@ -827,7 +885,7 @@ class TestVRRP4(VppTestCase):
class TestVRRP6(VppTestCase):
- """ IPv6 VRRP Test Case """
+ """IPv6 VRRP Test Case"""
@classmethod
def setUpClass(cls):
@@ -849,7 +907,7 @@ class TestVRRP6(VppTestCase):
i.configure_ipv6_neighbors()
self._vrs = []
- self._default_flags = (VRRP_VR_FLAG_IPV6 | VRRP_VR_FLAG_PREEMPT)
+ self._default_flags = VRRP_VR_FLAG_IPV6 | VRRP_VR_FLAG_PREEMPT
self._default_adv = 100
def tearDown(self):
@@ -922,15 +980,15 @@ class TestVRRP6(VppTestCase):
# become master and start advertising immediately.
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp6_master_adv(self):
- """ IPv6 Master VR advertises """
+ """IPv6 Master VR advertises"""
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
prio = 255
intvl = self._default_adv
- vr = VppVRRPVirtualRouter(self, self.pg0, 100,
- prio=prio, intvl=intvl,
- flags=self._default_flags)
+ vr = VppVRRPVirtualRouter(
+ self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -956,25 +1014,30 @@ class TestVRRP6(VppTestCase):
# of parameters to test that too
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp6_master_adv_update(self):
- """ IPv6 Master VR adv + Update to Backup """
+ """IPv6 Master VR adv + Update to Backup"""
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
prio = 255
intvl = self._default_adv
- vr = VppVRRPVirtualRouter(self, self.pg0, 100,
- prio=prio, intvl=intvl,
- flags=self._default_flags)
+ vr = VppVRRPVirtualRouter(
+ self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags
+ )
vr.update_vpp_config()
vr.start_stop(is_start=1)
self.logger.info(self.vapi.cli("show vrrp vr"))
# Update VR with lower prio and larger interval
# we need to keep old VR for the adv checks
- upd_vr = VppVRRPVirtualRouter(self, self.pg0, 100,
- prio=100, intvl=2*intvl,
- flags=self._default_flags,
- vips=[self.pg0.remote_ip6])
+ upd_vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ 100,
+ prio=100,
+ intvl=2 * intvl,
+ flags=self._default_flags,
+ vips=[self.pg0.remote_ip6],
+ )
upd_vr._vrrp_index = vr._vrrp_index
upd_vr.update_vpp_config()
start_time = time.time()
@@ -1000,7 +1063,8 @@ class TestVRRP6(VppTestCase):
end_time = start_time + 2 * upd_vr.master_down_seconds()
while time.time() < end_time:
self.send_and_assert_no_replies(
- self.pg0, pkts, timeout=0.01*upd_vr._intvl)
+ self.pg0, pkts, timeout=0.01 * upd_vr._intvl
+ )
self.logger.info(self.vapi.cli("show trace"))
vr.start_stop(is_start=0)
@@ -1010,7 +1074,7 @@ class TestVRRP6(VppTestCase):
# long as it receives higher priority advertisements
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp6_backup_noadv(self):
- """ IPv6 Backup VR does not advertise """
+ """IPv6 Backup VR does not advertise"""
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
@@ -1018,10 +1082,15 @@ class TestVRRP6(VppTestCase):
prio = 100
intvl = self._default_adv
intvl_s = intvl * 0.01
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[self.pg0.remote_ip6])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[self.pg0.remote_ip6],
+ )
vr.add_vpp_config()
self._vrs.append(vr)
@@ -1037,7 +1106,7 @@ class TestVRRP6(VppTestCase):
# send higher prio advertisements, should not see VPP send any
src_ip = self.pg0.remote_ip6_ll
num_advs = 5
- pkts = [vr.vrrp_adv_packet(prio=prio+10, src_ip=src_ip)]
+ pkts = [vr.vrrp_adv_packet(prio=prio + 10, src_ip=src_ip)]
self.logger.info(self.vapi.cli("show vlib graph"))
while time.time() < end_time:
self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s)
@@ -1050,16 +1119,16 @@ class TestVRRP6(VppTestCase):
self._vrs = []
def test_vrrp6_master_nd(self):
- """ IPv6 Master VR replies to NDP """
+ """IPv6 Master VR replies to NDP"""
self.pg_start()
# VR virtual IP is the default, which is the pg local IP
vr_id = 100
prio = 255
intvl = self._default_adv
- vr = VppVRRPVirtualRouter(self, self.pg0, 100,
- prio=prio, intvl=intvl,
- flags=self._default_flags)
+ vr = VppVRRPVirtualRouter(
+ self, self.pg0, 100, prio=prio, intvl=intvl, flags=self._default_flags
+ )
vr.add_vpp_config()
self._vrs.append(vr)
@@ -1082,7 +1151,7 @@ class TestVRRP6(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp6_backup_nond(self):
- """ IPv6 Backup VR ignores NDP """
+ """IPv6 Backup VR ignores NDP"""
# We need an address for a virtual IP that is not the IP that
# ARP requests will originate from
@@ -1091,10 +1160,15 @@ class TestVRRP6(VppTestCase):
intvl = self._default_adv
intvl_s = intvl * 0.01
vip = self.pg0.remote_hosts[1].ip6
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
vr.add_vpp_config()
self._vrs.append(vr)
@@ -1102,36 +1176,43 @@ class TestVRRP6(VppTestCase):
dmac = in6_getnsmac(nsma)
dst_ip = inet_ntop(socket.AF_INET6, nsma)
- ndp_req = (Ether(dst=dmac, src=self.pg0.remote_mac) /
- IPv6(dst=dst_ip, src=self.pg0.remote_ip6) /
- ICMPv6ND_NS(tgt=vip) /
- ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac))
+ ndp_req = (
+ Ether(dst=dmac, src=self.pg0.remote_mac)
+ / IPv6(dst=dst_ip, src=self.pg0.remote_ip6)
+ / ICMPv6ND_NS(tgt=vip)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.pg0.remote_mac)
+ )
# Before the VR is started make sure no reply to request for VIP
self.send_and_assert_no_replies(self.pg0, [ndp_req], timeout=1)
# VR should start in backup state and still should not reply to NDP
# send a higher priority adv to make sure it does not become master
- adv = vr.vrrp_adv_packet(prio=prio+10, src_ip=self.pg0.remote_ip6)
+ adv = vr.vrrp_adv_packet(prio=prio + 10, src_ip=self.pg0.remote_ip6)
pkts = [adv, ndp_req]
vr.start_stop(is_start=1)
- self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s)
+ self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s)
vr.start_stop(is_start=0)
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp6_election(self):
- """ IPv6 Backup VR becomes master if no advertisements received """
+ """IPv6 Backup VR becomes master if no advertisements received"""
vr_id = 100
prio = 100
intvl = self._default_adv
intvl_s = intvl * 0.01
vip = self.pg0.remote_ip6
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -1158,17 +1239,22 @@ class TestVRRP6(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp6_backup_preempts(self):
- """ IPv6 Backup VR preempts lower priority master """
+ """IPv6 Backup VR preempts lower priority master"""
vr_id = 100
prio = 100
intvl = self._default_adv
intvl_s = intvl * 0.01
vip = self.pg0.remote_ip6
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -1184,7 +1270,7 @@ class TestVRRP6(VppTestCase):
# send lower prio advertisements until timer expires
src_ip = self.pg0.remote_ip6
- pkts = [vr.vrrp_adv_packet(prio=prio-10, src_ip=src_ip)]
+ pkts = [vr.vrrp_adv_packet(prio=prio - 10, src_ip=src_ip)]
while (time.time() + intvl_s) < end_time:
self.send_and_assert_no_replies(self.pg0, pkts, timeout=intvl_s)
self.logger.info(self.vapi.cli("show trace"))
@@ -1196,7 +1282,7 @@ class TestVRRP6(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp6_master_preempted(self):
- """ IPv6 Master VR preempted by higher priority backup """
+ """IPv6 Master VR preempted by higher priority backup"""
# A prio 255 VR cannot be preempted so the prio has to be lower and
# we have to wait for it to take over
@@ -1204,10 +1290,15 @@ class TestVRRP6(VppTestCase):
prio = 100
intvl = self._default_adv
vip = self.pg0.remote_ip6
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -1233,7 +1324,7 @@ class TestVRRP6(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp6_accept_mode_disabled(self):
- """ IPv6 Master VR does not reply for VIP w/ accept mode off """
+ """IPv6 Master VR does not reply for VIP w/ accept mode off"""
# accept mode only matters when prio < 255, so it will have to
# come up as a backup and take over as master after the timeout
@@ -1241,10 +1332,15 @@ class TestVRRP6(VppTestCase):
prio = 100
intvl = self._default_adv
vip = self.pg0.remote_hosts[4].ip6
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -1262,9 +1358,11 @@ class TestVRRP6(VppTestCase):
vr.assert_state_equals(VRRP_VR_STATE_MASTER)
# send an ICMPv6 echo to the VR virtual IP address
- echo = (Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) /
- IPv6(dst=vip, src=self.pg0.remote_ip6) /
- ICMPv6EchoRequest(seq=1, id=self.pg0.sw_if_index))
+ echo = (
+ Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac)
+ / IPv6(dst=vip, src=self.pg0.remote_ip6)
+ / ICMPv6EchoRequest(seq=1, id=self.pg0.sw_if_index)
+ )
self.pg_send(self.pg0, [echo])
# wait for an echo reply. none should be received
@@ -1273,7 +1371,7 @@ class TestVRRP6(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp6_accept_mode_enabled(self):
- """ IPv6 Master VR replies for VIP w/ accept mode on """
+ """IPv6 Master VR replies for VIP w/ accept mode on"""
# A prio 255 VR cannot be preempted so the prio has to be lower and
# we have to wait for it to take over
@@ -1281,11 +1379,10 @@ class TestVRRP6(VppTestCase):
prio = 100
intvl = self._default_adv
vip = self.pg0.remote_hosts[4].ip6
- flags = (self._default_flags | VRRP_VR_FLAG_ACCEPT)
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=flags,
- vips=[vip])
+ flags = self._default_flags | VRRP_VR_FLAG_ACCEPT
+ vr = VppVRRPVirtualRouter(
+ self, self.pg0, vr_id, prio=prio, intvl=intvl, flags=flags, vips=[vip]
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -1303,15 +1400,18 @@ class TestVRRP6(VppTestCase):
vr.assert_state_equals(VRRP_VR_STATE_MASTER)
# send an ICMP echo to the VR virtual IP address
- echo = (Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac) /
- IPv6(dst=vip, src=self.pg0.remote_ip6) /
- ICMPv6EchoRequest(seq=1, id=self.pg0.sw_if_index))
+ echo = (
+ Ether(dst=vr.virtual_mac(), src=self.pg0.remote_mac)
+ / IPv6(dst=vip, src=self.pg0.remote_ip6)
+ / ICMPv6EchoRequest(seq=1, id=self.pg0.sw_if_index)
+ )
self.pg_send(self.pg0, [echo])
# wait for an echo reply.
time.sleep(1)
- rx_pkts = self.pg0.get_capture(expected_count=1, timeout=1,
- filter_out_fn=is_not_echo_reply)
+ rx_pkts = self.pg0.get_capture(
+ expected_count=1, timeout=1, filter_out_fn=is_not_echo_reply
+ )
self.assertEqual(rx_pkts[0][IPv6].src, vip)
self.assertEqual(rx_pkts[0][IPv6].dst, self.pg0.remote_ip6)
@@ -1320,17 +1420,22 @@ class TestVRRP6(VppTestCase):
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp6_intf_tracking(self):
- """ IPv6 Master VR adjusts priority based on tracked interface """
+ """IPv6 Master VR adjusts priority based on tracked interface"""
vr_id = 100
prio = 255
intvl = self._default_adv
intvl_s = intvl * 0.01
vip = self.pg0.local_ip6
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=self._default_flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self,
+ self.pg0,
+ vr_id,
+ prio=prio,
+ intvl=intvl,
+ flags=self._default_flags,
+ vips=[vip],
+ )
self._vrs.append(vr)
vr.add_vpp_config()
@@ -1340,9 +1445,9 @@ class TestVRRP6(VppTestCase):
# add pg1 as a tracked interface and start the VR
adjustment = 50
adjusted_prio = prio - adjustment
- vr.add_del_tracked_interface(is_add=1,
- sw_if_index=self.pg1.sw_if_index,
- prio=adjustment)
+ vr.add_del_tracked_interface(
+ is_add=1, sw_if_index=self.pg1.sw_if_index, prio=adjustment
+ )
vr.start_stop(is_start=1)
vr.assert_state_equals(VRRP_VR_STATE_MASTER)
@@ -1351,53 +1456,47 @@ class TestVRRP6(VppTestCase):
# tracked intf is up -> advertised priority == configured priority
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertEqual(rx, adv_configured)
# take down pg1, verify priority is now being adjusted
self.pg1.admin_down()
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertEqual(rx, adv_adjusted)
# bring up pg1, verify priority now matches configured value
self.pg1.admin_up()
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertEqual(rx, adv_configured)
# remove IP address from pg1, verify priority now being adjusted
self.pg1.unconfig_ip6()
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertEqual(rx, adv_adjusted)
# add IP address to pg1, verify priority now matches configured value
self.pg1.config_ip6()
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertEqual(rx, adv_configured)
@unittest.skipUnless(config.extended, "part of extended tests")
def test_vrrp6_master_adv_unicast(self):
- """ IPv6 Master VR advertises (unicast) """
+ """IPv6 Master VR advertises (unicast)"""
vr_id = 100
prio = 255
intvl = self._default_adv
intvl_s = intvl * 0.01
vip = self.pg0.local_ip6
- flags = (self._default_flags | VRRP_VR_FLAG_UNICAST)
+ flags = self._default_flags | VRRP_VR_FLAG_UNICAST
unicast_peer = self.pg0.remote_hosts[4]
- vr = VppVRRPVirtualRouter(self, self.pg0, vr_id,
- prio=prio, intvl=intvl,
- flags=flags,
- vips=[vip])
+ vr = VppVRRPVirtualRouter(
+ self, self.pg0, vr_id, prio=prio, intvl=intvl, flags=flags, vips=[vip]
+ )
self._vrs.append(vr)
vr.add_vpp_config()
vr.set_unicast_peers([unicast_peer.ip6])
@@ -1410,23 +1509,22 @@ class TestVRRP6(VppTestCase):
vr.assert_state_equals(VRRP_VR_STATE_MASTER)
self.pg0.enable_capture()
- rx = self.pg0.wait_for_packet(timeout=intvl_s,
- filter_out_fn=is_not_adv)
+ rx = self.pg0.wait_for_packet(timeout=intvl_s, filter_out_fn=is_not_adv)
self.assertTrue(rx.haslayer(Ether))
self.assertTrue(rx.haslayer(IPv6))
self.assertTrue(rx.haslayer(VRRPv3))
self.assertEqual(rx[Ether].src, self.pg0.local_mac)
self.assertEqual(rx[Ether].dst, unicast_peer.mac)
- self.assertEqual(ip6_normalize(rx[IPv6].src),
- ip6_normalize(self.pg0.local_ip6_ll))
- self.assertEqual(ip6_normalize(rx[IPv6].dst),
- ip6_normalize(unicast_peer.ip6))
+ self.assertEqual(
+ ip6_normalize(rx[IPv6].src), ip6_normalize(self.pg0.local_ip6_ll)
+ )
+ self.assertEqual(ip6_normalize(rx[IPv6].dst), ip6_normalize(unicast_peer.ip6))
self.assertEqual(rx[VRRPv3].vrid, vr_id)
self.assertEqual(rx[VRRPv3].priority, prio)
self.assertEqual(rx[VRRPv3].ipcount, 1)
self.assertEqual(rx[VRRPv3].addrlist, [vip])
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_vtr.py b/test/test_vtr.py
index c3704f1e7b6..b33dcb66541 100644
--- a/test/test_vtr.py
+++ b/test/test_vtr.py
@@ -12,13 +12,13 @@ from framework import VppTestCase, VppTestRunner
from vpp_sub_interface import L2_VTR_OP, VppDot1QSubint, VppDot1ADSubint
from collections import namedtuple
-Tag = namedtuple('Tag', ['dot1', 'vlan'])
+Tag = namedtuple("Tag", ["dot1", "vlan"])
DOT1AD = 0x88A8
DOT1Q = 0x8100
class TestVtr(VppTestCase):
- """ VTR Test Case """
+ """VTR Test Case"""
@classmethod
def setUpClass(cls):
@@ -36,9 +36,9 @@ class TestVtr(VppTestCase):
cls.create_pg_interfaces(ifs)
cls.sub_interfaces = [
- VppDot1ADSubint(cls, cls.pg1, cls.dot1ad_sub_id,
- cls.Btag, cls.Atag),
- VppDot1QSubint(cls, cls.pg2, cls.Btag)]
+ VppDot1ADSubint(cls, cls.pg1, cls.dot1ad_sub_id, cls.Btag, cls.Atag),
+ VppDot1QSubint(cls, cls.pg2, cls.Btag),
+ ]
interfaces = list(cls.pg_interfaces)
interfaces.extend(cls.sub_interfaces)
@@ -46,10 +46,14 @@ class TestVtr(VppTestCase):
# Create BD with MAC learning enabled and put interfaces and
# sub-interfaces to this BD
for pg_if in cls.pg_interfaces:
- sw_if_index = pg_if.sub_if.sw_if_index \
- if hasattr(pg_if, 'sub_if') else pg_if.sw_if_index
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=sw_if_index,
- bd_id=cls.bd_id)
+ sw_if_index = (
+ pg_if.sub_if.sw_if_index
+ if hasattr(pg_if, "sub_if")
+ else pg_if.sw_if_index
+ )
+ cls.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=sw_if_index, bd_id=cls.bd_id
+ )
# setup all interfaces
for i in interfaces:
@@ -86,8 +90,7 @@ class TestVtr(VppTestCase):
def show_commands_at_teardown(self):
self.logger.info(self.vapi.ppcli("show l2fib verbose"))
- self.logger.info(self.vapi.ppcli("show bridge-domain %s detail" %
- self.bd_id))
+ self.logger.info(self.vapi.ppcli("show bridge-domain %s detail" % self.bd_id))
@classmethod
def create_hosts_and_learn(cls, count):
@@ -98,10 +101,11 @@ class TestVtr(VppTestCase):
for j in range(1, count + 1):
host = Host(
"00:00:00:ff:%02x:%02x" % (pg_if.sw_if_index, j),
- "172.17.1%02x.%u" % (pg_if.sw_if_index, j))
- packet = (Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac))
+ "172.17.1%02x.%u" % (pg_if.sw_if_index, j),
+ )
+ packet = Ether(dst="ff:ff:ff:ff:ff:ff", src=host.mac)
hosts.append(host)
- if hasattr(pg_if, 'sub_if'):
+ if hasattr(pg_if, "sub_if"):
packet = pg_if.sub_if.add_dot1_layer(packet)
packets.append(packet)
pg_if.add_stream(packets)
@@ -115,12 +119,14 @@ class TestVtr(VppTestCase):
src_host = random.choice(self.hosts_by_pg_idx[src_if.sw_if_index])
pkt_info = self.create_packet_info(src_if, dst_if)
payload = self.info_to_payload(pkt_info)
- p = (Ether(dst=dst_host.mac, src=src_host.mac) /
- IP(src=src_host.ip4, dst=dst_host.ip4) /
- UDP(sport=1234, dport=1234) /
- Raw(payload))
+ p = (
+ Ether(dst=dst_host.mac, src=src_host.mac)
+ / IP(src=src_host.ip4, dst=dst_host.ip4)
+ / UDP(sport=1234, dport=1234)
+ / Raw(payload)
+ )
pkt_info.data = p.copy()
- if do_dot1 and hasattr(src_if, 'sub_if'):
+ if do_dot1 and hasattr(src_if, "sub_if"):
p = src_if.sub_if.add_dot1_layer(p)
size = random.choice(packet_sizes)
self.extend_packet(p, size)
@@ -172,8 +178,9 @@ class TestVtr(VppTestCase):
return
i = VppDot1QSubint(self, self.pg0, tags[0].vlan)
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=self.bd_id, enable=1)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index, bd_id=self.bd_id, enable=1
+ )
i.admin_up()
p = self.create_packet(self.pg0, swif, do_dot1=False)
@@ -185,202 +192,217 @@ class TestVtr(VppTestCase):
swif.sub_if.remove_dot1_layer(rx[0])
self.assertTrue(Dot1Q not in rx[0])
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=i.sw_if_index,
- bd_id=self.bd_id, enable=0)
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=i.sw_if_index, bd_id=self.bd_id, enable=0
+ )
i.remove_vpp_config()
def test_1ad_vtr_pop_1(self):
- """ 1AD VTR pop 1 test
- """
+ """1AD VTR pop 1 test"""
self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_POP_1)
self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=100)])
def test_1ad_vtr_pop_2(self):
- """ 1AD VTR pop 2 test
- """
+ """1AD VTR pop 2 test"""
self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_POP_2)
self.vtr_test(self.pg1, [])
def test_1ad_vtr_push_1ad(self):
- """ 1AD VTR push 1 1AD test
- """
+ """1AD VTR push 1 1AD test"""
self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_1, tag=300)
- self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=300),
- Tag(dot1=DOT1AD, vlan=200),
- Tag(dot1=DOT1Q, vlan=100)])
+ self.vtr_test(
+ self.pg1,
+ [
+ Tag(dot1=DOT1AD, vlan=300),
+ Tag(dot1=DOT1AD, vlan=200),
+ Tag(dot1=DOT1Q, vlan=100),
+ ],
+ )
def test_1ad_vtr_push_2ad(self):
- """ 1AD VTR push 2 1AD test
- """
+ """1AD VTR push 2 1AD test"""
self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_2, outer=400, inner=300)
- self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=400),
- Tag(dot1=DOT1Q, vlan=300),
- Tag(dot1=DOT1AD, vlan=200),
- Tag(dot1=DOT1Q, vlan=100)])
+ self.vtr_test(
+ self.pg1,
+ [
+ Tag(dot1=DOT1AD, vlan=400),
+ Tag(dot1=DOT1Q, vlan=300),
+ Tag(dot1=DOT1AD, vlan=200),
+ Tag(dot1=DOT1Q, vlan=100),
+ ],
+ )
def test_1ad_vtr_push_1q(self):
- """ 1AD VTR push 1 1Q test
- """
+ """1AD VTR push 1 1Q test"""
self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_1, tag=300, push1q=1)
- self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=300),
- Tag(dot1=DOT1AD, vlan=200),
- Tag(dot1=DOT1Q, vlan=100)])
+ self.vtr_test(
+ self.pg1,
+ [
+ Tag(dot1=DOT1Q, vlan=300),
+ Tag(dot1=DOT1AD, vlan=200),
+ Tag(dot1=DOT1Q, vlan=100),
+ ],
+ )
def test_1ad_vtr_push_2q(self):
- """ 1AD VTR push 2 1Q test
- """
- self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_2,
- outer=400, inner=300, push1q=1)
- self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=400),
- Tag(dot1=DOT1Q, vlan=300),
- Tag(dot1=DOT1AD, vlan=200),
- Tag(dot1=DOT1Q, vlan=100)])
+ """1AD VTR push 2 1Q test"""
+ self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_2, outer=400, inner=300, push1q=1)
+ self.vtr_test(
+ self.pg1,
+ [
+ Tag(dot1=DOT1Q, vlan=400),
+ Tag(dot1=DOT1Q, vlan=300),
+ Tag(dot1=DOT1AD, vlan=200),
+ Tag(dot1=DOT1Q, vlan=100),
+ ],
+ )
def test_1ad_vtr_translate_1_1ad(self):
- """ 1AD VTR translate 1 -> 1 1AD test
- """
+ """1AD VTR translate 1 -> 1 1AD test"""
self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_1_1, tag=300)
- self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=300),
- Tag(dot1=DOT1Q, vlan=100)])
+ self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=300), Tag(dot1=DOT1Q, vlan=100)])
def test_1ad_vtr_translate_1_2ad(self):
- """ 1AD VTR translate 1 -> 2 1AD test
- """
- self.pg1.sub_if.set_vtr(
- L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400)
- self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=400),
- Tag(dot1=DOT1Q, vlan=300),
- Tag(dot1=DOT1Q, vlan=100)])
+ """1AD VTR translate 1 -> 2 1AD test"""
+ self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400)
+ self.vtr_test(
+ self.pg1,
+ [
+ Tag(dot1=DOT1AD, vlan=400),
+ Tag(dot1=DOT1Q, vlan=300),
+ Tag(dot1=DOT1Q, vlan=100),
+ ],
+ )
def test_1ad_vtr_translate_2_1ad(self):
- """ 1AD VTR translate 2 -> 1 1AD test
- """
+ """1AD VTR translate 2 -> 1 1AD test"""
self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_2_1, tag=300)
self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=300)])
def test_1ad_vtr_translate_2_2ad(self):
- """ 1AD VTR translate 2 -> 2 1AD test
- """
- self.pg1.sub_if.set_vtr(
- L2_VTR_OP.L2_TRANSLATE_2_2, inner=300, outer=400)
- self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=400),
- Tag(dot1=DOT1Q, vlan=300)])
+ """1AD VTR translate 2 -> 2 1AD test"""
+ self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_2_2, inner=300, outer=400)
+ self.vtr_test(self.pg1, [Tag(dot1=DOT1AD, vlan=400), Tag(dot1=DOT1Q, vlan=300)])
def test_1ad_vtr_translate_1_1q(self):
- """ 1AD VTR translate 1 -> 1 1Q test
- """
+ """1AD VTR translate 1 -> 1 1Q test"""
self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_1_1, tag=300, push1q=1)
- self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=300),
- Tag(dot1=DOT1Q, vlan=100)])
+ self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=300), Tag(dot1=DOT1Q, vlan=100)])
def test_1ad_vtr_translate_1_2q(self):
- """ 1AD VTR translate 1 -> 2 1Q test
- """
+ """1AD VTR translate 1 -> 2 1Q test"""
self.pg1.sub_if.set_vtr(
- L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400, push1q=1)
- self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=400),
- Tag(dot1=DOT1Q, vlan=300),
- Tag(dot1=DOT1Q, vlan=100)])
+ L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400, push1q=1
+ )
+ self.vtr_test(
+ self.pg1,
+ [
+ Tag(dot1=DOT1Q, vlan=400),
+ Tag(dot1=DOT1Q, vlan=300),
+ Tag(dot1=DOT1Q, vlan=100),
+ ],
+ )
def test_1ad_vtr_translate_2_1q(self):
- """ 1AD VTR translate 2 -> 1 1Q test
- """
+ """1AD VTR translate 2 -> 1 1Q test"""
self.pg1.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_2_1, tag=300, push1q=1)
self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=300)])
def test_1ad_vtr_translate_2_2q(self):
- """ 1AD VTR translate 2 -> 2 1Q test
- """
+ """1AD VTR translate 2 -> 2 1Q test"""
self.pg1.sub_if.set_vtr(
- L2_VTR_OP.L2_TRANSLATE_2_2, inner=300, outer=400, push1q=1)
- self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=400),
- Tag(dot1=DOT1Q, vlan=300)])
+ L2_VTR_OP.L2_TRANSLATE_2_2, inner=300, outer=400, push1q=1
+ )
+ self.vtr_test(self.pg1, [Tag(dot1=DOT1Q, vlan=400), Tag(dot1=DOT1Q, vlan=300)])
def test_1q_vtr_pop_1(self):
- """ 1Q VTR pop 1 test
- """
+ """1Q VTR pop 1 test"""
self.pg2.sub_if.set_vtr(L2_VTR_OP.L2_POP_1)
self.vtr_test(self.pg2, [])
def test_1q_vtr_push_1(self):
- """ 1Q VTR push 1 test
- """
+ """1Q VTR push 1 test"""
self.pg2.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_1, tag=300)
- self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=300),
- Tag(dot1=DOT1Q, vlan=200)])
+ self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=300), Tag(dot1=DOT1Q, vlan=200)])
def test_1q_vtr_push_2(self):
- """ 1Q VTR push 2 test
- """
+ """1Q VTR push 2 test"""
self.pg2.sub_if.set_vtr(L2_VTR_OP.L2_PUSH_2, outer=400, inner=300)
- self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=400),
- Tag(dot1=DOT1Q, vlan=300),
- Tag(dot1=DOT1Q, vlan=200)])
+ self.vtr_test(
+ self.pg2,
+ [
+ Tag(dot1=DOT1AD, vlan=400),
+ Tag(dot1=DOT1Q, vlan=300),
+ Tag(dot1=DOT1Q, vlan=200),
+ ],
+ )
def test_1q_vtr_translate_1_1(self):
- """ 1Q VTR translate 1 -> 1 test
- """
+ """1Q VTR translate 1 -> 1 test"""
self.pg2.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_1_1, tag=300)
self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=300)])
def test_1q_vtr_translate_1_2(self):
- """ 1Q VTR translate 1 -> 2 test
- """
- self.pg2.sub_if.set_vtr(
- L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400)
- self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=400),
- Tag(dot1=DOT1Q, vlan=300)])
+ """1Q VTR translate 1 -> 2 test"""
+ self.pg2.sub_if.set_vtr(L2_VTR_OP.L2_TRANSLATE_1_2, inner=300, outer=400)
+ self.vtr_test(self.pg2, [Tag(dot1=DOT1AD, vlan=400), Tag(dot1=DOT1Q, vlan=300)])
def test_if_vtr_disable(self):
- """ Disable VTR on non-sub-interfaces
- """
+ """Disable VTR on non-sub-interfaces"""
# First set the VTR fields to junk
self.vapi.l2_interface_vlan_tag_rewrite(
- sw_if_index=self.pg0.sw_if_index, vtr_op=L2_VTR_OP.L2_PUSH_2,
- push_dot1q=1, tag1=19, tag2=630)
-
- if_state = self.vapi.sw_interface_dump(
- sw_if_index=self.pg0.sw_if_index)
+ sw_if_index=self.pg0.sw_if_index,
+ vtr_op=L2_VTR_OP.L2_PUSH_2,
+ push_dot1q=1,
+ tag1=19,
+ tag2=630,
+ )
+
+ if_state = self.vapi.sw_interface_dump(sw_if_index=self.pg0.sw_if_index)
self.assertEqual(if_state[0].sw_if_index, self.pg0.sw_if_index)
self.assertNotEqual(if_state[0].vtr_op, L2_VTR_OP.L2_DISABLED)
# Then ensure that a request to disable VTR is honored.
self.vapi.l2_interface_vlan_tag_rewrite(
- sw_if_index=self.pg0.sw_if_index, vtr_op=L2_VTR_OP.L2_DISABLED)
+ sw_if_index=self.pg0.sw_if_index, vtr_op=L2_VTR_OP.L2_DISABLED
+ )
- if_state = self.vapi.sw_interface_dump(
- sw_if_index=self.pg0.sw_if_index)
+ if_state = self.vapi.sw_interface_dump(sw_if_index=self.pg0.sw_if_index)
self.assertEqual(if_state[0].sw_if_index, self.pg0.sw_if_index)
self.assertEqual(if_state[0].vtr_op, L2_VTR_OP.L2_DISABLED)
def test_if_vtr_push_1q(self):
- """ 1Q VTR push 1 on non-sub-interfaces
- """
+ """1Q VTR push 1 on non-sub-interfaces"""
self.vapi.l2_interface_vlan_tag_rewrite(
- sw_if_index=self.pg0.sw_if_index, vtr_op=L2_VTR_OP.L2_PUSH_1,
- push_dot1q=1, tag1=150)
+ sw_if_index=self.pg0.sw_if_index,
+ vtr_op=L2_VTR_OP.L2_PUSH_1,
+ push_dot1q=1,
+ tag1=150,
+ )
- if_state = self.vapi.sw_interface_dump(
- sw_if_index=self.pg0.sw_if_index)
+ if_state = self.vapi.sw_interface_dump(sw_if_index=self.pg0.sw_if_index)
self.assertEqual(if_state[0].sw_if_index, self.pg0.sw_if_index)
self.assertEqual(if_state[0].vtr_op, L2_VTR_OP.L2_PUSH_1)
self.assertEqual(if_state[0].vtr_tag1, 150)
self.assertNotEqual(if_state[0].vtr_push_dot1q, 0)
def test_if_vtr_push_2ad(self):
- """ 1AD VTR push 2 on non-sub-interfaces
- """
+ """1AD VTR push 2 on non-sub-interfaces"""
self.vapi.l2_interface_vlan_tag_rewrite(
- sw_if_index=self.pg0.sw_if_index, vtr_op=L2_VTR_OP.L2_PUSH_2,
- push_dot1q=0, tag1=450, tag2=350)
-
- if_state = self.vapi.sw_interface_dump(
- sw_if_index=self.pg0.sw_if_index)
+ sw_if_index=self.pg0.sw_if_index,
+ vtr_op=L2_VTR_OP.L2_PUSH_2,
+ push_dot1q=0,
+ tag1=450,
+ tag2=350,
+ )
+
+ if_state = self.vapi.sw_interface_dump(sw_if_index=self.pg0.sw_if_index)
self.assertEqual(if_state[0].sw_if_index, self.pg0.sw_if_index)
self.assertEqual(if_state[0].vtr_op, L2_VTR_OP.L2_PUSH_2)
- self.assertEqual(if_state[0].vtr_tag1, 450) # outer
- self.assertEqual(if_state[0].vtr_tag2, 350) # inner
+ self.assertEqual(if_state[0].vtr_tag1, 450) # outer
+ self.assertEqual(if_state[0].vtr_tag2, 350) # inner
self.assertEqual(if_state[0].vtr_push_dot1q, 0)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_vxlan.py b/test/test_vxlan.py
index 4247a396d24..913fc4018e0 100644
--- a/test/test_vxlan.py
+++ b/test/test_vxlan.py
@@ -20,7 +20,7 @@ from vpp_neighbor import VppNeighbor
class TestVxlan(BridgeDomain, VppTestCase):
- """ VXLAN Test Case """
+ """VXLAN Test Case"""
def __init__(self, *args):
BridgeDomain.__init__(self)
@@ -31,14 +31,16 @@ class TestVxlan(BridgeDomain, VppTestCase):
Encapsulate the original payload frame by adding VXLAN header with its
UDP, IP and Ethernet fields
"""
- return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=self.dport, dport=self.dport, chksum=0) /
- VXLAN(vni=vni, flags=self.flags) /
- pkt)
+ return (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ / VXLAN(vni=vni, flags=self.flags)
+ / pkt
+ )
def ip_range(self, start, end):
- """ range of remote ip's """
+ """range of remote ip's"""
return ip4_range(self.pg0.remote_ip4, start, end)
def encap_mcast(self, pkt, src_ip, src_mac, vni):
@@ -46,18 +48,20 @@ class TestVxlan(BridgeDomain, VppTestCase):
Encapsulate the original payload frame by adding VXLAN header with its
UDP, IP and Ethernet fields
"""
- return (Ether(src=src_mac, dst=self.mcast_mac) /
- IP(src=src_ip, dst=self.mcast_ip4) /
- UDP(sport=self.dport, dport=self.dport, chksum=0) /
- VXLAN(vni=vni, flags=self.flags) /
- pkt)
+ return (
+ Ether(src=src_mac, dst=self.mcast_mac)
+ / IP(src=src_ip, dst=self.mcast_ip4)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ / VXLAN(vni=vni, flags=self.flags)
+ / pkt
+ )
def decapsulate(self, pkt):
"""
Decapsulate the original payload frame by removing VXLAN header
"""
# check if is set I flag
- self.assertEqual(pkt[VXLAN].flags, int('0x8', 16))
+ self.assertEqual(pkt[VXLAN].flags, int("0x8", 16))
return pkt[VXLAN].payload
# Method for checking VXLAN encapsulation.
@@ -93,18 +97,25 @@ class TestVxlan(BridgeDomain, VppTestCase):
ip_range_start = 10
ip_range_end = ip_range_start + n_ucast_tunnels
next_hop_address = cls.pg0.remote_ip4
- for dest_ip4 in ip4_range(next_hop_address, ip_range_start,
- ip_range_end):
+ for dest_ip4 in ip4_range(next_hop_address, ip_range_start, ip_range_end):
# add host route so dest_ip4 will not be resolved
- rip = VppIpRoute(cls, dest_ip4, 32,
- [VppRoutePath(next_hop_address,
- INVALID_INDEX)],
- register=False)
+ rip = VppIpRoute(
+ cls,
+ dest_ip4,
+ 32,
+ [VppRoutePath(next_hop_address, INVALID_INDEX)],
+ register=False,
+ )
rip.add_vpp_config()
- r = VppVxlanTunnel(cls, src=cls.pg0.local_ip4,
- src_port=port, dst_port=port,
- dst=dest_ip4, vni=vni)
+ r = VppVxlanTunnel(
+ cls,
+ src=cls.pg0.local_ip4,
+ src_port=port,
+ dst_port=port,
+ dst=dest_ip4,
+ vni=vni,
+ )
r.add_vpp_config()
cls.vapi.sw_interface_set_l2_bridge(r.sw_if_index, bd_id=vni)
@@ -118,12 +129,18 @@ class TestVxlan(BridgeDomain, VppTestCase):
vni_start = 10000
vni_end = vni_start + n_shared_dst_tunnels
for vni in range(vni_start, vni_end):
- r = VppVxlanTunnel(cls, src=cls.pg0.local_ip4,
- src_port=port, dst_port=port,
- dst=cls.mcast_ip4, mcast_sw_if_index=1, vni=vni)
+ r = VppVxlanTunnel(
+ cls,
+ src=cls.pg0.local_ip4,
+ src_port=port,
+ dst_port=port,
+ dst=cls.mcast_ip4,
+ mcast_sw_if_index=1,
+ vni=vni,
+ )
if is_add:
r.add_vpp_config()
- if r.sw_if_index == 0xffffffff:
+ if r.sw_if_index == 0xFFFFFFFF:
raise ValueError("bad sw_if_index: ~0")
else:
r.remove_vpp_config()
@@ -144,12 +161,17 @@ class TestVxlan(BridgeDomain, VppTestCase):
n_distinct_dst_tunnels = 200
ip_range_start = 10
ip_range_end = ip_range_start + n_distinct_dst_tunnels
- for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start,
- ip_range_end):
+ for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, ip_range_end):
vni = bytearray(socket.inet_pton(socket.AF_INET, dest_ip4))[3]
- r = VppVxlanTunnel(cls, src=cls.pg0.local_ip4,
- src_port=port, dst_port=port,
- dst=dest_ip4, mcast_sw_if_index=1, vni=vni)
+ r = VppVxlanTunnel(
+ cls,
+ src=cls.pg0.local_ip4,
+ src_port=port,
+ dst_port=port,
+ dst=dest_ip4,
+ mcast_sw_if_index=1,
+ vni=vni,
+ )
if is_add:
r.add_vpp_config()
else:
@@ -187,7 +209,7 @@ class TestVxlan(BridgeDomain, VppTestCase):
cls.pg0.resolve_arp()
# Our Multicast address
- cls.mcast_ip4 = '239.1.1.1'
+ cls.mcast_ip4 = "239.1.1.1"
cls.mcast_mac = util.mcast_ip_to_mac(cls.mcast_ip4)
except Exception:
cls.tearDownClass()
@@ -207,30 +229,44 @@ class TestVxlan(BridgeDomain, VppTestCase):
self.single_tunnel_vni = 0x12345
self.single_tunnel_bd = 1
- r = VppVxlanTunnel(self, src=self.pg0.local_ip4,
- dst=self.pg0.remote_ip4,
- src_port=self.dport, dst_port=self.dport,
- vni=self.single_tunnel_vni)
+ r = VppVxlanTunnel(
+ self,
+ src=self.pg0.local_ip4,
+ dst=self.pg0.remote_ip4,
+ src_port=self.dport,
+ dst_port=self.dport,
+ vni=self.single_tunnel_vni,
+ )
r.add_vpp_config()
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=self.single_tunnel_bd)
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd)
+ rx_sw_if_index=r.sw_if_index, bd_id=self.single_tunnel_bd
+ )
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd
+ )
# Setup vni 2 to test multicast flooding
self.n_ucast_tunnels = 10
self.mcast_flood_bd = 2
- self.create_vxlan_flood_test_bd(self.mcast_flood_bd,
- self.n_ucast_tunnels,
- self.dport)
- r = VppVxlanTunnel(self, src=self.pg0.local_ip4, dst=self.mcast_ip4,
- src_port=self.dport, dst_port=self.dport,
- mcast_sw_if_index=1, vni=self.mcast_flood_bd)
+ self.create_vxlan_flood_test_bd(
+ self.mcast_flood_bd, self.n_ucast_tunnels, self.dport
+ )
+ r = VppVxlanTunnel(
+ self,
+ src=self.pg0.local_ip4,
+ dst=self.mcast_ip4,
+ src_port=self.dport,
+ dst_port=self.dport,
+ mcast_sw_if_index=1,
+ vni=self.mcast_flood_bd,
+ )
r.add_vpp_config()
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=self.mcast_flood_bd)
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd)
+ rx_sw_if_index=r.sw_if_index, bd_id=self.mcast_flood_bd
+ )
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd
+ )
# Add and delete mcast tunnels to check stability
self.add_shared_mcast_dst_load(self.dport)
@@ -240,11 +276,12 @@ class TestVxlan(BridgeDomain, VppTestCase):
# Setup vni 3 to test unicast flooding
self.ucast_flood_bd = 3
- self.create_vxlan_flood_test_bd(self.ucast_flood_bd,
- self.n_ucast_tunnels,
- self.dport)
+ self.create_vxlan_flood_test_bd(
+ self.ucast_flood_bd, self.n_ucast_tunnels, self.dport
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd)
+ rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd
+ )
# Set scapy listen custom port for VxLAN
bind_layers(UDP, VXLAN, dport=self.dport)
@@ -252,10 +289,12 @@ class TestVxlan(BridgeDomain, VppTestCase):
def encap_big_packet(self):
self.vapi.sw_interface_set_mtu(self.pg0.sw_if_index, [1500, 0, 0, 0])
- frame = (Ether(src='00:00:00:00:00:02', dst='00:00:00:00:00:01') /
- IP(src='4.3.2.1', dst='1.2.3.4') /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 1450))
+ frame = (
+ Ether(src="00:00:00:00:00:02", dst="00:00:00:00:00:01")
+ / IP(src="4.3.2.1", dst="1.2.3.4")
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 1450)
+ )
self.pg1.add_stream([frame])
@@ -277,43 +316,44 @@ class TestVxlan(BridgeDomain, VppTestCase):
"""
Tests with default port (4789)
"""
+
def test_decap(self):
- """ Decapsulation test
+ """Decapsulation test
from BridgeDoman
"""
self.createVxLANInterfaces()
super(TestVxlan, self).test_decap()
def test_encap(self):
- """ Encapsulation test
+ """Encapsulation test
from BridgeDoman
"""
self.createVxLANInterfaces()
super(TestVxlan, self).test_encap()
def test_encap_big_packet(self):
- """ Encapsulation test send big frame from pg1
+ """Encapsulation test send big frame from pg1
Verify receipt of encapsulated frames on pg0
"""
self.createVxLANInterfaces()
self.encap_big_packet()
def test_ucast_flood(self):
- """ Unicast flood test
+ """Unicast flood test
from BridgeDoman
"""
self.createVxLANInterfaces()
super(TestVxlan, self).test_ucast_flood()
def test_mcast_flood(self):
- """ Multicast flood test
+ """Multicast flood test
from BridgeDoman
"""
self.createVxLANInterfaces()
super(TestVxlan, self).test_mcast_flood()
def test_mcast_rcv(self):
- """ Multicast receive test
+ """Multicast receive test
from BridgeDoman
"""
self.createVxLANInterfaces()
@@ -322,36 +362,37 @@ class TestVxlan(BridgeDomain, VppTestCase):
"""
Tests with custom port
"""
+
def test_decap_custom_port(self):
- """ Decapsulation test custom port
+ """Decapsulation test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1111)
super(TestVxlan, self).test_decap()
def test_encap_custom_port(self):
- """ Encapsulation test custom port
+ """Encapsulation test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1111)
super(TestVxlan, self).test_encap()
def test_ucast_flood_custom_port(self):
- """ Unicast flood test custom port
+ """Unicast flood test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1111)
super(TestVxlan, self).test_ucast_flood()
def test_mcast_flood_custom_port(self):
- """ Multicast flood test custom port
+ """Multicast flood test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1111)
super(TestVxlan, self).test_mcast_flood()
def test_mcast_rcv_custom_port(self):
- """ Multicast receive test custom port
+ """Multicast receive test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1111)
@@ -372,7 +413,8 @@ class TestVxlan(BridgeDomain, VppTestCase):
class TestVxlan2(VppTestCase):
- """ VXLAN Test Case """
+ """VXLAN Test Case"""
+
def setUp(self):
super(TestVxlan2, self).setUp()
@@ -389,38 +431,37 @@ class TestVxlan2(VppTestCase):
super(TestVxlan2, self).tearDown()
def test_xconnect(self):
- """ VXLAN source address not local """
+ """VXLAN source address not local"""
#
# test the broken configuration of a VXLAN tunnel whose
# source address is not local ot the box. packets sent
# through the tunnel should be dropped
#
- t = VppVxlanTunnel(self,
- src="10.0.0.5",
- dst=self.pg0.local_ip4,
- vni=1000)
+ t = VppVxlanTunnel(self, src="10.0.0.5", dst=self.pg0.local_ip4, vni=1000)
t.add_vpp_config()
t.admin_up()
- self.vapi.sw_interface_set_l2_xconnect(t.sw_if_index,
- self.pg1.sw_if_index,
- enable=1)
- self.vapi.sw_interface_set_l2_xconnect(self.pg1.sw_if_index,
- t.sw_if_index,
- enable=1)
+ self.vapi.sw_interface_set_l2_xconnect(
+ t.sw_if_index, self.pg1.sw_if_index, enable=1
+ )
+ self.vapi.sw_interface_set_l2_xconnect(
+ self.pg1.sw_if_index, t.sw_if_index, enable=1
+ )
- p = (Ether(src="00:11:22:33:44:55",
- dst="00:00:00:11:22:33") /
- IP(src="4.3.2.1", dst="1.2.3.4") /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 1450))
+ p = (
+ Ether(src="00:11:22:33:44:55", dst="00:00:00:11:22:33")
+ / IP(src="4.3.2.1", dst="1.2.3.4")
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 1450)
+ )
rx = self.send_and_assert_no_replies(self.pg1, [p])
class TestVxlanL2Mode(VppTestCase):
- """ VXLAN Test Case """
+ """VXLAN Test Case"""
+
def setUp(self):
super(TestVxlanL2Mode, self).setUp()
@@ -440,11 +481,10 @@ class TestVxlanL2Mode(VppTestCase):
super(TestVxlanL2Mode, self).tearDown()
def test_l2_mode(self):
- """ VXLAN L2 mode """
- t = VppVxlanTunnel(self,
- src=self.pg0.local_ip4,
- dst=self.pg0.remote_ip4,
- vni=1000, is_l3=False)
+ """VXLAN L2 mode"""
+ t = VppVxlanTunnel(
+ self, src=self.pg0.local_ip4, dst=self.pg0.remote_ip4, vni=1000, is_l3=False
+ )
t.add_vpp_config()
t.config_ip4()
t.admin_up()
@@ -452,10 +492,12 @@ class TestVxlanL2Mode(VppTestCase):
dstIP = t.local_ip4[:-1] + "2"
# Create a packet to send
- p = (Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac) /
- IP(src=self.pg1.local_ip4, dst=dstIP) /
- UDP(sport=555, dport=556) /
- Raw(b'\x00' * 80))
+ p = (
+ Ether(dst=self.pg1.local_mac, src=self.pg1.remote_mac)
+ / IP(src=self.pg1.local_ip4, dst=dstIP)
+ / UDP(sport=555, dport=556)
+ / Raw(b"\x00" * 80)
+ )
# Expect ARP request
rx = self.send_and_expect(self.pg1, [p], self.pg0)
@@ -466,9 +508,7 @@ class TestVxlanL2Mode(VppTestCase):
self.assertEqual(p[ARP].pdst, dstIP)
# Resolve ARP
- VppNeighbor(self, t.sw_if_index,
- self.pg1.remote_mac,
- dstIP).add_vpp_config()
+ VppNeighbor(self, t.sw_if_index, self.pg1.remote_mac, dstIP).add_vpp_config()
# Send packets
NUM_PKTS = 128
@@ -476,5 +516,5 @@ class TestVxlanL2Mode(VppTestCase):
self.assertEqual(NUM_PKTS, len(rx))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_vxlan6.py b/test/test_vxlan6.py
index 123cce9b7ba..0f9c5121f6d 100644
--- a/test/test_vxlan6.py
+++ b/test/test_vxlan6.py
@@ -17,7 +17,7 @@ from vpp_ip import INVALID_INDEX
class TestVxlan6(BridgeDomain, VppTestCase):
- """ VXLAN over IPv6 Test Case """
+ """VXLAN over IPv6 Test Case"""
def __init__(self, *args):
BridgeDomain.__init__(self)
@@ -28,16 +28,18 @@ class TestVxlan6(BridgeDomain, VppTestCase):
Encapsulate the original payload frame by adding VXLAN header with its
UDP, IP and Ethernet fields
"""
- return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6) /
- UDP(sport=self.dport, dport=self.dport, chksum=0) /
- VXLAN(vni=vni, flags=self.flags) /
- pkt)
+ return (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst=self.pg0.local_ip6)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ / VXLAN(vni=vni, flags=self.flags)
+ / pkt
+ )
@classmethod
def ip_range(cls, s, e):
- """ range of remote ip's """
- tmp = cls.pg0.remote_ip6.rsplit(':', 1)[0]
+ """range of remote ip's"""
+ tmp = cls.pg0.remote_ip6.rsplit(":", 1)[0]
return ("%s:%x" % (tmp, i) for i in range(s, e))
def encap_mcast(self, pkt, src_ip, src_mac, vni):
@@ -45,18 +47,20 @@ class TestVxlan6(BridgeDomain, VppTestCase):
Encapsulate the original payload frame by adding VXLAN header with its
UDP, IP and Ethernet fields
"""
- return (Ether(src=src_mac, dst=self.mcast_mac) /
- IPv6(src=src_ip, dst=self.mcast_ip6) /
- UDP(sport=self.dport, dport=self.dport, chksum=0) /
- VXLAN(vni=vni, flags=self.flags) /
- pkt)
+ return (
+ Ether(src=src_mac, dst=self.mcast_mac)
+ / IPv6(src=src_ip, dst=self.mcast_ip6)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ / VXLAN(vni=vni, flags=self.flags)
+ / pkt
+ )
def decapsulate(self, pkt):
"""
Decapsulate the original payload frame by removing VXLAN header
"""
# check if is set I flag
- self.assertEqual(pkt[VXLAN].flags, int('0x8', 16))
+ self.assertEqual(pkt[VXLAN].flags, int("0x8", 16))
return pkt[VXLAN].payload
# Method for checking VXLAN encapsulation.
@@ -93,13 +97,22 @@ class TestVxlan6(BridgeDomain, VppTestCase):
end = start + n_ucast_tunnels
for dest_ip6 in cls.ip_range(start, end):
# add host route so dest ip will not be resolved
- rip = VppIpRoute(cls, dest_ip6, 128,
- [VppRoutePath(cls.pg0.remote_ip6, INVALID_INDEX)],
- register=False)
+ rip = VppIpRoute(
+ cls,
+ dest_ip6,
+ 128,
+ [VppRoutePath(cls.pg0.remote_ip6, INVALID_INDEX)],
+ register=False,
+ )
rip.add_vpp_config()
- r = VppVxlanTunnel(cls, src=cls.pg0.local_ip6,
- src_port=port, dst_port=port,
- dst=dest_ip6, vni=vni)
+ r = VppVxlanTunnel(
+ cls,
+ src=cls.pg0.local_ip6,
+ src_port=port,
+ dst_port=port,
+ dst=dest_ip6,
+ vni=vni,
+ )
r.add_vpp_config()
cls.vapi.sw_interface_set_l2_bridge(r.sw_if_index, bd_id=vni)
@@ -135,7 +148,7 @@ class TestVxlan6(BridgeDomain, VppTestCase):
cls.pg0.resolve_ndp()
# Our Multicast address
- cls.mcast_ip6 = 'ff0e::1'
+ cls.mcast_ip6 = "ff0e::1"
cls.mcast_mac = util.mcast_ip_to_mac(cls.mcast_ip6)
except Exception:
super(TestVxlan6, cls).tearDownClass()
@@ -155,38 +168,53 @@ class TestVxlan6(BridgeDomain, VppTestCase):
self.single_tunnel_vni = 0x12345
self.single_tunnel_bd = 1
- r = VppVxlanTunnel(self, src=self.pg0.local_ip6,
- dst=self.pg0.remote_ip6,
- src_port=self.dport, dst_port=self.dport,
- vni=self.single_tunnel_vni)
+ r = VppVxlanTunnel(
+ self,
+ src=self.pg0.local_ip6,
+ dst=self.pg0.remote_ip6,
+ src_port=self.dport,
+ dst_port=self.dport,
+ vni=self.single_tunnel_vni,
+ )
r.add_vpp_config()
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=self.single_tunnel_bd)
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd)
+ rx_sw_if_index=r.sw_if_index, bd_id=self.single_tunnel_bd
+ )
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd
+ )
# Setup vni 2 to test multicast flooding
self.n_ucast_tunnels = 10
self.mcast_flood_bd = 2
- self.create_vxlan_flood_test_bd(self.mcast_flood_bd,
- self.n_ucast_tunnels,
- self.dport)
- r = VppVxlanTunnel(self, src=self.pg0.local_ip6, dst=self.mcast_ip6,
- src_port=self.dport, dst_port=self.dport,
- mcast_sw_if_index=1, vni=self.mcast_flood_bd)
+ self.create_vxlan_flood_test_bd(
+ self.mcast_flood_bd, self.n_ucast_tunnels, self.dport
+ )
+ r = VppVxlanTunnel(
+ self,
+ src=self.pg0.local_ip6,
+ dst=self.mcast_ip6,
+ src_port=self.dport,
+ dst_port=self.dport,
+ mcast_sw_if_index=1,
+ vni=self.mcast_flood_bd,
+ )
r.add_vpp_config()
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=self.mcast_flood_bd)
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd)
+ rx_sw_if_index=r.sw_if_index, bd_id=self.mcast_flood_bd
+ )
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd
+ )
# Setup vni 3 to test unicast flooding
self.ucast_flood_bd = 3
- self.create_vxlan_flood_test_bd(self.ucast_flood_bd,
- self.n_ucast_tunnels,
- self.dport)
+ self.create_vxlan_flood_test_bd(
+ self.ucast_flood_bd, self.n_ucast_tunnels, self.dport
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd)
+ rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd
+ )
# Set scapy listen custom port for VxLAN
bind_layers(UDP, VXLAN, dport=self.dport)
@@ -204,10 +232,12 @@ class TestVxlan6(BridgeDomain, VppTestCase):
self.logger.info(self.vapi.cli("show vxlan tunnel"))
def encap_fragmented_packet(self):
- frame = (Ether(src='00:00:00:00:00:02', dst='00:00:00:00:00:01') /
- IP(src='4.3.2.1', dst='1.2.3.4') /
- UDP(sport=20000, dport=10000) /
- Raw(b'\xa5' * 1000))
+ frame = (
+ Ether(src="00:00:00:00:00:02", dst="00:00:00:00:00:01")
+ / IP(src="4.3.2.1", dst="1.2.3.4")
+ / UDP(sport=20000, dport=10000)
+ / Raw(b"\xa5" * 1000)
+ )
frags = util.fragment_rfc791(frame, 400)
@@ -231,43 +261,44 @@ class TestVxlan6(BridgeDomain, VppTestCase):
"""
Tests with default port (4789)
"""
+
def test_decap(self):
- """ Decapsulation test
+ """Decapsulation test
from BridgeDoman
"""
self.createVxLANInterfaces()
super(TestVxlan6, self).test_decap()
def test_encap(self):
- """ Encapsulation test
+ """Encapsulation test
from BridgeDoman
"""
self.createVxLANInterfaces()
super(TestVxlan6, self).test_encap()
def test_encap_fragmented_packet(self):
- """ Encapsulation test send fragments from pg1
+ """Encapsulation test send fragments from pg1
Verify receipt of encapsulated frames on pg0
"""
self.createVxLANInterfaces()
self.encap_fragmented_packet()
def test_ucast_flood(self):
- """ Unicast flood test
+ """Unicast flood test
from BridgeDoman
"""
self.createVxLANInterfaces()
super(TestVxlan6, self).test_ucast_flood()
def test_mcast_flood(self):
- """ Multicast flood test
+ """Multicast flood test
from BridgeDoman
"""
self.createVxLANInterfaces()
super(TestVxlan6, self).test_mcast_flood()
def test_mcast_rcv(self):
- """ Multicast receive test
+ """Multicast receive test
from BridgeDoman
"""
self.createVxLANInterfaces()
@@ -276,41 +307,42 @@ class TestVxlan6(BridgeDomain, VppTestCase):
"""
Tests with custom port
"""
+
def test_decap_custom_port(self):
- """ Decapsulation test custom port
+ """Decapsulation test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1111)
super(TestVxlan6, self).test_decap()
def test_encap_custom_port(self):
- """ Encapsulation test custom port
+ """Encapsulation test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1111)
super(TestVxlan6, self).test_encap()
def test_ucast_flood_custom_port(self):
- """ Unicast flood test custom port
+ """Unicast flood test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1111)
super(TestVxlan6, self).test_ucast_flood()
def test_mcast_flood_custom_port(self):
- """ Multicast flood test custom port
+ """Multicast flood test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1111)
super(TestVxlan6, self).test_mcast_flood()
def test_mcast_rcv_custom_port(self):
- """ Multicast receive test custom port
+ """Multicast receive test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1111)
super(TestVxlan6, self).test_mcast_rcv()
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_vxlan_gpe.py b/test/test_vxlan_gpe.py
index 828b5fc30cd..f432becfce3 100644
--- a/test/test_vxlan_gpe.py
+++ b/test/test_vxlan_gpe.py
@@ -20,7 +20,7 @@ from vpp_ip import INVALID_INDEX
@unittest.skipUnless(config.extended, "part of extended tests")
class TestVxlanGpe(BridgeDomain, VppTestCase):
- """ VXLAN-GPE Test Case """
+ """VXLAN-GPE Test Case"""
def __init__(self, *args):
BridgeDomain.__init__(self)
@@ -31,14 +31,16 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
Encapsulate the original payload frame by adding VXLAN-GPE header
with its UDP, IP and Ethernet fields
"""
- return (Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac) /
- IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4) /
- UDP(sport=self.dport, dport=self.dport, chksum=0) /
- VXLAN(vni=vni, flags=self.flags) /
- pkt)
+ return (
+ Ether(src=self.pg0.remote_mac, dst=self.pg0.local_mac)
+ / IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ / VXLAN(vni=vni, flags=self.flags)
+ / pkt
+ )
def ip_range(self, start, end):
- """ range of remote ip's """
+ """range of remote ip's"""
return ip4_range(self.pg0.remote_ip4, start, end)
def encap_mcast(self, pkt, src_ip, src_mac, vni):
@@ -46,18 +48,20 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
Encapsulate the original payload frame by adding VXLAN-GPE header
with its UDP, IP and Ethernet fields
"""
- return (Ether(src=src_mac, dst=self.mcast_mac) /
- IP(src=src_ip, dst=self.mcast_ip4) /
- UDP(sport=self.dport, dport=self.dport, chksum=0) /
- VXLAN(vni=vni, flags=self.flags) /
- pkt)
+ return (
+ Ether(src=src_mac, dst=self.mcast_mac)
+ / IP(src=src_ip, dst=self.mcast_ip4)
+ / UDP(sport=self.dport, dport=self.dport, chksum=0)
+ / VXLAN(vni=vni, flags=self.flags)
+ / pkt
+ )
def decapsulate(self, pkt):
"""
Decapsulate the original payload frame by removing VXLAN-GPE header
"""
# check if is set I and P flag
- self.assertEqual(pkt[VXLAN].flags, 0x0c)
+ self.assertEqual(pkt[VXLAN].flags, 0x0C)
return pkt[VXLAN].payload
# Method for checking VXLAN-GPE encapsulation.
@@ -92,24 +96,27 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
ip_range_start = 10
ip_range_end = ip_range_start + n_ucast_tunnels
next_hop_address = cls.pg0.remote_ip4
- for dest_ip4 in ip4_range(next_hop_address, ip_range_start,
- ip_range_end):
+ for dest_ip4 in ip4_range(next_hop_address, ip_range_start, ip_range_end):
# add host route so dest_ip4n will not be resolved
- rip = VppIpRoute(cls, dest_ip4, 32,
- [VppRoutePath(next_hop_address,
- INVALID_INDEX)],
- register=False)
+ rip = VppIpRoute(
+ cls,
+ dest_ip4,
+ 32,
+ [VppRoutePath(next_hop_address, INVALID_INDEX)],
+ register=False,
+ )
rip.add_vpp_config()
- r = VppVxlanGpeTunnel(cls,
- src_addr=cls.pg0.local_ip4,
- dst_addr=dest_ip4,
- src_port=port,
- dst_port=port,
- vni=vni)
+ r = VppVxlanGpeTunnel(
+ cls,
+ src_addr=cls.pg0.local_ip4,
+ dst_addr=dest_ip4,
+ src_port=port,
+ dst_port=port,
+ vni=vni,
+ )
r.add_vpp_config()
- cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=vni)
+ cls.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index, bd_id=vni)
@classmethod
def add_del_shared_mcast_dst_load(cls, port, is_add):
@@ -121,16 +128,18 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
vni_start = 1000
vni_end = vni_start + n_shared_dst_tunnels
for vni in range(vni_start, vni_end):
- r = VppVxlanGpeTunnel(cls,
- src_addr=cls.pg0.local_ip4,
- dst_addr=cls.mcast_ip4,
- src_port=port,
- dst_port=port,
- mcast_sw_if_index=1,
- vni=vni)
+ r = VppVxlanGpeTunnel(
+ cls,
+ src_addr=cls.pg0.local_ip4,
+ dst_addr=cls.mcast_ip4,
+ src_port=port,
+ dst_port=port,
+ mcast_sw_if_index=1,
+ vni=vni,
+ )
if is_add:
r.add_vpp_config()
- if r.sw_if_index == 0xffffffff:
+ if r.sw_if_index == 0xFFFFFFFF:
raise ValueError("bad sw_if_index: ~0")
else:
r.remove_vpp_config()
@@ -151,16 +160,17 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
n_distinct_dst_tunnels = 20
ip_range_start = 10
ip_range_end = ip_range_start + n_distinct_dst_tunnels
- for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start,
- ip_range_end):
+ for dest_ip4 in ip4_range(cls.mcast_ip4, ip_range_start, ip_range_end):
vni = int(dest_ip4.split(".")[3])
- r = VppVxlanGpeTunnel(cls,
- src_addr=cls.pg0.local_ip4,
- dst_addr=dest_ip4,
- src_port=port,
- dst_port=port,
- mcast_sw_if_index=1,
- vni=vni)
+ r = VppVxlanGpeTunnel(
+ cls,
+ src_addr=cls.pg0.local_ip4,
+ dst_addr=dest_ip4,
+ src_port=port,
+ dst_port=port,
+ mcast_sw_if_index=1,
+ vni=vni,
+ )
if is_add:
r.add_vpp_config()
else:
@@ -184,7 +194,7 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
super(TestVxlanGpe, cls).setUpClass()
try:
- cls.flags = 0x0c
+ cls.flags = 0x0C
# Create 2 pg interfaces.
cls.create_pg_interfaces(range(4))
@@ -198,7 +208,7 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
cls.pg0.resolve_arp()
# Our Multicast address
- cls.mcast_ip4 = '239.1.1.1'
+ cls.mcast_ip4 = "239.1.1.1"
cls.mcast_mac = util.mcast_ip_to_mac(cls.mcast_ip4)
except Exception:
cls.tearDownClass()
@@ -216,38 +226,46 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
# and pg1 into BD.
self.dport = port
- self.single_tunnel_vni = 0xabcde
+ self.single_tunnel_vni = 0xABCDE
self.single_tunnel_bd = 11
- r = VppVxlanGpeTunnel(self,
- src_addr=self.pg0.local_ip4,
- dst_addr=self.pg0.remote_ip4,
- src_port=port,
- dst_port=port,
- vni=self.single_tunnel_vni)
+ r = VppVxlanGpeTunnel(
+ self,
+ src_addr=self.pg0.local_ip4,
+ dst_addr=self.pg0.remote_ip4,
+ src_port=port,
+ dst_port=port,
+ vni=self.single_tunnel_vni,
+ )
r.add_vpp_config()
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=self.single_tunnel_bd)
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd)
+ rx_sw_if_index=r.sw_if_index, bd_id=self.single_tunnel_bd
+ )
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=self.pg1.sw_if_index, bd_id=self.single_tunnel_bd
+ )
# Setup vni 2 to test multicast flooding
self.n_ucast_tunnels = 10
self.mcast_flood_bd = 12
- self.create_vxlan_gpe_flood_test_bd(self.mcast_flood_bd,
- self.n_ucast_tunnels,
- self.dport)
- r = VppVxlanGpeTunnel(self,
- src_addr=self.pg0.local_ip4,
- dst_addr=self.mcast_ip4,
- src_port=port,
- dst_port=port,
- mcast_sw_if_index=1,
- vni=self.mcast_flood_bd)
+ self.create_vxlan_gpe_flood_test_bd(
+ self.mcast_flood_bd, self.n_ucast_tunnels, self.dport
+ )
+ r = VppVxlanGpeTunnel(
+ self,
+ src_addr=self.pg0.local_ip4,
+ dst_addr=self.mcast_ip4,
+ src_port=port,
+ dst_port=port,
+ mcast_sw_if_index=1,
+ vni=self.mcast_flood_bd,
+ )
r.add_vpp_config()
- self.vapi.sw_interface_set_l2_bridge(rx_sw_if_index=r.sw_if_index,
- bd_id=self.mcast_flood_bd)
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd)
+ rx_sw_if_index=r.sw_if_index, bd_id=self.mcast_flood_bd
+ )
+ self.vapi.sw_interface_set_l2_bridge(
+ rx_sw_if_index=self.pg2.sw_if_index, bd_id=self.mcast_flood_bd
+ )
# Add and delete mcast tunnels to check stability
self.add_shared_mcast_dst_load(self.dport)
@@ -257,11 +275,12 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
# Setup vni 3 to test unicast flooding
self.ucast_flood_bd = 13
- self.create_vxlan_gpe_flood_test_bd(self.ucast_flood_bd,
- self.n_ucast_tunnels,
- self.dport)
+ self.create_vxlan_gpe_flood_test_bd(
+ self.ucast_flood_bd, self.n_ucast_tunnels, self.dport
+ )
self.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd)
+ rx_sw_if_index=self.pg3.sw_if_index, bd_id=self.ucast_flood_bd
+ )
# Set scapy listen custom port for VxLAN
bind_layers(UDP, VXLAN, dport=self.dport)
@@ -269,22 +288,23 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
"""
Tests with default port (4790)
"""
+
def test_decap(self):
- """ Decapsulation test
+ """Decapsulation test
from BridgeDoman
"""
self.createVxLANInterfaces()
super(TestVxlanGpe, self).test_decap()
def test_encap(self):
- """ Encapsulation test
+ """Encapsulation test
from BridgeDoman
"""
self.createVxLANInterfaces()
super(TestVxlanGpe, self).test_encap()
def test_ucast_flood(self):
- """ Unicast flood test
+ """Unicast flood test
from BridgeDoman
"""
self.createVxLANInterfaces()
@@ -293,22 +313,23 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
"""
Tests with custom port (1112)
"""
+
def test_decap_custom_port(self):
- """ Decapsulation test custom port
+ """Decapsulation test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1112)
super(TestVxlanGpe, self).test_decap()
def test_encap_custom_port(self):
- """ Encapsulation test custom port
+ """Encapsulation test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1112)
super(TestVxlanGpe, self).test_encap()
def test_ucast_flood_custom_port(self):
- """ Unicast flood test custom port
+ """Unicast flood test custom port
from BridgeDoman
"""
self.createVxLANInterfaces(1112)
@@ -316,12 +337,12 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
@unittest.skip("test disabled for vxlan-gpe")
def test_mcast_flood(self):
- """ inherited from BridgeDomain """
+ """inherited from BridgeDomain"""
pass
@unittest.skip("test disabled for vxlan-gpe")
def test_mcast_rcv(self):
- """ inherited from BridgeDomain """
+ """inherited from BridgeDomain"""
pass
# Method to define VPP actions before tear down of the test case.
@@ -339,5 +360,5 @@ class TestVxlanGpe(BridgeDomain, VppTestCase):
self.logger.info(self.vapi.cli("show trace"))
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main(testRunner=VppTestRunner)
diff --git a/test/test_wireguard.py b/test/test_wireguard.py
index e844b1d5c0a..1a955b162f1 100644
--- a/test/test_wireguard.py
+++ b/test/test_wireguard.py
@@ -11,12 +11,22 @@ from scapy.packet import Raw
from scapy.layers.l2 import Ether, ARP
from scapy.layers.inet import IP, UDP
from scapy.layers.inet6 import IPv6
-from scapy.contrib.wireguard import Wireguard, WireguardResponse, \
- WireguardInitiation, WireguardTransport
-from cryptography.hazmat.primitives.asymmetric.x25519 import \
- X25519PrivateKey, X25519PublicKey
-from cryptography.hazmat.primitives.serialization import Encoding, \
- PrivateFormat, PublicFormat, NoEncryption
+from scapy.contrib.wireguard import (
+ Wireguard,
+ WireguardResponse,
+ WireguardInitiation,
+ WireguardTransport,
+)
+from cryptography.hazmat.primitives.asymmetric.x25519 import (
+ X25519PrivateKey,
+ X25519PublicKey,
+)
+from cryptography.hazmat.primitives.serialization import (
+ Encoding,
+ PrivateFormat,
+ PublicFormat,
+ NoEncryption,
+)
from cryptography.hazmat.primitives.hashes import BLAKE2s, Hash
from cryptography.hazmat.primitives.hmac import HMAC
from cryptography.hazmat.backends import default_backend
@@ -39,14 +49,11 @@ Wg test.
def private_key_bytes(k):
- return k.private_bytes(Encoding.Raw,
- PrivateFormat.Raw,
- NoEncryption())
+ return k.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
def public_key_bytes(k):
- return k.public_bytes(Encoding.Raw,
- PublicFormat.Raw)
+ return k.public_bytes(Encoding.Raw, PublicFormat.Raw)
class VppWgInterface(VppInterface):
@@ -69,37 +76,41 @@ class VppWgInterface(VppInterface):
return private_key_bytes(self.private_key)
def add_vpp_config(self):
- r = self.test.vapi.wireguard_interface_create(interface={
- 'user_instance': 0xffffffff,
- 'port': self.port,
- 'src_ip': self.src,
- 'private_key': private_key_bytes(self.private_key),
- 'generate_key': False
- })
+ r = self.test.vapi.wireguard_interface_create(
+ interface={
+ "user_instance": 0xFFFFFFFF,
+ "port": self.port,
+ "src_ip": self.src,
+ "private_key": private_key_bytes(self.private_key),
+ "generate_key": False,
+ }
+ )
self.set_sw_if_index(r.sw_if_index)
self.test.registry.register(self, self.test.logger)
return self
def remove_vpp_config(self):
- self.test.vapi.wireguard_interface_delete(
- sw_if_index=self._sw_if_index)
+ self.test.vapi.wireguard_interface_delete(sw_if_index=self._sw_if_index)
def query_vpp_config(self):
- ts = self.test.vapi.wireguard_interface_dump(sw_if_index=0xffffffff)
+ ts = self.test.vapi.wireguard_interface_dump(sw_if_index=0xFFFFFFFF)
for t in ts:
- if t.interface.sw_if_index == self._sw_if_index and \
- str(t.interface.src_ip) == self.src and \
- t.interface.port == self.port and \
- t.interface.private_key == private_key_bytes(self.private_key):
+ if (
+ t.interface.sw_if_index == self._sw_if_index
+ and str(t.interface.src_ip) == self.src
+ and t.interface.port == self.port
+ and t.interface.private_key == private_key_bytes(self.private_key)
+ ):
return True
return False
- def want_events(self, peer_index=0xffffffff):
+ def want_events(self, peer_index=0xFFFFFFFF):
self.test.vapi.want_wireguard_peer_events(
enable_disable=1,
pid=os.getpid(),
sw_if_index=self._sw_if_index,
- peer_index=peer_index)
+ peer_index=peer_index,
+ )
def wait_events(self, expect, peers, timeout=5):
for i in range(len(peers)):
@@ -118,8 +129,7 @@ def find_route(test, prefix, is_ip6, table_id=0):
routes = test.vapi.ip_route_dump(table_id, is_ip6)
for e in routes:
- if table_id == e.route.table_id \
- and str(e.route.prefix) == str(prefix):
+ if table_id == e.route.table_id and str(e.route.prefix) == str(prefix):
return True
return False
@@ -129,14 +139,7 @@ NOISE_IDENTIFIER_NAME = b"WireGuard v1 zx2c4 Jason@zx2c4.com"
class VppWgPeer(VppObject):
-
- def __init__(self,
- test,
- itf,
- endpoint,
- port,
- allowed_ips,
- persistent_keepalive=15):
+ def __init__(self, test, itf, endpoint, port, allowed_ips, persistent_keepalive=15):
self._test = test
self.itf = itf
self.endpoint = endpoint
@@ -153,13 +156,15 @@ class VppWgPeer(VppObject):
def add_vpp_config(self, is_ip6=False):
rv = self._test.vapi.wireguard_peer_add(
peer={
- 'public_key': self.public_key_bytes(),
- 'port': self.port,
- 'endpoint': self.endpoint,
- 'n_allowed_ips': len(self.allowed_ips),
- 'allowed_ips': self.allowed_ips,
- 'sw_if_index': self.itf.sw_if_index,
- 'persistent_keepalive': self.persistent_keepalive})
+ "public_key": self.public_key_bytes(),
+ "port": self.port,
+ "endpoint": self.endpoint,
+ "n_allowed_ips": len(self.allowed_ips),
+ "allowed_ips": self.allowed_ips,
+ "sw_if_index": self.itf.sw_if_index,
+ "persistent_keepalive": self.persistent_keepalive,
+ }
+ )
self.index = rv.peer_index
self.receiver_index = self.index + 1
self._test.registry.register(self, self._test.logger)
@@ -169,7 +174,7 @@ class VppWgPeer(VppObject):
self._test.vapi.wireguard_peer_remove(peer_index=self.index)
def object_id(self):
- return ("wireguard-peer-%s" % self.index)
+ return "wireguard-peer-%s" % self.index
def public_key_bytes(self):
return public_key_bytes(self.public_key)
@@ -178,11 +183,13 @@ class VppWgPeer(VppObject):
peers = self._test.vapi.wireguard_peers_dump()
for p in peers:
- if p.peer.public_key == self.public_key_bytes() and \
- p.peer.port == self.port and \
- str(p.peer.endpoint) == self.endpoint and \
- p.peer.sw_if_index == self.itf.sw_if_index and \
- len(self.allowed_ips) == p.peer.n_allowed_ips:
+ if (
+ p.peer.public_key == self.public_key_bytes()
+ and p.peer.port == self.port
+ and str(p.peer.endpoint) == self.endpoint
+ and p.peer.sw_if_index == self.itf.sw_if_index
+ and len(self.allowed_ips) == p.peer.n_allowed_ips
+ ):
self.allowed_ips.sort()
p.peer.allowed_ips.sort()
@@ -197,13 +204,17 @@ class VppWgPeer(VppObject):
def mk_tunnel_header(self, tx_itf, is_ip6=False):
if is_ip6 is False:
- return (Ether(dst=tx_itf.local_mac, src=tx_itf.remote_mac) /
- IP(src=self.endpoint, dst=self.itf.src) /
- UDP(sport=self.port, dport=self.itf.port))
+ return (
+ Ether(dst=tx_itf.local_mac, src=tx_itf.remote_mac)
+ / IP(src=self.endpoint, dst=self.itf.src)
+ / UDP(sport=self.port, dport=self.itf.port)
+ )
else:
- return (Ether(dst=tx_itf.local_mac, src=tx_itf.remote_mac) /
- IPv6(src=self.endpoint, dst=self.itf.src) /
- UDP(sport=self.port, dport=self.itf.port))
+ return (
+ Ether(dst=tx_itf.local_mac, src=tx_itf.remote_mac)
+ / IPv6(src=self.endpoint, dst=self.itf.src)
+ / UDP(sport=self.port, dport=self.itf.port)
+ )
def noise_init(self, public_key=None):
self.noise.set_prologue(NOISE_IDENTIFIER_NAME)
@@ -214,12 +225,12 @@ class VppWgPeer(VppObject):
# local/this private
self.noise.set_keypair_from_private_bytes(
- Keypair.STATIC,
- private_key_bytes(self.private_key))
+ Keypair.STATIC, private_key_bytes(self.private_key)
+ )
# remote's public
self.noise.set_keypair_from_public_bytes(
- Keypair.REMOTE_STATIC,
- public_key_bytes(public_key))
+ Keypair.REMOTE_STATIC, public_key_bytes(public_key)
+ )
self.noise.start_handshake()
@@ -227,7 +238,7 @@ class VppWgPeer(VppObject):
self.noise.set_as_initiator()
self.noise_init(public_key)
- p = (Wireguard() / WireguardInitiation())
+ p = Wireguard() / WireguardInitiation()
p[Wireguard].message_type = 1
p[Wireguard].reserved_zero = 0
@@ -236,8 +247,11 @@ class VppWgPeer(VppObject):
# some random data for the message
# lifted from the noise protocol's wireguard example
now = datetime.datetime.now()
- tai = struct.pack('!qi', 4611686018427387914 + int(now.timestamp()),
- int(now.microsecond * 1e3))
+ tai = struct.pack(
+ "!qi",
+ 4611686018427387914 + int(now.timestamp()),
+ int(now.microsecond * 1e3),
+ )
b = self.noise.write_message(payload=tai)
# load noise into init message
@@ -246,14 +260,13 @@ class VppWgPeer(VppObject):
p[WireguardInitiation].encrypted_timestamp = b[80:108]
# generate the mac1 hash
- mac_key = blake2s(b'mac1----' +
- self.itf.public_key_bytes()).digest()
- p[WireguardInitiation].mac1 = blake2s(bytes(p)[0:116],
- digest_size=16,
- key=mac_key).digest()
+ mac_key = blake2s(b"mac1----" + self.itf.public_key_bytes()).digest()
+ p[WireguardInitiation].mac1 = blake2s(
+ bytes(p)[0:116], digest_size=16, key=mac_key
+ ).digest()
p[WireguardInitiation].mac2 = bytearray(16)
- p = (self.mk_tunnel_header(tx_itf, is_ip6) / p)
+ p = self.mk_tunnel_header(tx_itf, is_ip6) / p
return p
@@ -281,11 +294,8 @@ class VppWgPeer(VppObject):
self.sender = init[WireguardInitiation].sender_index
# validate the hash
- mac_key = blake2s(b'mac1----' +
- public_key_bytes(self.public_key)).digest()
- mac1 = blake2s(bytes(init)[0:-32],
- digest_size=16,
- key=mac_key).digest()
+ mac_key = blake2s(b"mac1----" + public_key_bytes(self.public_key)).digest()
+ mac1 = blake2s(bytes(init)[0:-32], digest_size=16, key=mac_key).digest()
self._test.assertEqual(init[WireguardInitiation].mac1, mac1)
# this passes only unencrypted_ephemeral, encrypted_static,
@@ -294,19 +304,17 @@ class VppWgPeer(VppObject):
# build the response
b = self.noise.write_message()
- mac_key = blake2s(b'mac1----' +
- public_key_bytes(self.itf.public_key)).digest()
- resp = (Wireguard(message_type=2, reserved_zero=0) /
- WireguardResponse(sender_index=self.receiver_index,
- receiver_index=self.sender,
- unencrypted_ephemeral=b[0:32],
- encrypted_nothing=b[32:]))
- mac1 = blake2s(bytes(resp)[:-32],
- digest_size=16,
- key=mac_key).digest()
+ mac_key = blake2s(b"mac1----" + public_key_bytes(self.itf.public_key)).digest()
+ resp = Wireguard(message_type=2, reserved_zero=0) / WireguardResponse(
+ sender_index=self.receiver_index,
+ receiver_index=self.sender,
+ unencrypted_ephemeral=b[0:32],
+ encrypted_nothing=b[32:],
+ )
+ mac1 = blake2s(bytes(resp)[:-32], digest_size=16, key=mac_key).digest()
resp[WireguardResponse].mac1 = mac1
- resp = (self.mk_tunnel_header(tx_itf, is_ip6) / resp)
+ resp = self.mk_tunnel_header(tx_itf, is_ip6) / resp
self._test.assertTrue(self.noise.handshake_finished)
return resp
@@ -318,13 +326,14 @@ class VppWgPeer(VppObject):
self._test.assertEqual(resp[Wireguard].message_type, 2)
self._test.assertEqual(resp[Wireguard].reserved_zero, 0)
- self._test.assertEqual(resp[WireguardResponse].receiver_index,
- self.receiver_index)
+ self._test.assertEqual(
+ resp[WireguardResponse].receiver_index, self.receiver_index
+ )
self.sender = resp[Wireguard].sender_index
payload = self.noise.read_message(bytes(resp)[12:60])
- self._test.assertEqual(payload, b'')
+ self._test.assertEqual(payload, b"")
self._test.assertTrue(self.noise.handshake_finished)
def decrypt_transport(self, p, is_ip6=False):
@@ -333,11 +342,11 @@ class VppWgPeer(VppObject):
p = Wireguard(p[Raw])
self._test.assertEqual(p[Wireguard].message_type, 4)
self._test.assertEqual(p[Wireguard].reserved_zero, 0)
- self._test.assertEqual(p[WireguardTransport].receiver_index,
- self.receiver_index)
+ self._test.assertEqual(
+ p[WireguardTransport].receiver_index, self.receiver_index
+ )
- d = self.noise.decrypt(
- p[WireguardTransport].encrypted_encapsulated_packet)
+ d = self.noise.decrypt(p[WireguardTransport].encrypted_encapsulated_packet)
return d
def encrypt_transport(self, p):
@@ -350,20 +359,21 @@ class VppWgPeer(VppObject):
# chech the oringial packet is present
self._test.assertEqual(rx[IP].dst, tx[IP].dst)
- self._test.assertEqual(rx[IP].ttl, tx[IP].ttl-1)
+ self._test.assertEqual(rx[IP].ttl, tx[IP].ttl - 1)
else:
rx = IPv6(self.decrypt_transport(rx))
# chech the oringial packet is present
self._test.assertEqual(rx[IPv6].dst, tx[IPv6].dst)
- self._test.assertEqual(rx[IPv6].ttl, tx[IPv6].ttl-1)
+ self._test.assertEqual(rx[IPv6].ttl, tx[IPv6].ttl - 1)
def want_events(self):
self._test.vapi.want_wireguard_peer_events(
enable_disable=1,
pid=os.getpid(),
peer_index=self.index,
- sw_if_index=self.itf.sw_if_index)
+ sw_if_index=self.itf.sw_if_index,
+ )
def wait_event(self, expect, timeout=5):
rv = self._test.vapi.wait_for_event(timeout, "wireguard_peer_event")
@@ -372,14 +382,14 @@ class VppWgPeer(VppObject):
class TestWg(VppTestCase):
- """ Wireguard Test Case """
+ """Wireguard Test Case"""
error_str = compile(r"Error")
- wg4_output_node_name = '/err/wg4-output-tun/'
- wg4_input_node_name = '/err/wg4-input/'
- wg6_output_node_name = '/err/wg6-output-tun/'
- wg6_input_node_name = '/err/wg6-input/'
+ wg4_output_node_name = "/err/wg4-output-tun/"
+ wg4_input_node_name = "/err/wg4-input/"
+ wg6_output_node_name = "/err/wg6-output-tun/"
+ wg6_input_node_name = "/err/wg6-input/"
kp4_error = wg4_output_node_name + "Keypair error"
mac4_error = wg4_input_node_name + "Invalid MAC handshake"
peer4_error = wg4_input_node_name + "Peer error"
@@ -417,13 +427,11 @@ class TestWg(VppTestCase):
self.base_peer6_err = self.statistics.get_err_counter(self.peer6_error)
def test_wg_interface(self):
- """ Simple interface creation """
+ """Simple interface creation"""
port = 12312
# Create interface
- wg0 = VppWgInterface(self,
- self.pg1.local_ip4,
- port).add_vpp_config()
+ wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config()
self.logger.info(self.vapi.cli("sh int"))
@@ -431,27 +439,29 @@ class TestWg(VppTestCase):
wg0.remove_vpp_config()
def test_handshake_hash(self):
- """ test hashing an init message """
+ """test hashing an init message"""
# a init packet generated by linux given the key below
- h = "0100000098b9032b" \
- "55cc4b39e73c3d24" \
- "a2a1ab884b524a81" \
- "1808bb86640fb70d" \
- "e93154fec1879125" \
- "ab012624a27f0b75" \
- "c0a2582f438ddb5f" \
- "8e768af40b4ab444" \
- "02f9ff473e1b797e" \
- "80d39d93c5480c82" \
- "a3d4510f70396976" \
- "586fb67300a5167b" \
- "ae6ca3ff3dfd00eb" \
- "59be198810f5aa03" \
- "6abc243d2155ee4f" \
- "2336483900aef801" \
- "08752cd700000000" \
- "0000000000000000" \
+ h = (
+ "0100000098b9032b"
+ "55cc4b39e73c3d24"
+ "a2a1ab884b524a81"
+ "1808bb86640fb70d"
+ "e93154fec1879125"
+ "ab012624a27f0b75"
+ "c0a2582f438ddb5f"
+ "8e768af40b4ab444"
+ "02f9ff473e1b797e"
+ "80d39d93c5480c82"
+ "a3d4510f70396976"
+ "586fb67300a5167b"
+ "ae6ca3ff3dfd00eb"
+ "59be198810f5aa03"
+ "6abc243d2155ee4f"
+ "2336483900aef801"
+ "08752cd700000000"
+ "0000000000000000"
"00000000"
+ )
b = bytearray.fromhex(h)
tgt = Wireguard(b)
@@ -463,40 +473,34 @@ class TestWg(VppTestCase):
# strip the macs and build a new packet
init = b[0:-32]
- mac_key = blake2s(b'mac1----' + public_key_bytes(pub)).digest()
- init += blake2s(init,
- digest_size=16,
- key=mac_key).digest()
- init += b'\x00' * 16
+ mac_key = blake2s(b"mac1----" + public_key_bytes(pub)).digest()
+ init += blake2s(init, digest_size=16, key=mac_key).digest()
+ init += b"\x00" * 16
act = Wireguard(init)
self.assertEqual(tgt, act)
def test_wg_peer_resp(self):
- """ Send handshake response """
+ """Send handshake response"""
port = 12323
# Create interfaces
- wg0 = VppWgInterface(self,
- self.pg1.local_ip4,
- port).add_vpp_config()
+ wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config()
wg0.admin_up()
wg0.config_ip4()
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
- peer_1 = VppWgPeer(self,
- wg0,
- self.pg1.remote_ip4,
- port+1,
- ["10.11.3.0/24"]).add_vpp_config()
+ peer_1 = VppWgPeer(
+ self, wg0, self.pg1.remote_ip4, port + 1, ["10.11.3.0/24"]
+ ).add_vpp_config()
self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1)
- r1 = VppIpRoute(self, "10.11.3.0", 24,
- [VppRoutePath("10.11.3.1",
- wg0.sw_if_index)]).add_vpp_config()
+ r1 = VppIpRoute(
+ self, "10.11.3.0", 24, [VppRoutePath("10.11.3.1", wg0.sw_if_index)]
+ ).add_vpp_config()
# wait for the peer to send a handshake
rx = self.pg1.get_capture(1, timeout=2)
@@ -513,10 +517,12 @@ class TestWg(VppTestCase):
self.assertEqual(0, len(b))
# send a packets that are routed into the tunnel
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.11.3.2") /
- UDP(sport=555, dport=556) /
- Raw(b'\x00' * 80))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.11.3.2")
+ / UDP(sport=555, dport=556)
+ / Raw(b"\x00" * 80)
+ )
rxs = self.send_and_expect(self.pg0, p * 255, self.pg1)
@@ -524,15 +530,24 @@ class TestWg(VppTestCase):
# send packets into the tunnel, expect to receive them on
# the other side
- p = [(peer_1.mk_tunnel_header(self.pg1) /
- Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(
- receiver_index=peer_1.sender,
- counter=ii,
- encrypted_encapsulated_packet=peer_1.encrypt_transport(
- (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) /
- UDP(sport=222, dport=223) /
- Raw())))) for ii in range(255)]
+ p = [
+ (
+ peer_1.mk_tunnel_header(self.pg1)
+ / Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peer_1.sender,
+ counter=ii,
+ encrypted_encapsulated_packet=peer_1.encrypt_transport(
+ (
+ IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
+ ),
+ )
+ )
+ for ii in range(255)
+ ]
rxs = self.send_and_expect(self.pg1, p, self.pg0)
@@ -545,53 +560,54 @@ class TestWg(VppTestCase):
wg0.remove_vpp_config()
def test_wg_peer_v4o4(self):
- """ Test v4o4"""
+ """Test v4o4"""
port = 12333
# Create interfaces
- wg0 = VppWgInterface(self,
- self.pg1.local_ip4,
- port).add_vpp_config()
+ wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config()
wg0.admin_up()
wg0.config_ip4()
- peer_1 = VppWgPeer(self,
- wg0,
- self.pg1.remote_ip4,
- port+1,
- ["10.11.3.0/24"]).add_vpp_config()
+ peer_1 = VppWgPeer(
+ self, wg0, self.pg1.remote_ip4, port + 1, ["10.11.3.0/24"]
+ ).add_vpp_config()
self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1)
- r1 = VppIpRoute(self, "10.11.3.0", 24,
- [VppRoutePath("10.11.3.1",
- wg0.sw_if_index)]).add_vpp_config()
+ r1 = VppIpRoute(
+ self, "10.11.3.0", 24, [VppRoutePath("10.11.3.1", wg0.sw_if_index)]
+ ).add_vpp_config()
# route a packet into the wg interface
# use the allowed-ip prefix
# this is dropped because the peer is not initiated
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.11.3.2") /
- UDP(sport=555, dport=556) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.11.3.2")
+ / UDP(sport=555, dport=556)
+ / Raw()
+ )
self.send_and_assert_no_replies(self.pg0, [p])
- self.assertEqual(self.base_kp4_err + 1,
- self.statistics.get_err_counter(self.kp4_error))
+ self.assertEqual(
+ self.base_kp4_err + 1, self.statistics.get_err_counter(self.kp4_error)
+ )
# send a handsake from the peer with an invalid MAC
p = peer_1.mk_handshake(self.pg1)
- p[WireguardInitiation].mac1 = b'foobar'
+ p[WireguardInitiation].mac1 = b"foobar"
self.send_and_assert_no_replies(self.pg1, [p])
- self.assertEqual(self.base_mac4_err + 1,
- self.statistics.get_err_counter(self.mac4_error))
+ self.assertEqual(
+ self.base_mac4_err + 1, self.statistics.get_err_counter(self.mac4_error)
+ )
# send a handsake from the peer but signed by the wrong key.
- p = peer_1.mk_handshake(self.pg1,
- False,
- X25519PrivateKey.generate().public_key())
+ p = peer_1.mk_handshake(
+ self.pg1, False, X25519PrivateKey.generate().public_key()
+ )
self.send_and_assert_no_replies(self.pg1, [p])
- self.assertEqual(self.base_peer4_err + 1,
- self.statistics.get_err_counter(self.peer4_error))
+ self.assertEqual(
+ self.base_peer4_err + 1, self.statistics.get_err_counter(self.peer4_error)
+ )
# send a valid handsake init for which we expect a response
p = peer_1.mk_handshake(self.pg1)
@@ -602,25 +618,31 @@ class TestWg(VppTestCase):
# route a packet into the wg interface
# this is dropped because the peer is still not initiated
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.11.3.2") /
- UDP(sport=555, dport=556) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.11.3.2")
+ / UDP(sport=555, dport=556)
+ / Raw()
+ )
self.send_and_assert_no_replies(self.pg0, [p])
- self.assertEqual(self.base_kp4_err + 2,
- self.statistics.get_err_counter(self.kp4_error))
+ self.assertEqual(
+ self.base_kp4_err + 2, self.statistics.get_err_counter(self.kp4_error)
+ )
# send a data packet from the peer through the tunnel
# this completes the handshake
- p = (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) /
- UDP(sport=222, dport=223) /
- Raw())
+ p = (
+ IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
d = peer_1.encrypt_transport(p)
- p = (peer_1.mk_tunnel_header(self.pg1) /
- (Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(receiver_index=peer_1.sender,
- counter=0,
- encrypted_encapsulated_packet=d)))
+ p = peer_1.mk_tunnel_header(self.pg1) / (
+ Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peer_1.sender, counter=0, encrypted_encapsulated_packet=d
+ )
+ )
rxs = self.send_and_expect(self.pg1, [p], self.pg0)
for rx in rxs:
@@ -628,10 +650,12 @@ class TestWg(VppTestCase):
self.assertEqual(rx[IP].ttl, 19)
# send a packets that are routed into the tunnel
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.11.3.2") /
- UDP(sport=555, dport=556) /
- Raw(b'\x00' * 80))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.11.3.2")
+ / UDP(sport=555, dport=556)
+ / Raw(b"\x00" * 80)
+ )
rxs = self.send_and_expect(self.pg0, p * 255, self.pg1)
@@ -640,19 +664,28 @@ class TestWg(VppTestCase):
# chech the oringial packet is present
self.assertEqual(rx[IP].dst, p[IP].dst)
- self.assertEqual(rx[IP].ttl, p[IP].ttl-1)
+ self.assertEqual(rx[IP].ttl, p[IP].ttl - 1)
# send packets into the tunnel, expect to receive them on
# the other side
- p = [(peer_1.mk_tunnel_header(self.pg1) /
- Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(
- receiver_index=peer_1.sender,
- counter=ii+1,
- encrypted_encapsulated_packet=peer_1.encrypt_transport(
- (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) /
- UDP(sport=222, dport=223) /
- Raw())))) for ii in range(255)]
+ p = [
+ (
+ peer_1.mk_tunnel_header(self.pg1)
+ / Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peer_1.sender,
+ counter=ii + 1,
+ encrypted_encapsulated_packet=peer_1.encrypt_transport(
+ (
+ IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
+ ),
+ )
+ )
+ for ii in range(255)
+ ]
rxs = self.send_and_expect(self.pg1, p, self.pg0)
@@ -665,56 +698,57 @@ class TestWg(VppTestCase):
wg0.remove_vpp_config()
def test_wg_peer_v6o6(self):
- """ Test v6o6"""
+ """Test v6o6"""
port = 12343
# Create interfaces
- wg0 = VppWgInterface(self,
- self.pg1.local_ip6,
- port).add_vpp_config()
+ wg0 = VppWgInterface(self, self.pg1.local_ip6, port).add_vpp_config()
wg0.admin_up()
wg0.config_ip6()
- peer_1 = VppWgPeer(self,
- wg0,
- self.pg1.remote_ip6,
- port+1,
- ["1::3:0/112"]).add_vpp_config(True)
+ peer_1 = VppWgPeer(
+ self, wg0, self.pg1.remote_ip6, port + 1, ["1::3:0/112"]
+ ).add_vpp_config(True)
self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1)
- r1 = VppIpRoute(self, "1::3:0", 112,
- [VppRoutePath("1::3:1",
- wg0.sw_if_index)]).add_vpp_config()
+ r1 = VppIpRoute(
+ self, "1::3:0", 112, [VppRoutePath("1::3:1", wg0.sw_if_index)]
+ ).add_vpp_config()
# route a packet into the wg interface
# use the allowed-ip prefix
# this is dropped because the peer is not initiated
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst="1::3:2") /
- UDP(sport=555, dport=556) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst="1::3:2")
+ / UDP(sport=555, dport=556)
+ / Raw()
+ )
self.send_and_assert_no_replies(self.pg0, [p])
- self.assertEqual(self.base_kp6_err + 1,
- self.statistics.get_err_counter(self.kp6_error))
+ self.assertEqual(
+ self.base_kp6_err + 1, self.statistics.get_err_counter(self.kp6_error)
+ )
# send a handsake from the peer with an invalid MAC
p = peer_1.mk_handshake(self.pg1, True)
- p[WireguardInitiation].mac1 = b'foobar'
+ p[WireguardInitiation].mac1 = b"foobar"
self.send_and_assert_no_replies(self.pg1, [p])
- self.assertEqual(self.base_mac6_err + 1,
- self.statistics.get_err_counter(self.mac6_error))
+ self.assertEqual(
+ self.base_mac6_err + 1, self.statistics.get_err_counter(self.mac6_error)
+ )
# send a handsake from the peer but signed by the wrong key.
- p = peer_1.mk_handshake(self.pg1,
- True,
- X25519PrivateKey.generate().public_key())
+ p = peer_1.mk_handshake(
+ self.pg1, True, X25519PrivateKey.generate().public_key()
+ )
self.send_and_assert_no_replies(self.pg1, [p])
- self.assertEqual(self.base_peer6_err + 1,
- self.statistics.get_err_counter(self.peer6_error))
+ self.assertEqual(
+ self.base_peer6_err + 1, self.statistics.get_err_counter(self.peer6_error)
+ )
# send a valid handsake init for which we expect a response
p = peer_1.mk_handshake(self.pg1, True)
@@ -725,25 +759,31 @@ class TestWg(VppTestCase):
# route a packet into the wg interface
# this is dropped because the peer is still not initiated
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst="1::3:2") /
- UDP(sport=555, dport=556) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst="1::3:2")
+ / UDP(sport=555, dport=556)
+ / Raw()
+ )
self.send_and_assert_no_replies(self.pg0, [p])
- self.assertEqual(self.base_kp6_err + 2,
- self.statistics.get_err_counter(self.kp6_error))
+ self.assertEqual(
+ self.base_kp6_err + 2, self.statistics.get_err_counter(self.kp6_error)
+ )
# send a data packet from the peer through the tunnel
# this completes the handshake
- p = (IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) /
- UDP(sport=222, dport=223) /
- Raw())
+ p = (
+ IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
d = peer_1.encrypt_transport(p)
- p = (peer_1.mk_tunnel_header(self.pg1, True) /
- (Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(receiver_index=peer_1.sender,
- counter=0,
- encrypted_encapsulated_packet=d)))
+ p = peer_1.mk_tunnel_header(self.pg1, True) / (
+ Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peer_1.sender, counter=0, encrypted_encapsulated_packet=d
+ )
+ )
rxs = self.send_and_expect(self.pg1, [p], self.pg0)
for rx in rxs:
@@ -751,10 +791,12 @@ class TestWg(VppTestCase):
self.assertEqual(rx[IPv6].hlim, 19)
# send a packets that are routed into the tunnel
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst="1::3:2") /
- UDP(sport=555, dport=556) /
- Raw(b'\x00' * 80))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst="1::3:2")
+ / UDP(sport=555, dport=556)
+ / Raw(b"\x00" * 80)
+ )
rxs = self.send_and_expect(self.pg0, p * 255, self.pg1)
@@ -763,19 +805,28 @@ class TestWg(VppTestCase):
# chech the oringial packet is present
self.assertEqual(rx[IPv6].dst, p[IPv6].dst)
- self.assertEqual(rx[IPv6].hlim, p[IPv6].hlim-1)
+ self.assertEqual(rx[IPv6].hlim, p[IPv6].hlim - 1)
# send packets into the tunnel, expect to receive them on
# the other side
- p = [(peer_1.mk_tunnel_header(self.pg1, True) /
- Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(
- receiver_index=peer_1.sender,
- counter=ii+1,
- encrypted_encapsulated_packet=peer_1.encrypt_transport(
- (IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) /
- UDP(sport=222, dport=223) /
- Raw())))) for ii in range(255)]
+ p = [
+ (
+ peer_1.mk_tunnel_header(self.pg1, True)
+ / Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peer_1.sender,
+ counter=ii + 1,
+ encrypted_encapsulated_packet=peer_1.encrypt_transport(
+ (
+ IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
+ ),
+ )
+ )
+ for ii in range(255)
+ ]
rxs = self.send_and_expect(self.pg1, p, self.pg0)
@@ -788,54 +839,55 @@ class TestWg(VppTestCase):
wg0.remove_vpp_config()
def test_wg_peer_v6o4(self):
- """ Test v6o4"""
+ """Test v6o4"""
port = 12353
# Create interfaces
- wg0 = VppWgInterface(self,
- self.pg1.local_ip4,
- port).add_vpp_config()
+ wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config()
wg0.admin_up()
wg0.config_ip6()
- peer_1 = VppWgPeer(self,
- wg0,
- self.pg1.remote_ip4,
- port+1,
- ["1::3:0/112"]).add_vpp_config(True)
+ peer_1 = VppWgPeer(
+ self, wg0, self.pg1.remote_ip4, port + 1, ["1::3:0/112"]
+ ).add_vpp_config(True)
self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1)
- r1 = VppIpRoute(self, "1::3:0", 112,
- [VppRoutePath("1::3:1",
- wg0.sw_if_index)]).add_vpp_config()
+ r1 = VppIpRoute(
+ self, "1::3:0", 112, [VppRoutePath("1::3:1", wg0.sw_if_index)]
+ ).add_vpp_config()
# route a packet into the wg interface
# use the allowed-ip prefix
# this is dropped because the peer is not initiated
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst="1::3:2") /
- UDP(sport=555, dport=556) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst="1::3:2")
+ / UDP(sport=555, dport=556)
+ / Raw()
+ )
self.send_and_assert_no_replies(self.pg0, [p])
- self.assertEqual(self.base_kp6_err + 1,
- self.statistics.get_err_counter(self.kp6_error))
+ self.assertEqual(
+ self.base_kp6_err + 1, self.statistics.get_err_counter(self.kp6_error)
+ )
# send a handsake from the peer with an invalid MAC
p = peer_1.mk_handshake(self.pg1)
- p[WireguardInitiation].mac1 = b'foobar'
+ p[WireguardInitiation].mac1 = b"foobar"
self.send_and_assert_no_replies(self.pg1, [p])
- self.assertEqual(self.base_mac4_err + 1,
- self.statistics.get_err_counter(self.mac4_error))
+ self.assertEqual(
+ self.base_mac4_err + 1, self.statistics.get_err_counter(self.mac4_error)
+ )
# send a handsake from the peer but signed by the wrong key.
- p = peer_1.mk_handshake(self.pg1,
- False,
- X25519PrivateKey.generate().public_key())
+ p = peer_1.mk_handshake(
+ self.pg1, False, X25519PrivateKey.generate().public_key()
+ )
self.send_and_assert_no_replies(self.pg1, [p])
- self.assertEqual(self.base_peer4_err + 1,
- self.statistics.get_err_counter(self.peer4_error))
+ self.assertEqual(
+ self.base_peer4_err + 1, self.statistics.get_err_counter(self.peer4_error)
+ )
# send a valid handsake init for which we expect a response
p = peer_1.mk_handshake(self.pg1)
@@ -846,25 +898,31 @@ class TestWg(VppTestCase):
# route a packet into the wg interface
# this is dropped because the peer is still not initiated
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst="1::3:2") /
- UDP(sport=555, dport=556) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst="1::3:2")
+ / UDP(sport=555, dport=556)
+ / Raw()
+ )
self.send_and_assert_no_replies(self.pg0, [p])
- self.assertEqual(self.base_kp6_err + 2,
- self.statistics.get_err_counter(self.kp6_error))
+ self.assertEqual(
+ self.base_kp6_err + 2, self.statistics.get_err_counter(self.kp6_error)
+ )
# send a data packet from the peer through the tunnel
# this completes the handshake
- p = (IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) /
- UDP(sport=222, dport=223) /
- Raw())
+ p = (
+ IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
d = peer_1.encrypt_transport(p)
- p = (peer_1.mk_tunnel_header(self.pg1) /
- (Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(receiver_index=peer_1.sender,
- counter=0,
- encrypted_encapsulated_packet=d)))
+ p = peer_1.mk_tunnel_header(self.pg1) / (
+ Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peer_1.sender, counter=0, encrypted_encapsulated_packet=d
+ )
+ )
rxs = self.send_and_expect(self.pg1, [p], self.pg0)
for rx in rxs:
@@ -872,10 +930,12 @@ class TestWg(VppTestCase):
self.assertEqual(rx[IPv6].hlim, 19)
# send a packets that are routed into the tunnel
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IPv6(src=self.pg0.remote_ip6, dst="1::3:2") /
- UDP(sport=555, dport=556) /
- Raw(b'\x00' * 80))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IPv6(src=self.pg0.remote_ip6, dst="1::3:2")
+ / UDP(sport=555, dport=556)
+ / Raw(b"\x00" * 80)
+ )
rxs = self.send_and_expect(self.pg0, p * 255, self.pg1)
@@ -884,19 +944,28 @@ class TestWg(VppTestCase):
# chech the oringial packet is present
self.assertEqual(rx[IPv6].dst, p[IPv6].dst)
- self.assertEqual(rx[IPv6].hlim, p[IPv6].hlim-1)
+ self.assertEqual(rx[IPv6].hlim, p[IPv6].hlim - 1)
# send packets into the tunnel, expect to receive them on
# the other side
- p = [(peer_1.mk_tunnel_header(self.pg1) /
- Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(
- receiver_index=peer_1.sender,
- counter=ii+1,
- encrypted_encapsulated_packet=peer_1.encrypt_transport(
- (IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20) /
- UDP(sport=222, dport=223) /
- Raw())))) for ii in range(255)]
+ p = [
+ (
+ peer_1.mk_tunnel_header(self.pg1)
+ / Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peer_1.sender,
+ counter=ii + 1,
+ encrypted_encapsulated_packet=peer_1.encrypt_transport(
+ (
+ IPv6(src="1::3:1", dst=self.pg0.remote_ip6, hlim=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
+ ),
+ )
+ )
+ for ii in range(255)
+ ]
rxs = self.send_and_expect(self.pg1, p, self.pg0)
@@ -909,53 +978,54 @@ class TestWg(VppTestCase):
wg0.remove_vpp_config()
def test_wg_peer_v4o6(self):
- """ Test v4o6"""
+ """Test v4o6"""
port = 12363
# Create interfaces
- wg0 = VppWgInterface(self,
- self.pg1.local_ip6,
- port).add_vpp_config()
+ wg0 = VppWgInterface(self, self.pg1.local_ip6, port).add_vpp_config()
wg0.admin_up()
wg0.config_ip4()
- peer_1 = VppWgPeer(self,
- wg0,
- self.pg1.remote_ip6,
- port+1,
- ["10.11.3.0/24"]).add_vpp_config()
+ peer_1 = VppWgPeer(
+ self, wg0, self.pg1.remote_ip6, port + 1, ["10.11.3.0/24"]
+ ).add_vpp_config()
self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1)
- r1 = VppIpRoute(self, "10.11.3.0", 24,
- [VppRoutePath("10.11.3.1",
- wg0.sw_if_index)]).add_vpp_config()
+ r1 = VppIpRoute(
+ self, "10.11.3.0", 24, [VppRoutePath("10.11.3.1", wg0.sw_if_index)]
+ ).add_vpp_config()
# route a packet into the wg interface
# use the allowed-ip prefix
# this is dropped because the peer is not initiated
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.11.3.2") /
- UDP(sport=555, dport=556) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.11.3.2")
+ / UDP(sport=555, dport=556)
+ / Raw()
+ )
self.send_and_assert_no_replies(self.pg0, [p])
- self.assertEqual(self.base_kp4_err + 1,
- self.statistics.get_err_counter(self.kp4_error))
+ self.assertEqual(
+ self.base_kp4_err + 1, self.statistics.get_err_counter(self.kp4_error)
+ )
# send a handsake from the peer with an invalid MAC
p = peer_1.mk_handshake(self.pg1, True)
- p[WireguardInitiation].mac1 = b'foobar'
+ p[WireguardInitiation].mac1 = b"foobar"
self.send_and_assert_no_replies(self.pg1, [p])
- self.assertEqual(self.base_mac6_err + 1,
- self.statistics.get_err_counter(self.mac6_error))
+ self.assertEqual(
+ self.base_mac6_err + 1, self.statistics.get_err_counter(self.mac6_error)
+ )
# send a handsake from the peer but signed by the wrong key.
- p = peer_1.mk_handshake(self.pg1,
- True,
- X25519PrivateKey.generate().public_key())
+ p = peer_1.mk_handshake(
+ self.pg1, True, X25519PrivateKey.generate().public_key()
+ )
self.send_and_assert_no_replies(self.pg1, [p])
- self.assertEqual(self.base_peer6_err + 1,
- self.statistics.get_err_counter(self.peer6_error))
+ self.assertEqual(
+ self.base_peer6_err + 1, self.statistics.get_err_counter(self.peer6_error)
+ )
# send a valid handsake init for which we expect a response
p = peer_1.mk_handshake(self.pg1, True)
@@ -966,25 +1036,31 @@ class TestWg(VppTestCase):
# route a packet into the wg interface
# this is dropped because the peer is still not initiated
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.11.3.2") /
- UDP(sport=555, dport=556) /
- Raw())
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.11.3.2")
+ / UDP(sport=555, dport=556)
+ / Raw()
+ )
self.send_and_assert_no_replies(self.pg0, [p])
- self.assertEqual(self.base_kp4_err + 2,
- self.statistics.get_err_counter(self.kp4_error))
+ self.assertEqual(
+ self.base_kp4_err + 2, self.statistics.get_err_counter(self.kp4_error)
+ )
# send a data packet from the peer through the tunnel
# this completes the handshake
- p = (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) /
- UDP(sport=222, dport=223) /
- Raw())
+ p = (
+ IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
d = peer_1.encrypt_transport(p)
- p = (peer_1.mk_tunnel_header(self.pg1, True) /
- (Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(receiver_index=peer_1.sender,
- counter=0,
- encrypted_encapsulated_packet=d)))
+ p = peer_1.mk_tunnel_header(self.pg1, True) / (
+ Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peer_1.sender, counter=0, encrypted_encapsulated_packet=d
+ )
+ )
rxs = self.send_and_expect(self.pg1, [p], self.pg0)
for rx in rxs:
@@ -992,10 +1068,12 @@ class TestWg(VppTestCase):
self.assertEqual(rx[IP].ttl, 19)
# send a packets that are routed into the tunnel
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.11.3.2") /
- UDP(sport=555, dport=556) /
- Raw(b'\x00' * 80))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.11.3.2")
+ / UDP(sport=555, dport=556)
+ / Raw(b"\x00" * 80)
+ )
rxs = self.send_and_expect(self.pg0, p * 255, self.pg1)
@@ -1004,19 +1082,28 @@ class TestWg(VppTestCase):
# chech the oringial packet is present
self.assertEqual(rx[IP].dst, p[IP].dst)
- self.assertEqual(rx[IP].ttl, p[IP].ttl-1)
+ self.assertEqual(rx[IP].ttl, p[IP].ttl - 1)
# send packets into the tunnel, expect to receive them on
# the other side
- p = [(peer_1.mk_tunnel_header(self.pg1, True) /
- Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(
- receiver_index=peer_1.sender,
- counter=ii+1,
- encrypted_encapsulated_packet=peer_1.encrypt_transport(
- (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) /
- UDP(sport=222, dport=223) /
- Raw())))) for ii in range(255)]
+ p = [
+ (
+ peer_1.mk_tunnel_header(self.pg1, True)
+ / Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peer_1.sender,
+ counter=ii + 1,
+ encrypted_encapsulated_packet=peer_1.encrypt_transport(
+ (
+ IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
+ ),
+ )
+ )
+ for ii in range(255)
+ ]
rxs = self.send_and_expect(self.pg1, p, self.pg0)
@@ -1029,16 +1116,12 @@ class TestWg(VppTestCase):
wg0.remove_vpp_config()
def test_wg_multi_peer(self):
- """ multiple peer setup """
+ """multiple peer setup"""
port = 12373
# Create interfaces
- wg0 = VppWgInterface(self,
- self.pg1.local_ip4,
- port).add_vpp_config()
- wg1 = VppWgInterface(self,
- self.pg2.local_ip4,
- port+1).add_vpp_config()
+ wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config()
+ wg1 = VppWgInterface(self, self.pg2.local_ip4, port + 1).add_vpp_config()
wg0.admin_up()
wg1.admin_up()
@@ -1060,25 +1143,43 @@ class TestWg(VppTestCase):
routes_1 = []
routes_2 = []
for i in range(NUM_PEERS):
- peers_1.append(VppWgPeer(self,
- wg0,
- self.pg1.remote_hosts[i].ip4,
- port+1+i,
- ["10.0.%d.4/32" % i]).add_vpp_config())
- routes_1.append(VppIpRoute(self, "10.0.%d.4" % i, 32,
- [VppRoutePath(self.pg1.remote_hosts[i].ip4,
- wg0.sw_if_index)]).add_vpp_config())
-
- peers_2.append(VppWgPeer(self,
- wg1,
- self.pg2.remote_hosts[i].ip4,
- port+100+i,
- ["10.100.%d.4/32" % i]).add_vpp_config())
- routes_2.append(VppIpRoute(self, "10.100.%d.4" % i, 32,
- [VppRoutePath(self.pg2.remote_hosts[i].ip4,
- wg1.sw_if_index)]).add_vpp_config())
-
- self.assertEqual(len(self.vapi.wireguard_peers_dump()), NUM_PEERS*2)
+ peers_1.append(
+ VppWgPeer(
+ self,
+ wg0,
+ self.pg1.remote_hosts[i].ip4,
+ port + 1 + i,
+ ["10.0.%d.4/32" % i],
+ ).add_vpp_config()
+ )
+ routes_1.append(
+ VppIpRoute(
+ self,
+ "10.0.%d.4" % i,
+ 32,
+ [VppRoutePath(self.pg1.remote_hosts[i].ip4, wg0.sw_if_index)],
+ ).add_vpp_config()
+ )
+
+ peers_2.append(
+ VppWgPeer(
+ self,
+ wg1,
+ self.pg2.remote_hosts[i].ip4,
+ port + 100 + i,
+ ["10.100.%d.4/32" % i],
+ ).add_vpp_config()
+ )
+ routes_2.append(
+ VppIpRoute(
+ self,
+ "10.100.%d.4" % i,
+ 32,
+ [VppRoutePath(self.pg2.remote_hosts[i].ip4, wg1.sw_if_index)],
+ ).add_vpp_config()
+ )
+
+ self.assertEqual(len(self.vapi.wireguard_peers_dump()), NUM_PEERS * 2)
self.logger.info(self.vapi.cli("show wireguard peer"))
self.logger.info(self.vapi.cli("show wireguard interface"))
@@ -1104,7 +1205,7 @@ class TestWg(VppTestCase):
wg1.remove_vpp_config()
def test_wg_multi_interface(self):
- """ Multi-tunnel on the same port """
+ """Multi-tunnel on the same port"""
port = 12500
# Create many wireguard interfaces
@@ -1120,21 +1221,28 @@ class TestWg(VppTestCase):
wg_ifs = []
for i in range(NUM_IFS):
# Use the same port for each interface
- wg0 = VppWgInterface(self,
- self.pg1.local_ip4,
- port).add_vpp_config()
+ wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config()
wg0.admin_up()
wg0.config_ip4()
wg_ifs.append(wg0)
- peers.append(VppWgPeer(self,
- wg0,
- self.pg1.remote_hosts[i].ip4,
- port+1+i,
- ["10.0.%d.0/24" % i]).add_vpp_config())
-
- routes.append(VppIpRoute(self, "10.0.%d.0" % i, 24,
- [VppRoutePath("10.0.%d.4" % i,
- wg0.sw_if_index)]).add_vpp_config())
+ peers.append(
+ VppWgPeer(
+ self,
+ wg0,
+ self.pg1.remote_hosts[i].ip4,
+ port + 1 + i,
+ ["10.0.%d.0/24" % i],
+ ).add_vpp_config()
+ )
+
+ routes.append(
+ VppIpRoute(
+ self,
+ "10.0.%d.0" % i,
+ 24,
+ [VppRoutePath("10.0.%d.4" % i, wg0.sw_if_index)],
+ ).add_vpp_config()
+ )
self.assertEqual(len(self.vapi.wireguard_peers_dump()), NUM_IFS)
@@ -1146,16 +1254,20 @@ class TestWg(VppTestCase):
# send a data packet from the peer through the tunnel
# this completes the handshake
- p = (IP(src="10.0.%d.4" % i,
- dst=self.pg0.remote_hosts[i].ip4, ttl=20) /
- UDP(sport=222, dport=223) /
- Raw())
+ p = (
+ IP(src="10.0.%d.4" % i, dst=self.pg0.remote_hosts[i].ip4, ttl=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
d = peers[i].encrypt_transport(p)
- p = (peers[i].mk_tunnel_header(self.pg1) /
- (Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(receiver_index=peers[i].sender,
- counter=0,
- encrypted_encapsulated_packet=d)))
+ p = peers[i].mk_tunnel_header(self.pg1) / (
+ Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peers[i].sender,
+ counter=0,
+ encrypted_encapsulated_packet=d,
+ )
+ )
rxs = self.send_and_expect(self.pg1, [p], self.pg0)
for rx in rxs:
self.assertEqual(rx[IP].dst, self.pg0.remote_hosts[i].ip4)
@@ -1163,10 +1275,12 @@ class TestWg(VppTestCase):
# send a packets that are routed into the tunnel
for i in range(NUM_IFS):
- p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_hosts[i].ip4, dst="10.0.%d.4" % i) /
- UDP(sport=555, dport=556) /
- Raw(b'\x00' * 80))
+ p = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_hosts[i].ip4, dst="10.0.%d.4" % i)
+ / UDP(sport=555, dport=556)
+ / Raw(b"\x00" * 80)
+ )
rxs = self.send_and_expect(self.pg0, p * 64, self.pg1)
@@ -1175,20 +1289,32 @@ class TestWg(VppTestCase):
# check the oringial packet is present
self.assertEqual(rx[IP].dst, p[IP].dst)
- self.assertEqual(rx[IP].ttl, p[IP].ttl-1)
+ self.assertEqual(rx[IP].ttl, p[IP].ttl - 1)
# send packets into the tunnel
for i in range(NUM_IFS):
- p = [(peers[i].mk_tunnel_header(self.pg1) /
- Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(
- receiver_index=peers[i].sender,
- counter=ii+1,
- encrypted_encapsulated_packet=peers[i].encrypt_transport(
- (IP(src="10.0.%d.4" % i,
- dst=self.pg0.remote_hosts[i].ip4, ttl=20) /
- UDP(sport=222, dport=223) /
- Raw())))) for ii in range(64)]
+ p = [
+ (
+ peers[i].mk_tunnel_header(self.pg1)
+ / Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peers[i].sender,
+ counter=ii + 1,
+ encrypted_encapsulated_packet=peers[i].encrypt_transport(
+ (
+ IP(
+ src="10.0.%d.4" % i,
+ dst=self.pg0.remote_hosts[i].ip4,
+ ttl=20,
+ )
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
+ ),
+ )
+ )
+ for ii in range(64)
+ ]
rxs = self.send_and_expect(self.pg1, p, self.pg0)
@@ -1204,22 +1330,16 @@ class TestWg(VppTestCase):
i.remove_vpp_config()
def test_wg_event(self):
- """ Test events """
+ """Test events"""
port = 12600
- ESTABLISHED_FLAG = VppEnum.\
- vl_api_wireguard_peer_flags_t.\
- WIREGUARD_PEER_ESTABLISHED
- DEAD_FLAG = VppEnum.\
- vl_api_wireguard_peer_flags_t.\
- WIREGUARD_PEER_STATUS_DEAD
+ ESTABLISHED_FLAG = (
+ VppEnum.vl_api_wireguard_peer_flags_t.WIREGUARD_PEER_ESTABLISHED
+ )
+ DEAD_FLAG = VppEnum.vl_api_wireguard_peer_flags_t.WIREGUARD_PEER_STATUS_DEAD
# Create interfaces
- wg0 = VppWgInterface(self,
- self.pg1.local_ip4,
- port).add_vpp_config()
- wg1 = VppWgInterface(self,
- self.pg2.local_ip4,
- port+1).add_vpp_config()
+ wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config()
+ wg1 = VppWgInterface(self, self.pg2.local_ip4, port + 1).add_vpp_config()
wg0.admin_up()
wg1.admin_up()
@@ -1241,25 +1361,43 @@ class TestWg(VppTestCase):
routes_0 = []
routes_1 = []
for i in range(NUM_PEERS):
- peers_0.append(VppWgPeer(self,
- wg0,
- self.pg1.remote_hosts[i].ip4,
- port+1+i,
- ["10.0.%d.4/32" % i]).add_vpp_config())
- routes_0.append(VppIpRoute(self, "10.0.%d.4" % i, 32,
- [VppRoutePath(self.pg1.remote_hosts[i].ip4,
- wg0.sw_if_index)]).add_vpp_config())
-
- peers_1.append(VppWgPeer(self,
- wg1,
- self.pg2.remote_hosts[i].ip4,
- port+100+i,
- ["10.100.%d.4/32" % i]).add_vpp_config())
- routes_1.append(VppIpRoute(self, "10.100.%d.4" % i, 32,
- [VppRoutePath(self.pg2.remote_hosts[i].ip4,
- wg1.sw_if_index)]).add_vpp_config())
-
- self.assertEqual(len(self.vapi.wireguard_peers_dump()), NUM_PEERS*2)
+ peers_0.append(
+ VppWgPeer(
+ self,
+ wg0,
+ self.pg1.remote_hosts[i].ip4,
+ port + 1 + i,
+ ["10.0.%d.4/32" % i],
+ ).add_vpp_config()
+ )
+ routes_0.append(
+ VppIpRoute(
+ self,
+ "10.0.%d.4" % i,
+ 32,
+ [VppRoutePath(self.pg1.remote_hosts[i].ip4, wg0.sw_if_index)],
+ ).add_vpp_config()
+ )
+
+ peers_1.append(
+ VppWgPeer(
+ self,
+ wg1,
+ self.pg2.remote_hosts[i].ip4,
+ port + 100 + i,
+ ["10.100.%d.4/32" % i],
+ ).add_vpp_config()
+ )
+ routes_1.append(
+ VppIpRoute(
+ self,
+ "10.100.%d.4" % i,
+ 32,
+ [VppRoutePath(self.pg2.remote_hosts[i].ip4, wg1.sw_if_index)],
+ ).add_vpp_config()
+ )
+
+ self.assertEqual(len(self.vapi.wireguard_peers_dump()), NUM_PEERS * 2)
# Want events from the first perr of wg0
# and from all wg1 peers
@@ -1271,16 +1409,14 @@ class TestWg(VppTestCase):
p = peers_0[i].mk_handshake(self.pg1)
rx = self.send_and_expect(self.pg1, [p], self.pg1)
peers_0[i].consume_response(rx[0])
- if (i == 0):
+ if i == 0:
peers_0[0].wait_event(ESTABLISHED_FLAG)
p = peers_1[i].mk_handshake(self.pg2)
rx = self.send_and_expect(self.pg2, [p], self.pg2)
peers_1[i].consume_response(rx[0])
- wg1.wait_events(
- ESTABLISHED_FLAG,
- [peers_1[0].index, peers_1[1].index])
+ wg1.wait_events(ESTABLISHED_FLAG, [peers_1[0].index, peers_1[1].index])
# remove routes
for r in routes_0:
@@ -1292,7 +1428,7 @@ class TestWg(VppTestCase):
for i in range(NUM_PEERS):
self.assertTrue(peers_0[i].query_vpp_config())
peers_0[i].remove_vpp_config()
- if (i == 0):
+ if i == 0:
peers_0[i].wait_event(0)
peers_0[i].wait_event(DEAD_FLAG)
for p in peers_1:
@@ -1306,32 +1442,28 @@ class TestWg(VppTestCase):
class WireguardHandoffTests(TestWg):
- """ Wireguard Tests in multi worker setup """
+ """Wireguard Tests in multi worker setup"""
+
vpp_worker_count = 2
def test_wg_peer_init(self):
- """ Handoff """
+ """Handoff"""
port = 12383
# Create interfaces
- wg0 = VppWgInterface(self,
- self.pg1.local_ip4,
- port).add_vpp_config()
+ wg0 = VppWgInterface(self, self.pg1.local_ip4, port).add_vpp_config()
wg0.admin_up()
wg0.config_ip4()
- peer_1 = VppWgPeer(self,
- wg0,
- self.pg1.remote_ip4,
- port+1,
- ["10.11.2.0/24",
- "10.11.3.0/24"]).add_vpp_config()
+ peer_1 = VppWgPeer(
+ self, wg0, self.pg1.remote_ip4, port + 1, ["10.11.2.0/24", "10.11.3.0/24"]
+ ).add_vpp_config()
self.assertEqual(len(self.vapi.wireguard_peers_dump()), 1)
- r1 = VppIpRoute(self, "10.11.3.0", 24,
- [VppRoutePath("10.11.3.1",
- wg0.sw_if_index)]).add_vpp_config()
+ r1 = VppIpRoute(
+ self, "10.11.3.0", 24, [VppRoutePath("10.11.3.1", wg0.sw_if_index)]
+ ).add_vpp_config()
# send a valid handsake init for which we expect a response
p = peer_1.mk_handshake(self.pg1)
@@ -1342,17 +1474,19 @@ class WireguardHandoffTests(TestWg):
# send a data packet from the peer through the tunnel
# this completes the handshake and pins the peer to worker 0
- p = (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) /
- UDP(sport=222, dport=223) /
- Raw())
+ p = (
+ IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
d = peer_1.encrypt_transport(p)
- p = (peer_1.mk_tunnel_header(self.pg1) /
- (Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(receiver_index=peer_1.sender,
- counter=0,
- encrypted_encapsulated_packet=d)))
- rxs = self.send_and_expect(self.pg1, [p], self.pg0,
- worker=0)
+ p = peer_1.mk_tunnel_header(self.pg1) / (
+ Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
+ receiver_index=peer_1.sender, counter=0, encrypted_encapsulated_packet=d
+ )
+ )
+ rxs = self.send_and_expect(self.pg1, [p], self.pg0, worker=0)
for rx in rxs:
self.assertEqual(rx[IP].dst, self.pg0.remote_ip4)
@@ -1360,23 +1494,34 @@ class WireguardHandoffTests(TestWg):
# send a packets that are routed into the tunnel
# and pins the peer tp worker 1
- pe = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
- IP(src=self.pg0.remote_ip4, dst="10.11.3.2") /
- UDP(sport=555, dport=556) /
- Raw(b'\x00' * 80))
+ pe = (
+ Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
+ / IP(src=self.pg0.remote_ip4, dst="10.11.3.2")
+ / UDP(sport=555, dport=556)
+ / Raw(b"\x00" * 80)
+ )
rxs = self.send_and_expect(self.pg0, pe * 255, self.pg1, worker=1)
peer_1.validate_encapped(rxs, pe)
# send packets into the tunnel, from the other worker
- p = [(peer_1.mk_tunnel_header(self.pg1) /
- Wireguard(message_type=4, reserved_zero=0) /
- WireguardTransport(
+ p = [
+ (
+ peer_1.mk_tunnel_header(self.pg1)
+ / Wireguard(message_type=4, reserved_zero=0)
+ / WireguardTransport(
receiver_index=peer_1.sender,
- counter=ii+1,
+ counter=ii + 1,
encrypted_encapsulated_packet=peer_1.encrypt_transport(
- (IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20) /
- UDP(sport=222, dport=223) /
- Raw())))) for ii in range(255)]
+ (
+ IP(src="10.11.3.1", dst=self.pg0.remote_ip4, ttl=20)
+ / UDP(sport=222, dport=223)
+ / Raw()
+ )
+ ),
+ )
+ )
+ for ii in range(255)
+ ]
rxs = self.send_and_expect(self.pg1, p, self.pg0, worker=1)
@@ -1396,4 +1541,4 @@ class WireguardHandoffTests(TestWg):
@unittest.skip("test disabled")
def test_wg_multi_interface(self):
- """ Multi-tunnel on the same port """
+ """Multi-tunnel on the same port"""
diff --git a/test/util.py b/test/util.py
index 2c24571c350..249bd864259 100644
--- a/test/util.py
+++ b/test/util.py
@@ -11,8 +11,12 @@ from collections import UserDict
import scapy.compat
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP
-from scapy.layers.inet6 import IPv6, IPv6ExtHdrFragment, IPv6ExtHdrRouting,\
- IPv6ExtHdrHopByHop
+from scapy.layers.inet6 import (
+ IPv6,
+ IPv6ExtHdrFragment,
+ IPv6ExtHdrRouting,
+ IPv6ExtHdrHopByHop,
+)
from scapy.packet import Raw
from scapy.utils import hexdump
from scapy.utils6 import in6_mactoifaceid
@@ -21,7 +25,7 @@ from io import BytesIO
from vpp_papi import mac_pton
# Set up an empty logger for the testcase that can be overridden as necessary
-null_logger = logging.getLogger('VppTestCase.util')
+null_logger = logging.getLogger("VppTestCase.util")
null_logger.addHandler(logging.NullHandler())
@@ -30,14 +34,16 @@ def pr(packet):
def ppp(headline, packet):
- """ Return string containing headline and output of scapy packet.show() """
- return '%s\n%s\n\n%s\n' % (headline,
- hexdump(packet, dump=True),
- packet.show(dump=True))
+ """Return string containing headline and output of scapy packet.show()"""
+ return "%s\n%s\n\n%s\n" % (
+ headline,
+ hexdump(packet, dump=True),
+ packet.show(dump=True),
+ )
def ppc(headline, capture, limit=10):
- """ Return string containing ppp() printout for a capture.
+ """Return string containing ppp() printout for a capture.
:param headline: printed as first line of output
:param capture: packets to print
@@ -48,14 +54,17 @@ def ppc(headline, capture, limit=10):
tail = ""
if limit < len(capture):
tail = "\nPrint limit reached, %s out of %s packets printed" % (
- limit, len(capture))
- body = "".join([ppp("Packet #%s:" % count, p)
- for count, p in zip(range(0, limit), capture)])
+ limit,
+ len(capture),
+ )
+ body = "".join(
+ [ppp("Packet #%s:" % count, p) for count, p in zip(range(0, limit), capture)]
+ )
return "%s\n%s%s" % (headline, body, tail)
def ip4_range(ip4, s, e):
- tmp = ip4.rsplit('.', 1)[0]
+ tmp = ip4.rsplit(".", 1)[0]
return ("%s.%d" % (tmp, i) for i in range(s, e))
@@ -65,14 +74,18 @@ def mcast_ip_to_mac(ip):
raise ValueError("Must be multicast address.")
ip_as_int = int(ip)
if ip.version == 4:
- mcast_mac = "01:00:5e:%02x:%02x:%02x" % ((ip_as_int >> 16) & 0x7f,
- (ip_as_int >> 8) & 0xff,
- ip_as_int & 0xff)
+ mcast_mac = "01:00:5e:%02x:%02x:%02x" % (
+ (ip_as_int >> 16) & 0x7F,
+ (ip_as_int >> 8) & 0xFF,
+ ip_as_int & 0xFF,
+ )
else:
- mcast_mac = "33:33:%02x:%02x:%02x:%02x" % ((ip_as_int >> 24) & 0xff,
- (ip_as_int >> 16) & 0xff,
- (ip_as_int >> 8) & 0xff,
- ip_as_int & 0xff)
+ mcast_mac = "33:33:%02x:%02x:%02x:%02x" % (
+ (ip_as_int >> 24) & 0xFF,
+ (ip_as_int >> 16) & 0xFF,
+ (ip_as_int >> 8) & 0xFF,
+ ip_as_int & 0xFF,
+ )
return mcast_mac
@@ -84,8 +97,7 @@ def mk_ll_addr(mac):
def ip6_normalize(ip6):
- return socket.inet_ntop(socket.AF_INET6,
- socket.inet_pton(socket.AF_INET6, ip6))
+ return socket.inet_ntop(socket.AF_INET6, socket.inet_pton(socket.AF_INET6, ip6))
def get_core_path(tempdir):
@@ -107,13 +119,14 @@ def check_core_path(logger, core_path):
if corefmt.startswith("|"):
logger.error(
"WARNING: redirecting the core dump through a"
- " filter may result in truncated dumps.")
+ " filter may result in truncated dumps."
+ )
logger.error(
" You may want to check the filter settings"
" or uninstall it and edit the"
- " /proc/sys/kernel/core_pattern accordingly.")
- logger.error(
- " current core pattern is: %s" % corefmt)
+ " /proc/sys/kernel/core_pattern accordingly."
+ )
+ logger.error(" current core pattern is: %s" % corefmt)
class NumericConstant:
@@ -136,55 +149,57 @@ class NumericConstant:
class Host:
- """ Generic test host "connected" to VPPs interface. """
+ """Generic test host "connected" to VPPs interface."""
@property
def mac(self):
- """ MAC address """
+ """MAC address"""
return self._mac
@property
def bin_mac(self):
- """ MAC address """
+ """MAC address"""
return mac_pton(self._mac)
@property
def ip4(self):
- """ IPv4 address - string """
+ """IPv4 address - string"""
return self._ip4
@property
def ip4n(self):
- """ IPv4 address of remote host - raw, suitable as API parameter."""
+ """IPv4 address of remote host - raw, suitable as API parameter."""
return socket.inet_pton(socket.AF_INET, self._ip4)
@property
def ip6(self):
- """ IPv6 address - string """
+ """IPv6 address - string"""
return self._ip6
@property
def ip6n(self):
- """ IPv6 address of remote host - raw, suitable as API parameter."""
+ """IPv6 address of remote host - raw, suitable as API parameter."""
return socket.inet_pton(socket.AF_INET6, self._ip6)
@property
def ip6_ll(self):
- """ IPv6 link-local address - string """
+ """IPv6 link-local address - string"""
return self._ip6_ll
@property
def ip6n_ll(self):
- """ IPv6 link-local address of remote host -
+ """IPv6 link-local address of remote host -
raw, suitable as API parameter."""
return socket.inet_pton(socket.AF_INET6, self._ip6_ll)
def __eq__(self, other):
if isinstance(other, Host):
- return (self.mac == other.mac and
- self.ip4 == other.ip4 and
- self.ip6 == other.ip6 and
- self.ip6_ll == other.ip6_ll)
+ return (
+ self.mac == other.mac
+ and self.ip4 == other.ip4
+ and self.ip6 == other.ip6
+ and self.ip6_ll == other.ip6_ll
+ )
else:
return False
@@ -192,10 +207,12 @@ class Host:
return not self.__eq__(other)
def __repr__(self):
- return "Host { mac:%s ip4:%s ip6:%s ip6_ll:%s }" % (self.mac,
- self.ip4,
- self.ip6,
- self.ip6_ll)
+ return "Host { mac:%s ip4:%s ip6:%s ip6_ll:%s }" % (
+ self.mac,
+ self.ip4,
+ self.ip6,
+ self.ip6_ll,
+ )
def __hash__(self):
return hash(self.__repr__())
@@ -207,8 +224,8 @@ class Host:
self._ip6_ll = ip6_ll
-class L4_Conn():
- """ L4 'connection' tied to two VPP interfaces """
+class L4_Conn:
+ """L4 'connection' tied to two VPP interfaces"""
def __init__(self, testcase, if1, if2, af, l4proto, port1, port2):
self.testcase = testcase
@@ -228,22 +245,25 @@ class L4_Conn():
s1 = 1 - side
src_if = self.ifs[s0]
dst_if = self.ifs[s1]
- layer_3 = [IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4),
- IPv6(src=src_if.remote_ip6, dst=dst_if.remote_ip6)]
- merged_l4args = {'sport': self.ports[s0], 'dport': self.ports[s1]}
+ layer_3 = [
+ IP(src=src_if.remote_ip4, dst=dst_if.remote_ip4),
+ IPv6(src=src_if.remote_ip6, dst=dst_if.remote_ip6),
+ ]
+ merged_l4args = {"sport": self.ports[s0], "dport": self.ports[s1]}
merged_l4args.update(l4args)
- p = (Ether(dst=src_if.local_mac, src=src_if.remote_mac) /
- layer_3[is_ip6] /
- self.l4proto(**merged_l4args) /
- Raw(payload))
+ p = (
+ Ether(dst=src_if.local_mac, src=src_if.remote_mac)
+ / layer_3[is_ip6]
+ / self.l4proto(**merged_l4args)
+ / Raw(payload)
+ )
return p
def send(self, side, flags=None, payload=""):
l4args = {}
if flags is not None:
- l4args['flags'] = flags
- self.ifs[side].add_stream(self.pkt(side,
- l4args=l4args, payload=payload))
+ l4args["flags"] = flags
+ self.ifs[side].add_stream(self.pkt(side, l4args=l4args, payload=payload))
self.ifs[1 - side].enable_capture()
self.testcase.pg_start()
@@ -285,8 +305,8 @@ def fragment_rfc791(packet, fragsize, logger=null_logger):
pre_ip_len = len(packet) - len(packet[IP])
ip_header_len = packet[IP].ihl * 4
hex_packet = scapy.compat.raw(packet)
- hex_headers = hex_packet[:(pre_ip_len + ip_header_len)]
- hex_payload = hex_packet[(pre_ip_len + ip_header_len):]
+ hex_headers = hex_packet[: (pre_ip_len + ip_header_len)]
+ hex_payload = hex_packet[(pre_ip_len + ip_header_len) :]
pkts = []
ihl = packet[IP].ihl
@@ -294,14 +314,14 @@ def fragment_rfc791(packet, fragsize, logger=null_logger):
nfb = int((fragsize - pre_ip_len - ihl * 4) / 8)
fo = packet[IP].frag
- p = packet.__class__(hex_headers + hex_payload[:nfb * 8])
+ p = packet.__class__(hex_headers + hex_payload[: nfb * 8])
p[IP].flags = "MF"
p[IP].frag = fo
p[IP].len = ihl * 4 + nfb * 8
del p[IP].chksum
pkts.append(p)
- p = packet.__class__(hex_headers + hex_payload[nfb * 8:])
+ p = packet.__class__(hex_headers + hex_payload[nfb * 8 :])
p[IP].len = otl - nfb * 8
p[IP].frag = fo + nfb
del p[IP].chksum
@@ -345,15 +365,19 @@ def fragment_rfc8200(packet, identification, fragsize, logger=null_logger):
routing_hdr = counter
elif l.__class__ is IPv6ExtHdrHopByHop:
hop_by_hop_hdr = counter
- elif seen_ipv6 and not upper_layer and \
- not l.__class__.__name__.startswith('IPv6ExtHdr'):
+ elif (
+ seen_ipv6
+ and not upper_layer
+ and not l.__class__.__name__.startswith("IPv6ExtHdr")
+ ):
upper_layer = counter
counter = counter + 1
l = packet.getlayer(counter)
logger.debug(
- "Layers seen: IPv6(#%s), Routing(#%s), HopByHop(#%s), upper(#%s)" %
- (ipv6_nr, routing_hdr, hop_by_hop_hdr, upper_layer))
+ "Layers seen: IPv6(#%s), Routing(#%s), HopByHop(#%s), upper(#%s)"
+ % (ipv6_nr, routing_hdr, hop_by_hop_hdr, upper_layer)
+ )
if upper_layer is None:
raise Exception("Upper layer header not found in IPv6 packet")
@@ -379,18 +403,27 @@ def fragment_rfc8200(packet, identification, fragsize, logger=null_logger):
logger.debug(ppp("Fragment header:", fragment_ext_hdr))
len_ext_and_upper_layer_payload = len(ext_and_upper_layer.payload)
- if not len_ext_and_upper_layer_payload and \
- hasattr(ext_and_upper_layer, "data"):
+ if not len_ext_and_upper_layer_payload and hasattr(ext_and_upper_layer, "data"):
len_ext_and_upper_layer_payload = len(ext_and_upper_layer.data)
- if len(per_fragment_headers) + len(fragment_ext_hdr) +\
- len(ext_and_upper_layer) - len_ext_and_upper_layer_payload\
- > fragsize:
- raise Exception("Cannot fragment this packet - MTU too small "
- "(%s, %s, %s, %s, %s)" % (
- len(per_fragment_headers), len(fragment_ext_hdr),
- len(ext_and_upper_layer),
- len_ext_and_upper_layer_payload, fragsize))
+ if (
+ len(per_fragment_headers)
+ + len(fragment_ext_hdr)
+ + len(ext_and_upper_layer)
+ - len_ext_and_upper_layer_payload
+ > fragsize
+ ):
+ raise Exception(
+ "Cannot fragment this packet - MTU too small "
+ "(%s, %s, %s, %s, %s)"
+ % (
+ len(per_fragment_headers),
+ len(fragment_ext_hdr),
+ len(ext_and_upper_layer),
+ len_ext_and_upper_layer_payload,
+ fragsize,
+ )
+ )
orig_nh = packet[IPv6].nh
p = per_fragment_headers
@@ -399,7 +432,7 @@ def fragment_rfc8200(packet, identification, fragsize, logger=null_logger):
p = p / fragment_ext_hdr
del p[IPv6ExtHdrFragment].nh
first_payload_len_nfb = int((fragsize - len(p)) / 8)
- p = p / Raw(hex_payload[:first_payload_len_nfb * 8])
+ p = p / Raw(hex_payload[: first_payload_len_nfb * 8])
del p[IPv6].plen
p[IPv6ExtHdrFragment].nh = orig_nh
p[IPv6ExtHdrFragment].id = identification
@@ -417,7 +450,7 @@ def fragment_rfc8200(packet, identification, fragsize, logger=null_logger):
p = p / fragment_ext_hdr
del p[IPv6ExtHdrFragment].nh
l_nfb = int((fragsize - len(p)) / 8)
- p = p / Raw(hex_payload[offset:offset + l_nfb * 8])
+ p = p / Raw(hex_payload[offset : offset + l_nfb * 8])
p[IPv6ExtHdrFragment].nh = orig_nh
p[IPv6ExtHdrFragment].id = identification
p[IPv6ExtHdrFragment].offset = int(offset / 8)
@@ -437,11 +470,11 @@ def reassemble4_core(listoffragments, return_ip):
first = listoffragments[0]
buffer.seek(20)
for pkt in listoffragments:
- buffer.seek(pkt[IP].frag*8)
+ buffer.seek(pkt[IP].frag * 8)
buffer.write(bytes(pkt[IP].payload))
first.len = len(buffer.getvalue()) + 20
first.flags = 0
- del(first.chksum)
+ del first.chksum
if return_ip:
header = bytes(first[IP])[:20]
return first[IP].__class__(header + buffer.getvalue())
@@ -472,8 +505,7 @@ def recursive_dict_merge(dict_base, dict_update):
for key in dict_update:
if key in dict_base:
if type(dict_update[key]) is dict:
- dict_base[key] = recursive_dict_merge(dict_base[key],
- dict_update[key])
+ dict_base[key] = recursive_dict_merge(dict_base[key], dict_update[key])
else:
dict_base[key] = dict_update[key]
else:
diff --git a/test/vpp_acl.py b/test/vpp_acl.py
index 2d2f7ca257b..958d6973f26 100644
--- a/test/vpp_acl.py
+++ b/test/vpp_acl.py
@@ -7,7 +7,6 @@ from vpp_papi_provider import UnexpectedApiReturnValueError
class VppAclPlugin(VppObject):
-
def __init__(self, test, enable_intf_counters=False):
self._test = test
self.enable_intf_counters = enable_intf_counters
@@ -30,11 +29,11 @@ class VppAclPlugin(VppObject):
pass
def object_id(self):
- return ("acl-plugin-%d" % (self._sw_if_index))
+ return "acl-plugin-%d" % (self._sw_if_index)
-class AclRule():
- """ ACL Rule """
+class AclRule:
+ """ACL Rule"""
# port ranges
PORTS_ALL = -1
@@ -70,10 +69,18 @@ class AclRule():
icmp6_code_from_2 = 8
icmp6_code_to_2 = 42
- def __init__(self, is_permit, src_prefix=IPv4Network('0.0.0.0/0'),
- dst_prefix=IPv4Network('0.0.0.0/0'),
- proto=0, ports=PORTS_ALL, sport_from=None, sport_to=None,
- dport_from=None, dport_to=None):
+ def __init__(
+ self,
+ is_permit,
+ src_prefix=IPv4Network("0.0.0.0/0"),
+ dst_prefix=IPv4Network("0.0.0.0/0"),
+ proto=0,
+ ports=PORTS_ALL,
+ sport_from=None,
+ sport_to=None,
+ dport_from=None,
+ dport_to=None,
+ ):
self.is_permit = is_permit
self.src_prefix = src_prefix
self.dst_prefix = dst_prefix
@@ -92,9 +99,17 @@ class AclRule():
self.dport_to = dport_to
def __copy__(self):
- new_rule = AclRule(self.is_permit, self.src_prefix, self.dst_prefix,
- self._proto, self._ports, self.sport_from,
- self.sport_to, self.dport_from, self.dport_to)
+ new_rule = AclRule(
+ self.is_permit,
+ self.src_prefix,
+ self.dst_prefix,
+ self._proto,
+ self._ports,
+ self.sport_from,
+ self.sport_to,
+ self.dport_from,
+ self.dport_to,
+ )
return new_rule
def update_ports(self):
@@ -172,17 +187,20 @@ class AclRule():
self.update_ports()
def encode(self):
- return {'is_permit': self.is_permit, 'proto': self.proto,
- 'srcport_or_icmptype_first': self.sport_from,
- 'srcport_or_icmptype_last': self.sport_to,
- 'src_prefix': self.src_prefix,
- 'dstport_or_icmpcode_first': self.dport_from,
- 'dstport_or_icmpcode_last': self.dport_to,
- 'dst_prefix': self.dst_prefix}
+ return {
+ "is_permit": self.is_permit,
+ "proto": self.proto,
+ "srcport_or_icmptype_first": self.sport_from,
+ "srcport_or_icmptype_last": self.sport_to,
+ "src_prefix": self.src_prefix,
+ "dstport_or_icmpcode_first": self.dport_from,
+ "dstport_or_icmpcode_last": self.dport_to,
+ "dst_prefix": self.dst_prefix,
+ }
class VppAcl(VppObject):
- """ VPP ACL """
+ """VPP ACL"""
def __init__(self, test, rules, acl_index=INVALID_INDEX, tag=None):
self._test = test
@@ -211,8 +229,11 @@ class VppAcl(VppObject):
def add_vpp_config(self, expect_error=False):
try:
reply = self._test.vapi.acl_add_replace(
- acl_index=self._acl_index, tag=self.tag, count=self.count,
- r=self.encode_rules())
+ acl_index=self._acl_index,
+ tag=self.tag,
+ count=self.count,
+ r=self.encode_rules(),
+ )
self._acl_index = reply.acl_index
self._test.registry.register(self, self._test.logger)
if expect_error:
@@ -247,11 +268,11 @@ class VppAcl(VppObject):
return False
def object_id(self):
- return ("acl-%s-%d" % (self.tag, self._acl_index))
+ return "acl-%s-%d" % (self.tag, self._acl_index)
class VppEtypeWhitelist(VppObject):
- """ VPP Etype Whitelist """
+ """VPP Etype Whitelist"""
def __init__(self, test, sw_if_index, whitelist, n_input=0):
self._test = test
@@ -269,26 +290,31 @@ class VppEtypeWhitelist(VppObject):
def add_vpp_config(self):
self._test.vapi.acl_interface_set_etype_whitelist(
- sw_if_index=self._sw_if_index, count=self.count,
- n_input=self.n_input, whitelist=self.whitelist)
+ sw_if_index=self._sw_if_index,
+ count=self.count,
+ n_input=self.n_input,
+ whitelist=self.whitelist,
+ )
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
self._test.vapi.acl_interface_set_etype_whitelist(
- sw_if_index=self._sw_if_index, count=0, n_input=0, whitelist=[])
+ sw_if_index=self._sw_if_index, count=0, n_input=0, whitelist=[]
+ )
def query_vpp_config(self):
self._test.vapi.acl_interface_etype_whitelist_dump(
- sw_if_index=self._sw_if_index)
+ sw_if_index=self._sw_if_index
+ )
return False
def object_id(self):
- return ("acl-etype_wl-%d" % (self._sw_if_index))
+ return "acl-etype_wl-%d" % (self._sw_if_index)
class VppAclInterface(VppObject):
- """ VPP ACL Interface """
+ """VPP ACL Interface"""
def __init__(self, test, sw_if_index, acls, n_input=0):
self._test = test
@@ -313,8 +339,11 @@ class VppAclInterface(VppObject):
def add_vpp_config(self, expect_error=False):
try:
reply = self._test.vapi.acl_interface_set_acl_list(
- sw_if_index=self._sw_if_index, n_input=self.n_input,
- count=self.count, acls=self.encode_acls())
+ sw_if_index=self._sw_if_index,
+ n_input=self.n_input,
+ count=self.count,
+ acls=self.encode_acls(),
+ )
self._test.registry.register(self, self._test.logger)
if expect_error:
self._test.fail("Unexpected api reply")
@@ -327,7 +356,8 @@ class VppAclInterface(VppObject):
def remove_vpp_config(self, expect_error=False):
try:
reply = self._test.vapi.acl_interface_set_acl_list(
- sw_if_index=self._sw_if_index, n_input=0, count=0, acls=[])
+ sw_if_index=self._sw_if_index, n_input=0, count=0, acls=[]
+ )
if expect_error:
self._test.fail("Unexpected api reply")
except UnexpectedApiReturnValueError:
@@ -335,35 +365,38 @@ class VppAclInterface(VppObject):
self._test.fail("Unexpected api reply")
def query_vpp_config(self):
- dump = self._test.vapi.acl_interface_list_dump(
- sw_if_index=self._sw_if_index)
+ dump = self._test.vapi.acl_interface_list_dump(sw_if_index=self._sw_if_index)
for acl_list in dump:
if acl_list.count > 0:
return True
return False
def object_id(self):
- return ("acl-if-list-%d" % (self._sw_if_index))
+ return "acl-if-list-%d" % (self._sw_if_index)
-class MacipRule():
- """ Mac Ip rule """
+class MacipRule:
+ """Mac Ip rule"""
- def __init__(self, is_permit, src_mac=0, src_mac_mask=0,
- src_prefix=IPv4Network('0.0.0.0/0')):
+ def __init__(
+ self, is_permit, src_mac=0, src_mac_mask=0, src_prefix=IPv4Network("0.0.0.0/0")
+ ):
self.is_permit = is_permit
self.src_mac = src_mac
self.src_mac_mask = src_mac_mask
self.src_prefix = src_prefix
def encode(self):
- return {'is_permit': self.is_permit, 'src_mac': self.src_mac,
- 'src_mac_mask': self.src_mac_mask,
- 'src_prefix': self.src_prefix}
+ return {
+ "is_permit": self.is_permit,
+ "src_mac": self.src_mac,
+ "src_mac_mask": self.src_mac_mask,
+ "src_prefix": self.src_prefix,
+ }
class VppMacipAcl(VppObject):
- """ Vpp Mac Ip ACL """
+ """Vpp Mac Ip ACL"""
def __init__(self, test, rules, acl_index=INVALID_INDEX, tag=None):
self._test = test
@@ -392,8 +425,11 @@ class VppMacipAcl(VppObject):
def add_vpp_config(self, expect_error=False):
try:
reply = self._test.vapi.macip_acl_add_replace(
- acl_index=self._acl_index, tag=self.tag, count=self.count,
- r=self.encode_rules())
+ acl_index=self._acl_index,
+ tag=self.tag,
+ count=self.count,
+ r=self.encode_rules(),
+ )
self._acl_index = reply.acl_index
self._test.registry.register(self, self._test.logger)
if expect_error:
@@ -428,11 +464,11 @@ class VppMacipAcl(VppObject):
return False
def object_id(self):
- return ("macip-acl-%s-%d" % (self.tag, self._acl_index))
+ return "macip-acl-%s-%d" % (self.tag, self._acl_index)
class VppMacipAclInterface(VppObject):
- """ VPP Mac Ip ACL Interface """
+ """VPP Mac Ip ACL Interface"""
def __init__(self, test, sw_if_index, acls):
self._test = test
@@ -450,19 +486,20 @@ class VppMacipAclInterface(VppObject):
def add_vpp_config(self):
for acl in self.acls:
self._test.vapi.macip_acl_interface_add_del(
- is_add=True, sw_if_index=self._sw_if_index,
- acl_index=acl.acl_index)
+ is_add=True, sw_if_index=self._sw_if_index, acl_index=acl.acl_index
+ )
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
for acl in self.acls:
self._test.vapi.macip_acl_interface_add_del(
- is_add=False, sw_if_index=self._sw_if_index,
- acl_index=acl.acl_index)
+ is_add=False, sw_if_index=self._sw_if_index, acl_index=acl.acl_index
+ )
def dump(self):
return self._test.vapi.macip_acl_interface_list_dump(
- sw_if_index=self._sw_if_index)
+ sw_if_index=self._sw_if_index
+ )
def query_vpp_config(self):
dump = self.dump()
@@ -473,4 +510,4 @@ class VppMacipAclInterface(VppObject):
return False
def object_id(self):
- return ("macip-acl-if-list-%d" % (self._sw_if_index))
+ return "macip-acl-if-list-%d" % (self._sw_if_index)
diff --git a/test/vpp_bier.py b/test/vpp_bier.py
index 6e087a8ee0b..9fdaf1faa1c 100644
--- a/test/vpp_bier.py
+++ b/test/vpp_bier.py
@@ -18,7 +18,7 @@ class BIER_HDR_PAYLOAD:
BIER_HDR_PROTO_OAM = 8
-class VppBierTableID():
+class VppBierTableID:
def __init__(self, sub_domain_id, set_id, hdr_len_id):
self.set_id = set_id
self.sub_domain_id = sub_domain_id
@@ -28,9 +28,11 @@ class VppBierTableID():
def find_bier_table(test, bti):
tables = test.vapi.bier_table_dump()
for t in tables:
- if bti.set_id == t.bt_tbl_id.bt_set \
- and bti.sub_domain_id == t.bt_tbl_id.bt_sub_domain \
- and bti.hdr_len_id == t.bt_tbl_id.bt_hdr_len_id:
+ if (
+ bti.set_id == t.bt_tbl_id.bt_set
+ and bti.sub_domain_id == t.bt_tbl_id.bt_sub_domain
+ and bti.hdr_len_id == t.bt_tbl_id.bt_hdr_len_id
+ ):
return True
return False
@@ -38,10 +40,12 @@ def find_bier_table(test, bti):
def find_bier_route(test, bti, bp):
routes = test.vapi.bier_route_dump(bti)
for r in routes:
- if bti.set_id == r.br_route.br_tbl_id.bt_set \
- and bti.sub_domain_id == r.br_route.br_tbl_id.bt_sub_domain \
- and bti.hdr_len_id == r.br_route.br_tbl_id.bt_hdr_len_id \
- and bp == r.br_route.br_bp:
+ if (
+ bti.set_id == r.br_route.br_tbl_id.bt_set
+ and bti.sub_domain_id == r.br_route.br_tbl_id.bt_sub_domain
+ and bti.hdr_len_id == r.br_route.br_tbl_id.bt_hdr_len_id
+ and bp == r.br_route.br_bp
+ ):
return True
return False
@@ -57,8 +61,7 @@ def find_bier_disp_table(test, bdti):
def find_bier_disp_entry(test, bdti, bp):
entries = test.vapi.bier_disp_entry_dump(bdti)
for e in entries:
- if bp == e.bde_bp \
- and bdti == e.bde_tbl_id:
+ if bp == e.bde_bp and bdti == e.bde_tbl_id:
return True
return False
@@ -66,10 +69,12 @@ def find_bier_disp_entry(test, bdti, bp):
def find_bier_imp(test, bti, bp):
imps = test.vapi.bier_imp_dump()
for i in imps:
- if bti.set_id == i.bi_tbl_id.bt_set \
- and bti.sub_domain_id == i.bi_tbl_id.bt_sub_domain \
- and bti.hdr_len_id == i.bi_tbl_id.bt_hdr_len_id \
- and bp == i.bi_src:
+ if (
+ bti.set_id == i.bi_tbl_id.bt_set
+ and bti.sub_domain_id == i.bi_tbl_id.bt_sub_domain
+ and bti.hdr_len_id == i.bi_tbl_id.bt_hdr_len_id
+ and bp == i.bi_src
+ ):
return True
return False
@@ -85,22 +90,18 @@ class VppBierTable(VppObject):
self.mpls_label = mpls_label
def add_vpp_config(self):
- self._test.vapi.bier_table_add_del(
- self.id,
- self.mpls_label,
- is_add=1)
+ self._test.vapi.bier_table_add_del(self.id, self.mpls_label, is_add=1)
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
- self._test.vapi.bier_table_add_del(
- self.id,
- self.mpls_label,
- is_add=0)
+ self._test.vapi.bier_table_add_del(self.id, self.mpls_label, is_add=0)
def object_id(self):
- return "bier-table;[%d:%d:%d]" % (self.id.set_id,
- self.id.sub_domain_id,
- self.id.hdr_len_id)
+ return "bier-table;[%d:%d:%d]" % (
+ self.id.set_id,
+ self.id.sub_domain_id,
+ self.id.hdr_len_id,
+ )
def query_vpp_config(self):
return find_bier_table(self._test, self.id)
@@ -122,18 +123,14 @@ class VppBierRoute(VppObject):
def add_vpp_config(self):
self._test.vapi.bier_route_add_del(
- self.tbl_id,
- self.bp,
- self.encoded_paths,
- is_add=1)
+ self.tbl_id, self.bp, self.encoded_paths, is_add=1
+ )
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
self._test.vapi.bier_route_add_del(
- self.tbl_id,
- self.bp,
- self.encoded_paths,
- is_add=0)
+ self.tbl_id, self.bp, self.encoded_paths, is_add=0
+ )
def update_paths(self, paths):
self.paths = paths
@@ -141,46 +138,37 @@ class VppBierRoute(VppObject):
for path in self.paths:
self.encoded_paths.append(path.encode())
self._test.vapi.bier_route_add_del(
- self.tbl_id,
- self.bp,
- self.encoded_paths,
- is_replace=1)
+ self.tbl_id, self.bp, self.encoded_paths, is_replace=1
+ )
def add_path(self, path):
self.encoded_paths.append(path.encode())
self._test.vapi.bier_route_add_del(
- self.tbl_id,
- self.bp,
- [path.encode()],
- is_add=1,
- is_replace=0)
+ self.tbl_id, self.bp, [path.encode()], is_add=1, is_replace=0
+ )
self.paths.append(path)
self._test.registry.register(self, self._test.logger)
def remove_path(self, path):
self.encoded_paths.remove(path.encode())
self._test.vapi.bier_route_add_del(
- self.tbl_id,
- self.bp,
- [path.encode()],
- is_add=0,
- is_replace=0)
+ self.tbl_id, self.bp, [path.encode()], is_add=0, is_replace=0
+ )
self.paths.remove(path)
def remove_all_paths(self):
self._test.vapi.bier_route_add_del(
- self.tbl_id,
- self.bp,
- [],
- is_add=0,
- is_replace=1)
+ self.tbl_id, self.bp, [], is_add=0, is_replace=1
+ )
self.paths = []
def object_id(self):
- return "bier-route;[%d:%d:%d:%d]" % (self.tbl_id.set_id,
- self.tbl_id.sub_domain_id,
- self.tbl_id.hdr_len_id,
- self.bp)
+ return "bier-route;[%d:%d:%d:%d]" % (
+ self.tbl_id.set_id,
+ self.tbl_id.sub_domain_id,
+ self.tbl_id.hdr_len_id,
+ self.bp,
+ )
def query_vpp_config(self):
return find_bier_route(self._test, self.tbl_id, self.bp)
@@ -198,22 +186,20 @@ class VppBierImp(VppObject):
self.src = src
def add_vpp_config(self):
- res = self._test.vapi.bier_imp_add(
- self.tbl_id,
- self.src,
- self.ibytes)
+ res = self._test.vapi.bier_imp_add(self.tbl_id, self.src, self.ibytes)
self.bi_index = res.bi_index
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
- self._test.vapi.bier_imp_del(
- self.bi_index)
+ self._test.vapi.bier_imp_del(self.bi_index)
def object_id(self):
- return "bier-imp;[%d:%d:%d:%d]" % (self.tbl_id.set_id,
- self.tbl_id.sub_domain_id,
- self.tbl_id.hdr_len_id,
- self.src)
+ return "bier-imp;[%d:%d:%d:%d]" % (
+ self.tbl_id.set_id,
+ self.tbl_id.sub_domain_id,
+ self.tbl_id.hdr_len_id,
+ self.src,
+ )
def query_vpp_config(self):
return find_bier_imp(self._test, self.tbl_id, self.src)
@@ -229,15 +215,11 @@ class VppBierDispTable(VppObject):
self.id = id
def add_vpp_config(self):
- self._test.vapi.bier_disp_table_add_del(
- self.id,
- is_add=1)
+ self._test.vapi.bier_disp_table_add_del(self.id, is_add=1)
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
- self._test.vapi.bier_disp_table_add_del(
- self.id,
- is_add=0)
+ self._test.vapi.bier_disp_table_add_del(self.id, is_add=0)
def object_id(self):
return "bier-disp-table;[%d]" % (self.id)
@@ -251,8 +233,9 @@ class VppBierDispEntry(VppObject):
BIER Disposition Entry
"""
- def __init__(self, test, tbl_id, bp, payload_proto, nh_proto,
- nh, nh_tbl, rpf_id=~0):
+ def __init__(
+ self, test, tbl_id, bp, payload_proto, nh_proto, nh, nh_tbl, rpf_id=~0
+ ):
self._test = test
self.tbl_id = tbl_id
self.nh_tbl = nh_tbl
@@ -271,7 +254,8 @@ class VppBierDispEntry(VppObject):
self.nh,
self.nh_tbl,
self.rpf_id,
- is_add=1)
+ is_add=1,
+ )
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
@@ -283,11 +267,11 @@ class VppBierDispEntry(VppObject):
self.nh,
self.nh_tbl,
self.rpf_id,
- is_add=0)
+ is_add=0,
+ )
def object_id(self):
- return "bier-disp-entry;[%d:%d]" % (self.tbl_id,
- self.bp)
+ return "bier-disp-entry;[%d:%d]" % (self.tbl_id, self.bp)
def query_vpp_config(self):
return find_bier_disp_entry(self._test, self.tbl_id, self.bp)
diff --git a/test/vpp_bond_interface.py b/test/vpp_bond_interface.py
index 60c1ac1557b..636315cfce2 100644
--- a/test/vpp_bond_interface.py
+++ b/test/vpp_bond_interface.py
@@ -5,10 +5,19 @@ from vpp_interface import VppInterface
class VppBondInterface(VppInterface):
"""VPP bond interface."""
- def __init__(self, test, mode, lb=0, numa_only=0, enable_gso=0,
- use_custom_mac=0, mac_address='', id=0xFFFFFFFF):
-
- """ Create VPP Bond interface """
+ def __init__(
+ self,
+ test,
+ mode,
+ lb=0,
+ numa_only=0,
+ enable_gso=0,
+ use_custom_mac=0,
+ mac_address="",
+ id=0xFFFFFFFF,
+ ):
+
+ """Create VPP Bond interface"""
super(VppBondInterface, self).__init__(test)
self.mode = mode
self.lb = lb
@@ -19,29 +28,28 @@ class VppBondInterface(VppInterface):
self.id = id
def add_vpp_config(self):
- r = self.test.vapi.bond_create2(self.mode,
- self.lb,
- self.numa_only,
- self.enable_gso,
- self.use_custom_mac,
- self.mac_address,
- self.id)
+ r = self.test.vapi.bond_create2(
+ self.mode,
+ self.lb,
+ self.numa_only,
+ self.enable_gso,
+ self.use_custom_mac,
+ self.mac_address,
+ self.id,
+ )
self.set_sw_if_index(r.sw_if_index)
def remove_vpp_config(self):
self.test.vapi.bond_delete(self.sw_if_index)
- def add_member_vpp_bond_interface(self,
- sw_if_index,
- is_passive=0,
- is_long_timeout=0):
- self.test.vapi.bond_add_member(sw_if_index,
- self.sw_if_index,
- is_passive,
- is_long_timeout)
-
- def detach_vpp_bond_interface(self,
- sw_if_index):
+ def add_member_vpp_bond_interface(
+ self, sw_if_index, is_passive=0, is_long_timeout=0
+ ):
+ self.test.vapi.bond_add_member(
+ sw_if_index, self.sw_if_index, is_passive, is_long_timeout
+ )
+
+ def detach_vpp_bond_interface(self, sw_if_index):
self.test.vapi.bond_detach_member(sw_if_index)
def is_interface_config_in_dump(self, dump):
diff --git a/test/vpp_bvi_interface.py b/test/vpp_bvi_interface.py
index 7039f29ca8d..9ab80e91c14 100644
--- a/test/vpp_bvi_interface.py
+++ b/test/vpp_bvi_interface.py
@@ -6,13 +6,12 @@ class VppBviInterface(VppInterface, VppObject):
"""VPP bvi interface."""
def __init__(self, test):
- """ Create VPP BVI interface """
+ """Create VPP BVI interface"""
super(VppBviInterface, self).__init__(test)
self.add_vpp_config()
def add_vpp_config(self):
- r = self.test.vapi.bvi_create(user_instance=0xffffffff,
- mac="00:00:00:00:00:00")
+ r = self.test.vapi.bvi_create(user_instance=0xFFFFFFFF, mac="00:00:00:00:00:00")
self.set_sw_if_index(r.sw_if_index)
def remove_vpp_config(self):
diff --git a/test/vpp_devices.py b/test/vpp_devices.py
index 9e272cafe32..cff08e84435 100644
--- a/test/vpp_devices.py
+++ b/test/vpp_devices.py
@@ -2,27 +2,26 @@ from vpp_interface import VppInterface
class VppTAPInterface(VppInterface):
-
@property
def tap_id(self):
"""TAP id"""
return self._tap_id
- def __init__(self, test, tap_id=0xffffffff, mac_addr=None):
+ def __init__(self, test, tap_id=0xFFFFFFFF, mac_addr=None):
self._test = test
self._tap_id = tap_id
self._mac_addr = mac_addr
def get_vpp_dump(self):
- dump = self._test.vapi.sw_interface_tap_v2_dump(
- sw_if_index=self.sw_if_index)
+ dump = self._test.vapi.sw_interface_tap_v2_dump(sw_if_index=self.sw_if_index)
return dump
def add_vpp_config(self):
reply = self._test.vapi.tap_create_v2(
id=self._tap_id,
use_random_mac=bool(self._mac_addr),
- mac_address=self._mac_addr)
+ mac_address=self._mac_addr,
+ )
self.set_sw_if_index(reply.sw_if_index)
self._test.registry.register(self, self.test.logger)
diff --git a/test/vpp_dhcp.py b/test/vpp_dhcp.py
index f8265a26252..eb07df2ecd7 100644
--- a/test/vpp_dhcp.py
+++ b/test/vpp_dhcp.py
@@ -2,7 +2,6 @@ from vpp_object import VppObject
class VppDHCPProxy(VppObject):
-
def __init__(
self,
test,
@@ -17,14 +16,9 @@ class VppDHCPProxy(VppObject):
self._dhcp_server = dhcp_server
self._dhcp_src_address = dhcp_src_address
- def set_proxy(
- self,
- dhcp_server,
- dhcp_src_address,
- rx_vrf_id=0,
- server_vrf_id=0):
+ def set_proxy(self, dhcp_server, dhcp_src_address, rx_vrf_id=0, server_vrf_id=0):
if self.query_vpp_config():
- raise Exception('Vpp config present')
+ raise Exception("Vpp config present")
self._rx_vrf_id = rx_vrf_id
self._server_vrf_id = server_vrf_id
self._dhcp_server = dhcp_server
@@ -36,7 +30,8 @@ class VppDHCPProxy(VppObject):
rx_vrf_id=self._rx_vrf_id,
server_vrf_id=self._server_vrf_id,
dhcp_server=self._dhcp_server,
- dhcp_src_address=self._dhcp_src_address)
+ dhcp_src_address=self._dhcp_src_address,
+ )
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
@@ -45,7 +40,8 @@ class VppDHCPProxy(VppObject):
server_vrf_id=self._server_vrf_id,
dhcp_server=self._dhcp_server,
dhcp_src_address=self._dhcp_src_address,
- is_add=0)
+ is_add=0,
+ )
def get_vpp_dump(self):
dump = self._test.vapi.dhcp_proxy_dump()
@@ -62,17 +58,17 @@ class VppDHCPProxy(VppObject):
class VppDHCPClient(VppObject):
-
def __init__(
- self,
- test,
- sw_if_index,
- hostname,
- id=None,
- want_dhcp_event=False,
- set_broadcast_flag=True,
- dscp=None,
- pid=None):
+ self,
+ test,
+ sw_if_index,
+ hostname,
+ id=None,
+ want_dhcp_event=False,
+ set_broadcast_flag=True,
+ dscp=None,
+ pid=None,
+ ):
self._test = test
self._sw_if_index = sw_if_index
self._hostname = hostname
@@ -83,16 +79,17 @@ class VppDHCPClient(VppObject):
self._pid = pid
def set_client(
- self,
- sw_if_index,
- hostname,
- id=None,
- want_dhcp_event=False,
- set_broadcast_flag=True,
- dscp=None,
- pid=None):
+ self,
+ sw_if_index,
+ hostname,
+ id=None,
+ want_dhcp_event=False,
+ set_broadcast_flag=True,
+ dscp=None,
+ pid=None,
+ ):
if self.query_vpp_config():
- raise Exception('Vpp config present')
+ raise Exception("Vpp config present")
self._sw_if_index = sw_if_index
self._hostname = hostname
self._id = id
@@ -102,19 +99,21 @@ class VppDHCPClient(VppObject):
self._pid = pid
def add_vpp_config(self):
- id = self._id.encode('ascii') if self._id else None
- client = {'sw_if_index': self._sw_if_index, 'hostname': self._hostname,
- 'id': id,
- 'want_dhcp_event': self._want_dhcp_event,
- 'set_broadcast_flag': self._set_broadcast_flag,
- 'dscp': self._dscp, 'pid': self._pid}
+ id = self._id.encode("ascii") if self._id else None
+ client = {
+ "sw_if_index": self._sw_if_index,
+ "hostname": self._hostname,
+ "id": id,
+ "want_dhcp_event": self._want_dhcp_event,
+ "set_broadcast_flag": self._set_broadcast_flag,
+ "dscp": self._dscp,
+ "pid": self._pid,
+ }
self._test.vapi.dhcp_client_config(is_add=1, client=client)
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
- client = client = {
- 'sw_if_index': self._sw_if_index,
- 'hostname': self._hostname}
+ client = client = {"sw_if_index": self._sw_if_index, "hostname": self._hostname}
self._test.vapi.dhcp_client_config(client=client, is_add=0)
def get_vpp_dump(self):
diff --git a/test/vpp_gre_interface.py b/test/vpp_gre_interface.py
index 770292e80b8..9b02488349b 100644
--- a/test/vpp_gre_interface.py
+++ b/test/vpp_gre_interface.py
@@ -1,4 +1,3 @@
-
from vpp_interface import VppInterface
import socket
from vpp_papi import VppEnum
@@ -9,10 +8,18 @@ class VppGreInterface(VppInterface):
VPP GRE interface
"""
- def __init__(self, test, src_ip, dst_ip, outer_table_id=0,
- type=None, mode=None, flags=0,
- session=0):
- """ Create VPP GRE interface """
+ def __init__(
+ self,
+ test,
+ src_ip,
+ dst_ip,
+ outer_table_id=0,
+ type=None,
+ mode=None,
+ flags=0,
+ session=0,
+ ):
+ """Create VPP GRE interface"""
super(VppGreInterface, self).__init__(test)
self.t_src = src_ip
self.t_dst = dst_ip
@@ -21,25 +28,25 @@ class VppGreInterface(VppInterface):
self.t_flags = flags
self.t_type = type
if not self.t_type:
- self.t_type = (VppEnum.vl_api_gre_tunnel_type_t.
- GRE_API_TUNNEL_TYPE_L3)
+ self.t_type = VppEnum.vl_api_gre_tunnel_type_t.GRE_API_TUNNEL_TYPE_L3
self.t_mode = mode
if not self.t_mode:
- self.t_mode = (VppEnum.vl_api_tunnel_mode_t.
- TUNNEL_API_MODE_P2P)
+ self.t_mode = VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_P2P
def add_vpp_config(self):
r = self.test.vapi.gre_tunnel_add_del(
is_add=1,
tunnel={
- 'src': self.t_src,
- 'dst': self.t_dst,
- 'outer_table_id': self.t_outer_table,
- 'instance': 0xffffffff,
- 'type': self.t_type,
- 'mode': self.t_mode,
- 'flags': self.t_flags,
- 'session_id': self.t_session})
+ "src": self.t_src,
+ "dst": self.t_dst,
+ "outer_table_id": self.t_outer_table,
+ "instance": 0xFFFFFFFF,
+ "type": self.t_type,
+ "mode": self.t_mode,
+ "flags": self.t_flags,
+ "session_id": self.t_session,
+ },
+ )
self.set_sw_if_index(r.sw_if_index)
self.generate_remote_hosts()
self.test.registry.register(self, self.test.logger)
@@ -50,21 +57,22 @@ class VppGreInterface(VppInterface):
self.test.vapi.gre_tunnel_add_del(
is_add=0,
tunnel={
- 'src': self.t_src,
- 'dst': self.t_dst,
- 'outer_table_id': self.t_outer_table,
- 'instance': 0xffffffff,
- 'type': self.t_type,
- 'mode': self.t_mode,
- 'flags': self.t_flags,
- 'session_id': self.t_session})
+ "src": self.t_src,
+ "dst": self.t_dst,
+ "outer_table_id": self.t_outer_table,
+ "instance": 0xFFFFFFFF,
+ "type": self.t_type,
+ "mode": self.t_mode,
+ "flags": self.t_flags,
+ "session_id": self.t_session,
+ },
+ )
def object_id(self):
return "gre-%d" % self.sw_if_index
def query_vpp_config(self):
- return (self.test.vapi.gre_tunnel_dump(
- sw_if_index=self._sw_if_index))
+ return self.test.vapi.gre_tunnel_dump(sw_if_index=self._sw_if_index)
@property
def remote_ip(self):
diff --git a/test/vpp_igmp.py b/test/vpp_igmp.py
index 8f78a9b909a..da2beb0605d 100644
--- a/test/vpp_igmp.py
+++ b/test/vpp_igmp.py
@@ -1,4 +1,3 @@
-
from vpp_object import VppObject
import socket
@@ -15,22 +14,28 @@ class IGMP_FILTER:
def find_igmp_state(states, itf, gaddr, saddr):
for s in states:
- if s.sw_if_index == itf.sw_if_index and \
- str(s.gaddr) == gaddr and str(s.saddr) == saddr:
+ if (
+ s.sw_if_index == itf.sw_if_index
+ and str(s.gaddr) == gaddr
+ and str(s.saddr) == saddr
+ ):
return True
return False
def wait_for_igmp_event(test, timeout, itf, gaddr, saddr, ff):
ev = test.vapi.wait_for_event(timeout, "igmp_event")
- if ev.sw_if_index == itf.sw_if_index and \
- str(ev.gaddr) == gaddr and str(ev.saddr) == saddr and \
- ev.filter == ff:
+ if (
+ ev.sw_if_index == itf.sw_if_index
+ and str(ev.gaddr) == gaddr
+ and str(ev.saddr) == saddr
+ and ev.filter == ff
+ ):
return True
return False
-class IgmpSG():
+class IgmpSG:
def __init__(self, gaddr, saddrs):
self.gaddr = gaddr
self.gaddr_p = socket.inet_pton(socket.AF_INET, gaddr)
@@ -43,7 +48,7 @@ class IgmpSG():
self.saddrs_encoded.append(ss)
-class IgmpRecord():
+class IgmpRecord:
def __init__(self, sg, type):
self.sg = sg
self.type = type
@@ -58,15 +63,11 @@ class VppHostState(VppObject):
def add_vpp_config(self):
self._test.vapi.igmp_listen(
- self.filter, self.sw_if_index,
- self.sg.saddrs_encoded, self.sg.gaddr_p)
+ self.filter, self.sw_if_index, self.sg.saddrs_encoded, self.sg.gaddr_p
+ )
def remove_vpp_config(self):
- self._test.vapi.igmp_listen(
- self.filter,
- self.sw_if_index,
- [],
- self.sg.gaddr_p)
+ self._test.vapi.igmp_listen(self.filter, self.sw_if_index, [], self.sg.gaddr_p)
def object_id(self):
return "%s:%d" % (self.sg, self.sw_if_index)
diff --git a/test/vpp_ikev2.py b/test/vpp_ikev2.py
index de2081268ee..b9a6d8c2f7d 100644
--- a/test/vpp_ikev2.py
+++ b/test/vpp_ikev2.py
@@ -4,24 +4,24 @@ from vpp_papi import VppEnum
class AuthMethod:
- v = {'rsa-sig': 1,
- 'shared-key': 2}
+ v = {"rsa-sig": 1, "shared-key": 2}
@staticmethod
- def value(key): return AuthMethod.v[key]
+ def value(key):
+ return AuthMethod.v[key]
class IDType:
- v = {'ip4-addr': 1,
- 'fqdn': 2,
- 'ip6-addr': 5}
+ v = {"ip4-addr": 1, "fqdn": 2, "ip6-addr": 5}
@staticmethod
- def value(key): return IDType.v[key]
+ def value(key):
+ return IDType.v[key]
class Profile(VppObject):
- """ IKEv2 profile """
+ """IKEv2 profile"""
+
def __init__(self, test, profile_name):
self.test = test
self.vapi = test.vapi
@@ -38,49 +38,49 @@ class Profile(VppObject):
elif isinstance(method, str):
m = AuthMethod.value(method)
else:
- raise Exception('unsupported type {}'.format(method))
- self.auth = {'auth_method': m,
- 'data': data,
- 'is_hex': is_hex}
+ raise Exception("unsupported type {}".format(method))
+ self.auth = {"auth_method": m, "data": data, "is_hex": is_hex}
def add_local_id(self, id_type, data):
if isinstance(id_type, str):
t = IDType.value(id_type)
- self.local_id = {'id_type': t,
- 'data': data,
- 'is_local': True}
+ self.local_id = {"id_type": t, "data": data, "is_local": True}
def add_remote_id(self, id_type, data):
if isinstance(id_type, str):
t = IDType.value(id_type)
- self.remote_id = {'id_type': t,
- 'data': data,
- 'is_local': False}
+ self.remote_id = {"id_type": t, "data": data, "is_local": False}
- def add_local_ts(self, start_addr, end_addr, start_port=0, end_port=0xffff,
- proto=0, is_ip4=True):
+ def add_local_ts(
+ self, start_addr, end_addr, start_port=0, end_port=0xFFFF, proto=0, is_ip4=True
+ ):
self.ts_is_ip4 = is_ip4
- self.local_ts = {'is_local': True,
- 'protocol_id': proto,
- 'start_port': start_port,
- 'end_port': end_port,
- 'start_addr': start_addr,
- 'end_addr': end_addr}
-
- def add_remote_ts(self, start_addr, end_addr, start_port=0,
- end_port=0xffff, proto=0):
+ self.local_ts = {
+ "is_local": True,
+ "protocol_id": proto,
+ "start_port": start_port,
+ "end_port": end_port,
+ "start_addr": start_addr,
+ "end_addr": end_addr,
+ }
+
+ def add_remote_ts(
+ self, start_addr, end_addr, start_port=0, end_port=0xFFFF, proto=0
+ ):
try:
IPv4Address(start_addr)
is_ip4 = True
except AddressValueError:
is_ip4 = False
self.ts_is_ip4 = is_ip4
- self.remote_ts = {'is_local': False,
- 'protocol_id': proto,
- 'start_port': start_port,
- 'end_port': end_port,
- 'start_addr': start_addr,
- 'end_addr': end_addr}
+ self.remote_ts = {
+ "is_local": False,
+ "protocol_id": proto,
+ "start_port": start_port,
+ "end_port": end_port,
+ "start_addr": start_addr,
+ "end_addr": end_addr,
+ }
def add_responder_hostname(self, hn):
self.responder_hostname = hn
@@ -101,72 +101,78 @@ class Profile(VppObject):
self.lifetime_data = data
def set_ipsec_over_udp_port(self, port):
- self.ipsec_udp_port = {'is_set': 1,
- 'port': port}
+ self.ipsec_udp_port = {"is_set": 1, "port": port}
def set_tunnel_interface(self, sw_if_index):
self.tun_itf = sw_if_index
def object_id(self):
- return 'ikev2-profile-%s' % self.profile_name
+ return "ikev2-profile-%s" % self.profile_name
def remove_vpp_config(self):
self.vapi.ikev2_profile_add_del(name=self.profile_name, is_add=False)
def add_vpp_config(self):
self.vapi.ikev2_profile_add_del(name=self.profile_name, is_add=True)
- if hasattr(self, 'auth'):
- self.vapi.ikev2_profile_set_auth(name=self.profile_name,
- data_len=len(self.auth['data']),
- **self.auth)
- if hasattr(self, 'local_id'):
- self.vapi.ikev2_profile_set_id(name=self.profile_name,
- data_len=len(self.local_id
- ['data']),
- **self.local_id)
- if hasattr(self, 'remote_id'):
- self.vapi.ikev2_profile_set_id(name=self.profile_name,
- data_len=len(self.remote_id
- ['data']),
- **self.remote_id)
- if hasattr(self, 'local_ts'):
- self.vapi.ikev2_profile_set_ts(name=self.profile_name,
- ts=self.local_ts)
-
- if hasattr(self, 'remote_ts'):
- self.vapi.ikev2_profile_set_ts(name=self.profile_name,
- ts=self.remote_ts)
-
- if hasattr(self, 'responder'):
- self.vapi.ikev2_set_responder(name=self.profile_name,
- responder=self.responder)
-
- if hasattr(self, 'responder_hostname'):
+ if hasattr(self, "auth"):
+ self.vapi.ikev2_profile_set_auth(
+ name=self.profile_name, data_len=len(self.auth["data"]), **self.auth
+ )
+ if hasattr(self, "local_id"):
+ self.vapi.ikev2_profile_set_id(
+ name=self.profile_name,
+ data_len=len(self.local_id["data"]),
+ **self.local_id,
+ )
+ if hasattr(self, "remote_id"):
+ self.vapi.ikev2_profile_set_id(
+ name=self.profile_name,
+ data_len=len(self.remote_id["data"]),
+ **self.remote_id,
+ )
+ if hasattr(self, "local_ts"):
+ self.vapi.ikev2_profile_set_ts(name=self.profile_name, ts=self.local_ts)
+
+ if hasattr(self, "remote_ts"):
+ self.vapi.ikev2_profile_set_ts(name=self.profile_name, ts=self.remote_ts)
+
+ if hasattr(self, "responder"):
+ self.vapi.ikev2_set_responder(
+ name=self.profile_name, responder=self.responder
+ )
+
+ if hasattr(self, "responder_hostname"):
print(self.responder_hostname)
- self.vapi.ikev2_set_responder_hostname(name=self.profile_name,
- **self.responder_hostname)
+ self.vapi.ikev2_set_responder_hostname(
+ name=self.profile_name, **self.responder_hostname
+ )
- if hasattr(self, 'ike_transforms'):
- self.vapi.ikev2_set_ike_transforms(name=self.profile_name,
- tr=self.ike_transforms)
+ if hasattr(self, "ike_transforms"):
+ self.vapi.ikev2_set_ike_transforms(
+ name=self.profile_name, tr=self.ike_transforms
+ )
- if hasattr(self, 'esp_transforms'):
- self.vapi.ikev2_set_esp_transforms(name=self.profile_name,
- tr=self.esp_transforms)
+ if hasattr(self, "esp_transforms"):
+ self.vapi.ikev2_set_esp_transforms(
+ name=self.profile_name, tr=self.esp_transforms
+ )
if self.udp_encap:
self.vapi.ikev2_profile_set_udp_encap(name=self.profile_name)
- if hasattr(self, 'lifetime_data'):
- self.vapi.ikev2_set_sa_lifetime(name=self.profile_name,
- **self.lifetime_data)
-
- if hasattr(self, 'ipsec_udp_port'):
- self.vapi.ikev2_profile_set_ipsec_udp_port(name=self.profile_name,
- **self.ipsec_udp_port)
- if hasattr(self, 'tun_itf'):
- self.vapi.ikev2_set_tunnel_interface(name=self.profile_name,
- sw_if_index=self.tun_itf)
+ if hasattr(self, "lifetime_data"):
+ self.vapi.ikev2_set_sa_lifetime(
+ name=self.profile_name, **self.lifetime_data
+ )
+
+ if hasattr(self, "ipsec_udp_port"):
+ self.vapi.ikev2_profile_set_ipsec_udp_port(
+ name=self.profile_name, **self.ipsec_udp_port
+ )
+ if hasattr(self, "tun_itf"):
+ self.vapi.ikev2_set_tunnel_interface(
+ name=self.profile_name, sw_if_index=self.tun_itf
+ )
if not self.natt:
self.vapi.ikev2_profile_disable_natt(name=self.profile_name)
diff --git a/test/vpp_interface.py b/test/vpp_interface.py
index b7c830b06fd..cee6ea4f080 100644
--- a/test/vpp_interface.py
+++ b/test/vpp_interface.py
@@ -49,7 +49,7 @@ class VppInterface(metaclass=abc.ABCMeta):
@property
def local_ip4_prefix_len(self):
- """Local IPv4 prefix length """
+ """Local IPv4 prefix length"""
return self._local_ip4_len
@local_ip4_prefix_len.setter
@@ -58,8 +58,8 @@ class VppInterface(metaclass=abc.ABCMeta):
@property
def local_ip4_prefix(self):
- """Local IPv4 prefix """
- return ("%s/%d" % (self._local_ip4, self._local_ip4_len))
+ """Local IPv4 prefix"""
+ return "%s/%d" % (self._local_ip4, self._local_ip4_len)
@property
def remote_ip4(self):
@@ -77,7 +77,7 @@ class VppInterface(metaclass=abc.ABCMeta):
@property
def local_ip6_prefix_len(self):
- """Local IPv6 prefix length """
+ """Local IPv6 prefix length"""
return self._local_ip6_len
@local_ip6_prefix_len.setter
@@ -86,8 +86,8 @@ class VppInterface(metaclass=abc.ABCMeta):
@property
def local_ip6_prefix(self):
- """Local IPv4 prefix """
- return ("%s/%d" % (self._local_ip6, self._local_ip6_len))
+ """Local IPv4 prefix"""
+ return "%s/%d" % (self._local_ip6, self._local_ip6_len)
@property
def remote_ip6(self):
@@ -100,7 +100,9 @@ class VppInterface(metaclass=abc.ABCMeta):
if not self._local_ip6_ll:
self._local_ip6_ll = str(
self.test.vapi.sw_interface_ip6_get_link_local_address(
- self.sw_if_index).ip)
+ self.sw_if_index
+ ).ip
+ )
return self._local_ip6_ll
@property
@@ -173,8 +175,7 @@ class VppInterface(metaclass=abc.ABCMeta):
self._hosts_by_mac = {}
self._hosts_by_ip4 = {}
self._hosts_by_ip6 = {}
- for i in range(
- 2, count + 2): # 0: network address, 1: local vpp address
+ for i in range(2, count + 2): # 0: network address, 1: local vpp address
mac = "02:%02x:00:00:ff:%02x" % (self.sw_if_index, i)
ip4 = "172.16.%u.%u" % (self.sw_if_index, i)
ip6 = "fd01:%x::%x" % (self.sw_if_index, i)
@@ -196,14 +197,12 @@ class VppInterface(metaclass=abc.ABCMeta):
def set_mac(self, mac):
self._local_mac = str(mac)
- self.test.vapi.sw_interface_set_mac_address(
- self.sw_if_index, mac.packed)
+ self.test.vapi.sw_interface_set_mac_address(self.sw_if_index, mac.packed)
return self
def set_sw_if_index(self, sw_if_index):
if sw_if_index > 255:
- raise RuntimeError("Don't support sw_if_index values "
- "greater than 255.")
+ raise RuntimeError("Don't support sw_if_index values greater than 255.")
self._sw_if_index = sw_if_index
self.generate_remote_hosts()
@@ -220,10 +219,14 @@ class VppInterface(metaclass=abc.ABCMeta):
self.has_ip6_config = False
self.ip6_table_id = 0
- self._local_addr = {socket.AF_INET: self.local_ip4,
- socket.AF_INET6: self.local_ip6}
- self._remote_addr = {socket.AF_INET: self.remote_ip4,
- socket.AF_INET6: self.remote_ip6}
+ self._local_addr = {
+ socket.AF_INET: self.local_ip4,
+ socket.AF_INET6: self.local_ip6,
+ }
+ self._remote_addr = {
+ socket.AF_INET: self.remote_ip4,
+ socket.AF_INET6: self.remote_ip6,
+ }
r = self.test.vapi.sw_interface_dump(sw_if_index=self.sw_if_index)
for intf in r:
@@ -235,15 +238,16 @@ class VppInterface(metaclass=abc.ABCMeta):
else:
raise Exception(
"Could not find interface with sw_if_index %d "
- "in interface dump %s" %
- (self.sw_if_index, moves.reprlib.repr(r)))
+ "in interface dump %s" % (self.sw_if_index, moves.reprlib.repr(r))
+ )
self._remote_ip6_ll = mk_ll_addr(self.remote_mac)
self._local_ip6_ll = None
def config_ip4(self):
"""Configure IPv4 address on the VPP interface."""
self.test.vapi.sw_interface_add_del_address(
- sw_if_index=self.sw_if_index, prefix=self.local_ip4_prefix)
+ sw_if_index=self.sw_if_index, prefix=self.local_ip4_prefix
+ )
self.has_ip4_config = True
return self
@@ -252,8 +256,8 @@ class VppInterface(metaclass=abc.ABCMeta):
try:
if self.has_ip4_config:
self.test.vapi.sw_interface_add_del_address(
- sw_if_index=self.sw_if_index,
- prefix=self.local_ip4_prefix, is_add=0)
+ sw_if_index=self.sw_if_index, prefix=self.local_ip4_prefix, is_add=0
+ )
except AttributeError:
self.has_ip4_config = False
self.has_ip4_config = False
@@ -265,15 +269,14 @@ class VppInterface(metaclass=abc.ABCMeta):
:param vrf_id: The FIB table / VRF ID. (Default value = 0)
"""
for host in self._remote_hosts:
- self.test.vapi.ip_neighbor_add_del(self.sw_if_index,
- host.mac,
- host.ip4)
+ self.test.vapi.ip_neighbor_add_del(self.sw_if_index, host.mac, host.ip4)
return self
def config_ip6(self):
"""Configure IPv6 address on the VPP interface."""
self.test.vapi.sw_interface_add_del_address(
- sw_if_index=self.sw_if_index, prefix=self.local_ip6_prefix)
+ sw_if_index=self.sw_if_index, prefix=self.local_ip6_prefix
+ )
self.has_ip6_config = True
return self
@@ -282,8 +285,8 @@ class VppInterface(metaclass=abc.ABCMeta):
try:
if self.has_ip6_config:
self.test.vapi.sw_interface_add_del_address(
- sw_if_index=self.sw_if_index,
- prefix=self.local_ip6_prefix, is_add=0)
+ sw_if_index=self.sw_if_index, prefix=self.local_ip6_prefix, is_add=0
+ )
except AttributeError:
self.has_ip6_config = False
self.has_ip6_config = False
@@ -295,9 +298,7 @@ class VppInterface(metaclass=abc.ABCMeta):
:param vrf_id: The FIB table / VRF ID. (Default value = 0)
"""
for host in self._remote_hosts:
- self.test.vapi.ip_neighbor_add_del(self.sw_if_index,
- host.mac,
- host.ip6)
+ self.test.vapi.ip_neighbor_add_del(self.sw_if_index, host.mac, host.ip6)
def unconfig(self):
"""Unconfigure IPv6 and IPv4 address on the VPP interface."""
@@ -311,8 +312,7 @@ class VppInterface(metaclass=abc.ABCMeta):
.. note:: Must be called before configuring IP4 addresses.
"""
self.ip4_table_id = table_id
- self.test.vapi.sw_interface_set_table(
- self.sw_if_index, 0, self.ip4_table_id)
+ self.test.vapi.sw_interface_set_table(self.sw_if_index, 0, self.ip4_table_id)
return self
def set_table_ip6(self, table_id):
@@ -321,15 +321,14 @@ class VppInterface(metaclass=abc.ABCMeta):
.. note:: Must be called before configuring IP6 addresses.
"""
self.ip6_table_id = table_id
- self.test.vapi.sw_interface_set_table(
- self.sw_if_index, 1, self.ip6_table_id)
+ self.test.vapi.sw_interface_set_table(self.sw_if_index, 1, self.ip6_table_id)
return self
def disable_ipv6_ra(self):
"""Configure IPv6 RA suppress on the VPP interface."""
self.test.vapi.sw_interface_ip6nd_ra_config(
- sw_if_index=self.sw_if_index,
- suppress=1)
+ sw_if_index=self.sw_if_index, suppress=1
+ )
return self
def ip6_ra_config(self, no=0, suppress=0, send_unicast=0):
@@ -338,11 +337,13 @@ class VppInterface(metaclass=abc.ABCMeta):
sw_if_index=self.sw_if_index,
is_no=no,
suppress=suppress,
- send_unicast=send_unicast)
+ send_unicast=send_unicast,
+ )
return self
- def ip6_ra_prefix(self, prefix, is_no=0,
- off_link=0, no_autoconfig=0, use_default=0):
+ def ip6_ra_prefix(
+ self, prefix, is_no=0, off_link=0, no_autoconfig=0, use_default=0
+ ):
"""Configure IPv6 RA suppress on the VPP interface.
prefix can be a string in the format of '<address>/<length_in_bits>'
@@ -352,21 +353,23 @@ class VppInterface(metaclass=abc.ABCMeta):
sw_if_index=self.sw_if_index,
prefix=prefix,
use_default=use_default,
- off_link=off_link, no_autoconfig=no_autoconfig,
- is_no=is_no)
+ off_link=off_link,
+ no_autoconfig=no_autoconfig,
+ is_no=is_no,
+ )
return self
def admin_up(self):
"""Put interface ADMIN-UP."""
self.test.vapi.sw_interface_set_flags(
self.sw_if_index,
- flags=VppEnum.vl_api_if_status_flags_t.IF_STATUS_API_FLAG_ADMIN_UP)
+ flags=VppEnum.vl_api_if_status_flags_t.IF_STATUS_API_FLAG_ADMIN_UP,
+ )
return self
def admin_down(self):
"""Put interface ADMIN-down."""
- self.test.vapi.sw_interface_set_flags(self.sw_if_index,
- flags=0)
+ self.test.vapi.sw_interface_set_flags(self.sw_if_index, flags=0)
return self
def link_up(self):
@@ -379,14 +382,12 @@ class VppInterface(metaclass=abc.ABCMeta):
def ip6_enable(self):
"""IPv6 Enable interface"""
- self.test.vapi.sw_interface_ip6_enable_disable(self.sw_if_index,
- enable=1)
+ self.test.vapi.sw_interface_ip6_enable_disable(self.sw_if_index, enable=1)
return self
def ip6_disable(self):
"""Put interface ADMIN-DOWN."""
- self.test.vapi.sw_interface_ip6_enable_disable(self.sw_if_index,
- enable=0)
+ self.test.vapi.sw_interface_ip6_enable_disable(self.sw_if_index, enable=0)
return self
def add_sub_if(self, sub_if):
@@ -394,7 +395,7 @@ class VppInterface(metaclass=abc.ABCMeta):
:param sub_if: sub-interface
"""
- if not hasattr(self, 'sub_if'):
+ if not hasattr(self, "sub_if"):
self.sub_if = sub_if
else:
if isinstance(self.sub_if, list):
@@ -415,30 +416,30 @@ class VppInterface(metaclass=abc.ABCMeta):
def is_ip4_entry_in_fib_dump(self, dump):
for i in dump:
- n = IPv4Network(text_type("%s/%d" % (self.local_ip4,
- self.local_ip4_prefix_len)))
- if i.route.prefix == n and \
- i.route.table_id == self.ip4_table_id:
+ n = IPv4Network(
+ text_type("%s/%d" % (self.local_ip4, self.local_ip4_prefix_len))
+ )
+ if i.route.prefix == n and i.route.table_id == self.ip4_table_id:
return True
return False
def set_unnumbered(self, ip_sw_if_index):
- """ Set the interface to unnumbered via ip_sw_if_index """
- self.test.vapi.sw_interface_set_unnumbered(ip_sw_if_index,
- self.sw_if_index)
+ """Set the interface to unnumbered via ip_sw_if_index"""
+ self.test.vapi.sw_interface_set_unnumbered(ip_sw_if_index, self.sw_if_index)
return self
def unset_unnumbered(self, ip_sw_if_index):
- """ Unset the interface to unnumbered via ip_sw_if_index """
- self.test.vapi.sw_interface_set_unnumbered(ip_sw_if_index,
- self.sw_if_index, is_add=0)
+ """Unset the interface to unnumbered via ip_sw_if_index"""
+ self.test.vapi.sw_interface_set_unnumbered(
+ ip_sw_if_index, self.sw_if_index, is_add=0
+ )
return self
def set_proxy_arp(self, enable=1):
- """ Set the interface to enable/disable Proxy ARP """
+ """Set the interface to enable/disable Proxy ARP"""
self.test.vapi.proxy_arp_intfc_enable_disable(
- sw_if_index=self.sw_if_index,
- enable=enable)
+ sw_if_index=self.sw_if_index, enable=enable
+ )
return self
def query_vpp_config(self):
@@ -447,8 +448,10 @@ class VppInterface(metaclass=abc.ABCMeta):
def get_interface_config_from_dump(self, dump):
for i in dump:
- if i.interface_name.rstrip(' \t\r\n\0') == self.name and \
- i.sw_if_index == self.sw_if_index:
+ if (
+ i.interface_name.rstrip(" \t\r\n\0") == self.name
+ and i.sw_if_index == self.sw_if_index
+ ):
return i
else:
return None
@@ -456,34 +459,25 @@ class VppInterface(metaclass=abc.ABCMeta):
def is_interface_config_in_dump(self, dump):
return self.get_interface_config_from_dump(dump) is not None
- def assert_interface_state(self, admin_up_down, link_up_down,
- expect_event=False):
+ def assert_interface_state(self, admin_up_down, link_up_down, expect_event=False):
if expect_event:
- event = self.test.vapi.wait_for_event(timeout=1,
- name='sw_interface_event')
- self.test.assert_equal(event.sw_if_index, self.sw_if_index,
- "sw_if_index")
- self.test.assert_equal((event.flags & 1), admin_up_down,
- "admin state")
- self.test.assert_equal((event.flags & 2), link_up_down,
- "link state")
+ event = self.test.vapi.wait_for_event(timeout=1, name="sw_interface_event")
+ self.test.assert_equal(event.sw_if_index, self.sw_if_index, "sw_if_index")
+ self.test.assert_equal((event.flags & 1), admin_up_down, "admin state")
+ self.test.assert_equal((event.flags & 2), link_up_down, "link state")
dump = self.test.vapi.sw_interface_dump()
if_state = self.get_interface_config_from_dump(dump)
- self.test.assert_equal((if_state.flags & 1), admin_up_down,
- "admin state")
- self.test.assert_equal((if_state.flags & 2), link_up_down,
- "link state")
+ self.test.assert_equal((if_state.flags & 1), admin_up_down, "admin state")
+ self.test.assert_equal((if_state.flags & 2), link_up_down, "link state")
def __str__(self):
return self.name
def get_rx_stats(self):
- return (self.test.statistics["/if/rx"]
- [:, self.sw_if_index].sum_packets())
+ return self.test.statistics["/if/rx"][:, self.sw_if_index].sum_packets()
def get_tx_stats(self):
- return (self.test.statistics["/if/tx"]
- [:, self.sw_if_index].sum_packets())
+ return self.test.statistics["/if/tx"][:, self.sw_if_index].sum_packets()
def set_l3_mtu(self, mtu):
self.test.vapi.sw_interface_set_mtu(self.sw_if_index, [mtu, 0, 0, 0])
diff --git a/test/vpp_ip.py b/test/vpp_ip.py
index 48b6b9d2da6..24e7c19652a 100644
--- a/test/vpp_ip.py
+++ b/test/vpp_ip.py
@@ -8,6 +8,7 @@ from ipaddress import ip_address
from socket import AF_INET, AF_INET6
from vpp_papi import VppEnum
from vpp_object import VppObject
+
try:
text_type = unicode
except NameError:
@@ -25,7 +26,7 @@ class DpoProto:
DPO_PROTO_NSH = 5
-INVALID_INDEX = 0xffffffff
+INVALID_INDEX = 0xFFFFFFFF
def get_dpo_proto(addr):
@@ -35,16 +36,16 @@ def get_dpo_proto(addr):
return DpoProto.DPO_PROTO_IP4
-class VppIpAddressUnion():
+class VppIpAddressUnion:
def __init__(self, addr):
self.addr = addr
self.ip_addr = ip_address(text_type(self.addr))
def encode(self):
if self.version == 6:
- return {'ip6': self.ip_addr}
+ return {"ip6": self.ip_addr}
else:
- return {'ip4': self.ip_addr}
+ return {"ip4": self.ip_addr}
@property
def version(self):
@@ -72,9 +73,11 @@ class VppIpAddressUnion():
else:
return self.ip_addr == other.ip6
else:
- raise Exception("Comparing VppIpAddressUnions:%s"
- " with incomparable type: %s",
- self, other)
+ raise Exception(
+ "Comparing VppIpAddressUnions:%s with incomparable type: %s",
+ self,
+ other,
+ )
def __ne__(self, other):
return not (self == other)
@@ -83,26 +86,22 @@ class VppIpAddressUnion():
return str(self.ip_addr)
-class VppIpMPrefix():
+class VppIpMPrefix:
def __init__(self, saddr, gaddr, glen):
self.saddr = saddr
self.gaddr = gaddr
self.glen = glen
- if ip_address(self.saddr).version != \
- ip_address(self.gaddr).version:
- raise ValueError('Source and group addresses must be of the '
- 'same address family.')
+ if ip_address(self.saddr).version != ip_address(self.gaddr).version:
+ raise ValueError(
+ "Source and group addresses must be of the same address family."
+ )
def encode(self):
return {
- 'af': ip_address(self.gaddr).vapi_af,
- 'grp_address': {
- ip_address(self.gaddr).vapi_af_name: self.gaddr
- },
- 'src_address': {
- ip_address(self.saddr).vapi_af_name: self.saddr
- },
- 'grp_address_length': self.glen,
+ "af": ip_address(self.gaddr).vapi_af,
+ "grp_address": {ip_address(self.gaddr).vapi_af_name: self.gaddr},
+ "src_address": {ip_address(self.saddr).vapi_af_name: self.saddr},
+ "grp_address_length": self.glen,
}
@property
@@ -118,21 +117,29 @@ class VppIpMPrefix():
def __eq__(self, other):
if isinstance(other, self.__class__):
- return (self.glen == other.glen and
- self.saddr == other.gaddr and
- self.saddr == other.saddr)
- elif (hasattr(other, "grp_address_length") and
- hasattr(other, "grp_address") and
- hasattr(other, "src_address")):
+ return (
+ self.glen == other.glen
+ and self.saddr == other.gaddr
+ and self.saddr == other.saddr
+ )
+ elif (
+ hasattr(other, "grp_address_length")
+ and hasattr(other, "grp_address")
+ and hasattr(other, "src_address")
+ ):
# vl_api_mprefix_t
if 4 == self.version:
- return (self.glen == other.grp_address_length and
- self.gaddr == str(other.grp_address.ip4) and
- self.saddr == str(other.src_address.ip4))
+ return (
+ self.glen == other.grp_address_length
+ and self.gaddr == str(other.grp_address.ip4)
+ and self.saddr == str(other.src_address.ip4)
+ )
else:
- return (self.glen == other.grp_address_length and
- self.gaddr == str(other.grp_address.ip6) and
- self.saddr == str(other.src_address.ip6))
+ return (
+ self.glen == other.grp_address_length
+ and self.gaddr == str(other.grp_address.ip6)
+ and self.saddr == str(other.src_address.ip6)
+ )
return NotImplemented
@@ -143,12 +150,14 @@ class VppIpPuntPolicer(VppObject):
self._is_ip6 = is_ip6
def add_vpp_config(self):
- self._test.vapi.ip_punt_police(policer_index=self._policer_index,
- is_ip6=self._is_ip6, is_add=True)
+ self._test.vapi.ip_punt_police(
+ policer_index=self._policer_index, is_ip6=self._is_ip6, is_add=True
+ )
def remove_vpp_config(self):
- self._test.vapi.ip_punt_police(policer_index=self._policer_index,
- is_ip6=self._is_ip6, is_add=False)
+ self._test.vapi.ip_punt_police(
+ policer_index=self._policer_index, is_ip6=self._is_ip6, is_add=False
+ )
def query_vpp_config(self):
NotImplemented
@@ -162,8 +171,11 @@ class VppIpPuntRedirect(VppObject):
self._nh_addr = ip_address(nh_addr)
def encode(self):
- return {"rx_sw_if_index": self._rx_index,
- "tx_sw_if_index": self._tx_index, "nh": self._nh_addr}
+ return {
+ "rx_sw_if_index": self._rx_index,
+ "tx_sw_if_index": self._tx_index,
+ "nh": self._nh_addr,
+ }
def add_vpp_config(self):
self._test.vapi.ip_punt_redirect(punt=self.encode(), is_add=True)
@@ -176,7 +188,8 @@ class VppIpPuntRedirect(VppObject):
def get_vpp_config(self):
is_ipv6 = True if self._nh_addr.version == 6 else False
return self._test.vapi.ip_punt_redirect_dump(
- sw_if_index=self._rx_index, is_ipv6=is_ipv6)
+ sw_if_index=self._rx_index, is_ipv6=is_ipv6
+ )
def query_vpp_config(self):
if self.get_vpp_config():
@@ -192,39 +205,38 @@ class VppIpPathMtu(VppObject):
self.table_id = table_id
def add_vpp_config(self):
- self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh,
- 'table_id': self.table_id,
- 'path_mtu': self.pmtu})
+ self._test.vapi.ip_path_mtu_update(
+ pmtu={"nh": self.nh, "table_id": self.table_id, "path_mtu": self.pmtu}
+ )
self._test.registry.register(self, self._test.logger)
return self
def modify(self, pmtu):
self.pmtu = pmtu
- self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh,
- 'table_id': self.table_id,
- 'path_mtu': self.pmtu})
+ self._test.vapi.ip_path_mtu_update(
+ pmtu={"nh": self.nh, "table_id": self.table_id, "path_mtu": self.pmtu}
+ )
return self
def remove_vpp_config(self):
- self._test.vapi.ip_path_mtu_update(pmtu={'nh': self.nh,
- 'table_id': self.table_id,
- 'path_mtu': 0})
+ self._test.vapi.ip_path_mtu_update(
+ pmtu={"nh": self.nh, "table_id": self.table_id, "path_mtu": 0}
+ )
def query_vpp_config(self):
- ds = list(self._test.vapi.vpp.details_iter(
- self._test.vapi.ip_path_mtu_get))
+ ds = list(self._test.vapi.vpp.details_iter(self._test.vapi.ip_path_mtu_get))
for d in ds:
- if self.nh == str(d.pmtu.nh) \
- and self.table_id == d.pmtu.table_id \
- and self.pmtu == d.pmtu.path_mtu:
+ if (
+ self.nh == str(d.pmtu.nh)
+ and self.table_id == d.pmtu.table_id
+ and self.pmtu == d.pmtu.path_mtu
+ ):
return True
return False
def object_id(self):
- return ("ip-path-mtu-%d-%s-%d" % (self.table_id,
- self.nh,
- self.pmtu))
+ return "ip-path-mtu-%d-%s-%d" % (self.table_id, self.nh, self.pmtu)
def __str__(self):
return self.object_id()
diff --git a/test/vpp_ip_route.py b/test/vpp_ip_route.py
index f5e5a8801e4..06a963cfd88 100644
--- a/test/vpp_ip_route.py
+++ b/test/vpp_ip_route.py
@@ -5,13 +5,12 @@
"""
from vpp_object import VppObject
-from vpp_ip import DpoProto, INVALID_INDEX, VppIpAddressUnion, \
- VppIpMPrefix
+from vpp_ip import DpoProto, INVALID_INDEX, VppIpAddressUnion, VppIpMPrefix
from ipaddress import ip_network, ip_address, IPv4Network, IPv6Network
from vpp_papi_exceptions import UnexpectedApiReturnValueError
# from vnet/vnet/mpls/mpls_types.h
-MPLS_IETF_MAX_LABEL = 0xfffff
+MPLS_IETF_MAX_LABEL = 0xFFFFF
MPLS_LABEL_INVALID = MPLS_IETF_MAX_LABEL + 1
try:
@@ -85,8 +84,7 @@ def find_route(test, addr, len, table_id=0, sw_if_index=None):
routes = test.vapi.ip_route_dump(table_id, True)
for e in routes:
- if table_id == e.route.table_id \
- and str(e.route.prefix) == str(prefix):
+ if table_id == e.route.table_id and str(e.route.prefix) == str(prefix):
if not sw_if_index:
return True
else:
@@ -95,15 +93,14 @@ def find_route(test, addr, len, table_id=0, sw_if_index=None):
if e.route.n_paths != 1:
return False
else:
- return (e.route.paths[0].sw_if_index == sw_if_index)
+ return e.route.paths[0].sw_if_index == sw_if_index
return False
def find_route_in_dump(dump, route, table):
for r in dump:
- if table.table_id == r.route.table_id \
- and route.prefix == r.route.prefix:
+ if table.table_id == r.route.table_id and route.prefix == r.route.prefix:
if len(route.paths) == r.route.n_paths:
return True
return False
@@ -111,17 +108,13 @@ def find_route_in_dump(dump, route, table):
def find_mroute_in_dump(dump, route, table):
for r in dump:
- if table.table_id == r.route.table_id \
- and route.prefix == r.route.prefix:
+ if table.table_id == r.route.table_id and route.prefix == r.route.prefix:
return True
return False
-def find_mroute(test, grp_addr, src_addr, grp_addr_len,
- table_id=0):
- ip_mprefix = VppIpMPrefix(text_type(src_addr),
- text_type(grp_addr),
- grp_addr_len)
+def find_mroute(test, grp_addr, src_addr, grp_addr_len, table_id=0):
+ ip_mprefix = VppIpMPrefix(text_type(src_addr), text_type(grp_addr), grp_addr_len)
if 4 == ip_mprefix.version:
routes = test.vapi.ip_mroute_dump(table_id, False)
@@ -137,16 +130,18 @@ def find_mroute(test, grp_addr, src_addr, grp_addr_len,
def find_mpls_route(test, table_id, label, eos_bit, paths=None):
dump = test.vapi.mpls_route_dump(table_id)
for e in dump:
- if label == e.mr_route.mr_label \
- and eos_bit == e.mr_route.mr_eos \
- and table_id == e.mr_route.mr_table_id:
+ if (
+ label == e.mr_route.mr_label
+ and eos_bit == e.mr_route.mr_eos
+ and table_id == e.mr_route.mr_table_id
+ ):
if not paths:
return True
else:
- if (len(paths) != len(e.mr_route.mr_paths)):
+ if len(paths) != len(e.mr_route.mr_paths):
return False
for i in range(len(paths)):
- if (paths[i] != e.mr_route.mr_paths[i]):
+ if paths[i] != e.mr_route.mr_paths[i]:
return False
return True
return False
@@ -156,54 +151,49 @@ def fib_interface_ip_prefix(test, addr, len, sw_if_index):
# can't use python net here since we need the host bits in the prefix
prefix = "%s/%d" % (addr, len)
addrs = test.vapi.ip_address_dump(
- sw_if_index,
- is_ipv6=(6 == ip_address(addr).version))
+ sw_if_index, is_ipv6=(6 == ip_address(addr).version)
+ )
for a in addrs:
- if a.sw_if_index == sw_if_index and \
- str(a.prefix) == prefix:
+ if a.sw_if_index == sw_if_index and str(a.prefix) == prefix:
return True
return False
class VppIpTable(VppObject):
-
- def __init__(self,
- test,
- table_id,
- is_ip6=0,
- register=True):
+ def __init__(self, test, table_id, is_ip6=0, register=True):
self._test = test
self.table_id = table_id
self.is_ip6 = is_ip6
self.register = register
def add_vpp_config(self):
- self._test.vapi.ip_table_add_del(is_add=1,
- table={'is_ip6': self.is_ip6,
- 'table_id': self.table_id})
+ self._test.vapi.ip_table_add_del(
+ is_add=1, table={"is_ip6": self.is_ip6, "table_id": self.table_id}
+ )
if self.register:
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
- self._test.vapi.ip_table_add_del(is_add=0,
- table={'is_ip6': self.is_ip6,
- 'table_id': self.table_id})
+ self._test.vapi.ip_table_add_del(
+ is_add=0, table={"is_ip6": self.is_ip6, "table_id": self.table_id}
+ )
def replace_begin(self):
self._test.vapi.ip_table_replace_begin(
- table={'is_ip6': self.is_ip6,
- 'table_id': self.table_id})
+ table={"is_ip6": self.is_ip6, "table_id": self.table_id}
+ )
def replace_end(self):
self._test.vapi.ip_table_replace_end(
- table={'is_ip6': self.is_ip6,
- 'table_id': self.table_id})
+ table={"is_ip6": self.is_ip6, "table_id": self.table_id}
+ )
def flush(self):
- self._test.vapi.ip_table_flush(table={'is_ip6': self.is_ip6,
- 'table_id': self.table_id})
+ self._test.vapi.ip_table_flush(
+ table={"is_ip6": self.is_ip6, "table_id": self.table_id}
+ )
def dump(self):
return self._test.vapi.ip_route_dump(self.table_id, self.is_ip6)
@@ -216,19 +206,15 @@ class VppIpTable(VppObject):
# the default table always exists
return False
# find the default route
- return find_route(self._test,
- "::" if self.is_ip6 else "0.0.0.0",
- 0,
- self.table_id)
+ return find_route(
+ self._test, "::" if self.is_ip6 else "0.0.0.0", 0, self.table_id
+ )
def object_id(self):
- return ("table-%s-%d" %
- ("v6" if self.is_ip6 == 1 else "v4",
- self.table_id))
+ return "table-%s-%d" % ("v6" if self.is_ip6 == 1 else "v4", self.table_id)
class VppIpInterfaceAddress(VppObject):
-
def __init__(self, test, intf, addr, len, bind=None):
self._test = test
self.intf = intf
@@ -242,55 +228,57 @@ class VppIpInterfaceAddress(VppObject):
def add_vpp_config(self):
self._test.vapi.sw_interface_add_del_address(
- sw_if_index=self.intf.sw_if_index, prefix=self.prefix,
- is_add=1)
+ sw_if_index=self.intf.sw_if_index, prefix=self.prefix, is_add=1
+ )
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
self._test.vapi.sw_interface_add_del_address(
- sw_if_index=self.intf.sw_if_index, prefix=self.prefix,
- is_add=0)
+ sw_if_index=self.intf.sw_if_index, prefix=self.prefix, is_add=0
+ )
def query_vpp_config(self):
# search for the IP address mapping and the two expected
# FIB entries
v = ip_address(self.addr).version
- if ((v == 4 and self.len < 31) or (v == 6 and self.len < 127)):
- return (fib_interface_ip_prefix(self._test,
- self.addr,
- self.len,
- self.intf.sw_if_index) &
- find_route(self._test,
- self.addr,
- self.len,
- table_id=self.table_id,
- sw_if_index=self.intf.sw_if_index) &
- find_route(self._test,
- self.addr,
- self.host_len,
- table_id=self.table_id,
- sw_if_index=self.intf.sw_if_index))
+ if (v == 4 and self.len < 31) or (v == 6 and self.len < 127):
+ return (
+ fib_interface_ip_prefix(
+ self._test, self.addr, self.len, self.intf.sw_if_index
+ )
+ & find_route(
+ self._test,
+ self.addr,
+ self.len,
+ table_id=self.table_id,
+ sw_if_index=self.intf.sw_if_index,
+ )
+ & find_route(
+ self._test,
+ self.addr,
+ self.host_len,
+ table_id=self.table_id,
+ sw_if_index=self.intf.sw_if_index,
+ )
+ )
else:
- return (fib_interface_ip_prefix(self._test,
- self.addr,
- self.len,
- self.intf.sw_if_index) &
- find_route(self._test,
- self.addr,
- self.host_len,
- table_id=self.table_id,
- sw_if_index=self.intf.sw_if_index))
+ return fib_interface_ip_prefix(
+ self._test, self.addr, self.len, self.intf.sw_if_index
+ ) & find_route(
+ self._test,
+ self.addr,
+ self.host_len,
+ table_id=self.table_id,
+ sw_if_index=self.intf.sw_if_index,
+ )
def object_id(self):
- return "interface-ip-%s-%d-%s" % (self.intf,
- self.table_id,
- self.prefix)
+ return "interface-ip-%s-%d-%s" % (self.intf, self.table_id, self.prefix)
class VppIp6LinkLocalAddress(VppObject):
-
def __init__(self, test, intf, addr):
self._test = test
self.intf = intf
@@ -298,7 +286,8 @@ class VppIp6LinkLocalAddress(VppObject):
def add_vpp_config(self):
self._test.vapi.sw_interface_ip6_set_link_local_address(
- sw_if_index=self.intf.sw_if_index, ip=self.addr)
+ sw_if_index=self.intf.sw_if_index, ip=self.addr
+ )
self._test.registry.register(self, self._test.logger)
return self
@@ -315,7 +304,6 @@ class VppIp6LinkLocalAddress(VppObject):
class VppIpInterfaceBind(VppObject):
-
def __init__(self, test, intf, table):
self._test = test
self.intf = intf
@@ -341,9 +329,12 @@ class VppIpInterfaceBind(VppObject):
if 0 == self.table.table_id:
return False
try:
- return self._test.vapi.sw_interface_get_table(
- self.intf.sw_if_index,
- self.table.is_ip6).vrf_id == self.table.table_id
+ return (
+ self._test.vapi.sw_interface_get_table(
+ self.intf.sw_if_index, self.table.is_ip6
+ ).vrf_id
+ == self.table.table_id
+ )
except UnexpectedApiReturnValueError as e:
if e.retval == -2: # INVALID_SW_IF_INDEX
return False
@@ -362,22 +353,28 @@ class VppMplsLabel:
def encode(self):
is_uniform = 0 if self.mode is MplsLspMode.PIPE else 1
- return {'label': self.value,
- 'ttl': self.ttl,
- 'exp': self.exp,
- 'is_uniform': is_uniform}
+ return {
+ "label": self.value,
+ "ttl": self.ttl,
+ "exp": self.exp,
+ "is_uniform": is_uniform,
+ }
def __eq__(self, other):
if isinstance(other, self.__class__):
- return (self.value == other.value and
- self.ttl == other.ttl and
- self.exp == other.exp and
- self.mode == other.mode)
- elif hasattr(other, 'label'):
- return (self.value == other.label and
- self.ttl == other.ttl and
- self.exp == other.exp and
- (self.mode == MplsLspMode.UNIFORM) == other.is_uniform)
+ return (
+ self.value == other.value
+ and self.ttl == other.ttl
+ and self.exp == other.exp
+ and self.mode == other.mode
+ )
+ elif hasattr(other, "label"):
+ return (
+ self.value == other.label
+ and self.ttl == other.ttl
+ and self.exp == other.exp
+ and (self.mode == MplsLspMode.UNIFORM) == other.is_uniform
+ )
else:
return False
@@ -386,20 +383,18 @@ class VppMplsLabel:
class VppFibPathNextHop:
- def __init__(self, addr,
- via_label=MPLS_LABEL_INVALID,
- next_hop_id=INVALID_INDEX):
+ def __init__(self, addr, via_label=MPLS_LABEL_INVALID, next_hop_id=INVALID_INDEX):
self.addr = VppIpAddressUnion(addr)
self.via_label = via_label
self.obj_id = next_hop_id
def encode(self):
if self.via_label is not MPLS_LABEL_INVALID:
- return {'via_label': self.via_label}
+ return {"via_label": self.via_label}
if self.obj_id is not INVALID_INDEX:
- return {'obj_id': self.obj_id}
+ return {"obj_id": self.obj_id}
else:
- return {'address': self.addr.encode()}
+ return {"address": self.addr.encode()}
def proto(self):
if self.via_label is MPLS_LABEL_INVALID:
@@ -411,25 +406,27 @@ class VppFibPathNextHop:
if not isinstance(other, self.__class__):
# try the other instance's __eq__.
return NotImplemented
- return (self.addr == other.addr and
- self.via_label == other.via_label and
- self.obj_id == other.obj_id)
+ return (
+ self.addr == other.addr
+ and self.via_label == other.via_label
+ and self.obj_id == other.obj_id
+ )
class VppRoutePath:
-
def __init__(
- self,
- nh_addr,
- nh_sw_if_index,
- nh_table_id=0,
- labels=[],
- nh_via_label=MPLS_LABEL_INVALID,
- rpf_id=0,
- next_hop_id=INVALID_INDEX,
- proto=None,
- flags=FibPathFlags.FIB_PATH_FLAG_NONE,
- type=FibPathType.FIB_PATH_TYPE_NORMAL):
+ self,
+ nh_addr,
+ nh_sw_if_index,
+ nh_table_id=0,
+ labels=[],
+ nh_via_label=MPLS_LABEL_INVALID,
+ rpf_id=0,
+ next_hop_id=INVALID_INDEX,
+ proto=None,
+ flags=FibPathFlags.FIB_PATH_FLAG_NONE,
+ type=FibPathType.FIB_PATH_TYPE_NORMAL,
+ ):
self.nh_itf = nh_sw_if_index
self.nh_table_id = nh_table_id
self.nh_labels = labels
@@ -451,36 +448,37 @@ class VppRoutePath:
if type(l) == VppMplsLabel:
lstack.append(l.encode())
else:
- lstack.append({'label': l,
- 'ttl': 255})
- while (len(lstack) < 16):
+ lstack.append({"label": l, "ttl": 255})
+ while len(lstack) < 16:
lstack.append({})
return lstack
def encode(self):
- return {'weight': 1,
- 'preference': 0,
- 'table_id': self.nh_table_id,
- 'nh': self.nh.encode(),
- 'next_hop_id': self.next_hop_id,
- 'sw_if_index': self.nh_itf,
- 'rpf_id': self.rpf_id,
- 'proto': self.proto,
- 'type': self.type,
- 'flags': self.flags,
- 'n_labels': len(self.nh_labels),
- 'label_stack': self.encode_labels()}
+ return {
+ "weight": 1,
+ "preference": 0,
+ "table_id": self.nh_table_id,
+ "nh": self.nh.encode(),
+ "next_hop_id": self.next_hop_id,
+ "sw_if_index": self.nh_itf,
+ "rpf_id": self.rpf_id,
+ "proto": self.proto,
+ "type": self.type,
+ "flags": self.flags,
+ "n_labels": len(self.nh_labels),
+ "label_stack": self.encode_labels(),
+ }
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.nh == other.nh
- elif hasattr(other, 'sw_if_index'):
+ elif hasattr(other, "sw_if_index"):
# vl_api_fib_path_t
- if (len(self.nh_labels) != other.n_labels):
+ if len(self.nh_labels) != other.n_labels:
return False
for i in range(len(self.nh_labels)):
- if (self.nh_labels[i] != other.label_stack[i]):
+ if self.nh_labels[i] != other.label_stack[i]:
return False
return self.nh_itf == other.sw_if_index
else:
@@ -491,26 +489,28 @@ class VppRoutePath:
class VppMRoutePath(VppRoutePath):
-
- def __init__(self, nh_sw_if_index, flags,
- nh=None,
- proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
- type=FibPathType.FIB_PATH_TYPE_NORMAL,
- bier_imp=INVALID_INDEX):
+ def __init__(
+ self,
+ nh_sw_if_index,
+ flags,
+ nh=None,
+ proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ type=FibPathType.FIB_PATH_TYPE_NORMAL,
+ bier_imp=INVALID_INDEX,
+ ):
if not nh:
- nh = "::" if proto is FibPathProto.FIB_PATH_NH_PROTO_IP6 \
- else "0.0.0.0"
- super(VppMRoutePath, self).__init__(nh,
- nh_sw_if_index,
- proto=proto,
- type=type,
- next_hop_id=bier_imp)
+ nh = "::" if proto is FibPathProto.FIB_PATH_NH_PROTO_IP6 else "0.0.0.0"
+ super(VppMRoutePath, self).__init__(
+ nh, nh_sw_if_index, proto=proto, type=type, next_hop_id=bier_imp
+ )
self.nh_i_flags = flags
self.bier_imp = bier_imp
def encode(self):
- return {'path': super(VppMRoutePath, self).encode(),
- 'itf_flags': self.nh_i_flags}
+ return {
+ "path": super(VppMRoutePath, self).encode(),
+ "itf_flags": self.nh_i_flags,
+ }
class VppIpRoute(VppObject):
@@ -518,8 +518,9 @@ class VppIpRoute(VppObject):
IP Route
"""
- def __init__(self, test, dest_addr,
- dest_addr_len, paths, table_id=0, register=True):
+ def __init__(
+ self, test, dest_addr, dest_addr_len, paths, table_id=0, register=True
+ ):
self._test = test
self.paths = paths
self.table_id = table_id
@@ -533,8 +534,7 @@ class VppIpRoute(VppObject):
self.encoded_paths.append(path.encode())
def __eq__(self, other):
- if self.table_id == other.table_id and \
- self.prefix == other.prefix:
+ if self.table_id == other.table_id and self.prefix == other.prefix:
return True
return False
@@ -545,24 +545,28 @@ class VppIpRoute(VppObject):
self.encoded_paths.append(path.encode())
self.modified = True
- self._test.vapi.ip_route_add_del(route={'table_id': self.table_id,
- 'prefix': self.prefix,
- 'n_paths': len(
- self.encoded_paths),
- 'paths': self.encoded_paths,
- },
- is_add=1,
- is_multipath=0)
+ self._test.vapi.ip_route_add_del(
+ route={
+ "table_id": self.table_id,
+ "prefix": self.prefix,
+ "n_paths": len(self.encoded_paths),
+ "paths": self.encoded_paths,
+ },
+ is_add=1,
+ is_multipath=0,
+ )
def add_vpp_config(self):
r = self._test.vapi.ip_route_add_del(
- route={'table_id': self.table_id,
- 'prefix': self.prefix,
- 'n_paths': len(self.encoded_paths),
- 'paths': self.encoded_paths,
- },
+ route={
+ "table_id": self.table_id,
+ "prefix": self.prefix,
+ "n_paths": len(self.encoded_paths),
+ "paths": self.encoded_paths,
+ },
is_add=1,
- is_multipath=0)
+ is_multipath=0,
+ )
self.stats_index = r.stats_index
if self.register:
self._test.registry.register(self, self._test.logger)
@@ -575,32 +579,36 @@ class VppIpRoute(VppObject):
# passing no paths and multipath=0
if self.modified:
self._test.vapi.ip_route_add_del(
- route={'table_id': self.table_id,
- 'prefix': self.prefix,
- 'n_paths': len(
- self.encoded_paths),
- 'paths': self.encoded_paths},
+ route={
+ "table_id": self.table_id,
+ "prefix": self.prefix,
+ "n_paths": len(self.encoded_paths),
+ "paths": self.encoded_paths,
+ },
is_add=0,
- is_multipath=1)
+ is_multipath=1,
+ )
else:
self._test.vapi.ip_route_add_del(
- route={'table_id': self.table_id,
- 'prefix': self.prefix,
- 'n_paths': 0},
+ route={"table_id": self.table_id, "prefix": self.prefix, "n_paths": 0},
is_add=0,
- is_multipath=0)
+ is_multipath=0,
+ )
def query_vpp_config(self):
- return find_route(self._test,
- self.prefix.network_address,
- self.prefix.prefixlen,
- self.table_id)
+ return find_route(
+ self._test,
+ self.prefix.network_address,
+ self.prefix.prefixlen,
+ self.table_id,
+ )
def object_id(self):
- return ("%s:table-%d-%s" % (
- 'ip6-route' if self.prefix.version == 6 else 'ip-route',
- self.table_id,
- self.prefix))
+ return "%s:table-%d-%s" % (
+ "ip6-route" if self.prefix.version == 6 else "ip-route",
+ self.table_id,
+ self.prefix,
+ )
def get_stats_to(self):
c = self._test.statistics.get_counter("/net/route/to")
@@ -616,9 +624,9 @@ class VppIpRouteV2(VppObject):
IP Route V2
"""
- def __init__(self, test, dest_addr,
- dest_addr_len, paths, table_id=0,
- register=True, src=0):
+ def __init__(
+ self, test, dest_addr, dest_addr_len, paths, table_id=0, register=True, src=0
+ ):
self._test = test
self.paths = paths
self.table_id = table_id
@@ -633,8 +641,7 @@ class VppIpRouteV2(VppObject):
self.encoded_paths.append(path.encode())
def __eq__(self, other):
- if self.table_id == other.table_id and \
- self.prefix == other.prefix:
+ if self.table_id == other.table_id and self.prefix == other.prefix:
return True
return False
@@ -645,26 +652,30 @@ class VppIpRouteV2(VppObject):
self.encoded_paths.append(path.encode())
self.modified = True
- self._test.vapi.ip_route_add_del_v2(route={'table_id': self.table_id,
- 'prefix': self.prefix,
- 'src': self.src,
- 'n_paths': len(
- self.encoded_paths),
- 'paths': self.encoded_paths,
- },
- is_add=1,
- is_multipath=0)
+ self._test.vapi.ip_route_add_del_v2(
+ route={
+ "table_id": self.table_id,
+ "prefix": self.prefix,
+ "src": self.src,
+ "n_paths": len(self.encoded_paths),
+ "paths": self.encoded_paths,
+ },
+ is_add=1,
+ is_multipath=0,
+ )
def add_vpp_config(self):
r = self._test.vapi.ip_route_add_del_v2(
- route={'table_id': self.table_id,
- 'prefix': self.prefix,
- 'n_paths': len(self.encoded_paths),
- 'paths': self.encoded_paths,
- 'src': self.src,
- },
+ route={
+ "table_id": self.table_id,
+ "prefix": self.prefix,
+ "n_paths": len(self.encoded_paths),
+ "paths": self.encoded_paths,
+ "src": self.src,
+ },
is_add=1,
- is_multipath=0)
+ is_multipath=0,
+ )
self.stats_index = r.stats_index
if self.register:
self._test.registry.register(self, self._test.logger)
@@ -677,34 +688,42 @@ class VppIpRouteV2(VppObject):
# passing no paths and multipath=0
if self.modified:
self._test.vapi.ip_route_add_del_v2(
- route={'table_id': self.table_id,
- 'prefix': self.prefix,
- 'src': self.src,
- 'n_paths': len(
- self.encoded_paths),
- 'paths': self.encoded_paths},
+ route={
+ "table_id": self.table_id,
+ "prefix": self.prefix,
+ "src": self.src,
+ "n_paths": len(self.encoded_paths),
+ "paths": self.encoded_paths,
+ },
is_add=0,
- is_multipath=1)
+ is_multipath=1,
+ )
else:
self._test.vapi.ip_route_add_del_v2(
- route={'table_id': self.table_id,
- 'prefix': self.prefix,
- 'src': self.src,
- 'n_paths': 0},
+ route={
+ "table_id": self.table_id,
+ "prefix": self.prefix,
+ "src": self.src,
+ "n_paths": 0,
+ },
is_add=0,
- is_multipath=0)
+ is_multipath=0,
+ )
def query_vpp_config(self):
- return find_route(self._test,
- self.prefix.network_address,
- self.prefix.prefixlen,
- self.table_id)
+ return find_route(
+ self._test,
+ self.prefix.network_address,
+ self.prefix.prefixlen,
+ self.table_id,
+ )
def object_id(self):
- return ("%s:table-%d-%s" % (
- 'ip6-route' if self.prefix.version == 6 else 'ip-route',
- self.table_id,
- self.prefix))
+ return "%s:table-%d-%s" % (
+ "ip6-route" if self.prefix.version == 6 else "ip-route",
+ self.table_id,
+ self.prefix,
+ )
def get_stats_to(self):
c = self._test.statistics.get_counter("/net/route/to")
@@ -720,9 +739,17 @@ class VppIpMRoute(VppObject):
IP Multicast Route
"""
- def __init__(self, test, src_addr, grp_addr,
- grp_addr_len, e_flags, paths, table_id=0,
- rpf_id=0):
+ def __init__(
+ self,
+ test,
+ src_addr,
+ grp_addr,
+ grp_addr_len,
+ e_flags,
+ paths,
+ table_id=0,
+ rpf_id=0,
+ ):
self._test = test
self.paths = paths
self.table_id = table_id
@@ -736,38 +763,37 @@ class VppIpMRoute(VppObject):
def encode(self, paths=None):
_paths = self.encoded_paths if paths is None else paths
- return {'table_id': self.table_id,
- 'entry_flags': self.e_flags,
- 'rpf_id': self.rpf_id,
- 'prefix': self.prefix.encode(),
- 'n_paths': len(_paths),
- 'paths': _paths,
- }
+ return {
+ "table_id": self.table_id,
+ "entry_flags": self.e_flags,
+ "rpf_id": self.rpf_id,
+ "prefix": self.prefix.encode(),
+ "n_paths": len(_paths),
+ "paths": _paths,
+ }
def add_vpp_config(self):
- r = self._test.vapi.ip_mroute_add_del(route=self.encode(),
- is_multipath=1,
- is_add=1)
+ r = self._test.vapi.ip_mroute_add_del(
+ route=self.encode(), is_multipath=1, is_add=1
+ )
self.stats_index = r.stats_index
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
- self._test.vapi.ip_mroute_add_del(route=self.encode(),
- is_multipath=1,
- is_add=0)
+ self._test.vapi.ip_mroute_add_del(route=self.encode(), is_multipath=1, is_add=0)
def update_entry_flags(self, flags):
self.e_flags = flags
- self._test.vapi.ip_mroute_add_del(route=self.encode(paths=[]),
- is_multipath=1,
- is_add=1)
+ self._test.vapi.ip_mroute_add_del(
+ route=self.encode(paths=[]), is_multipath=1, is_add=1
+ )
def update_rpf_id(self, rpf_id):
self.rpf_id = rpf_id
- self._test.vapi.ip_mroute_add_del(route=self.encode(paths=[]),
- is_multipath=1,
- is_add=1)
+ self._test.vapi.ip_mroute_add_del(
+ route=self.encode(paths=[]), is_multipath=1, is_add=1
+ )
def update_path_flags(self, itf, flags):
for p in range(len(self.paths)):
@@ -777,23 +803,25 @@ class VppIpMRoute(VppObject):
break
self._test.vapi.ip_mroute_add_del(
- route=self.encode(
- paths=[self.encoded_paths[p]]),
- is_add=1,
- is_multipath=0)
+ route=self.encode(paths=[self.encoded_paths[p]]), is_add=1, is_multipath=0
+ )
def query_vpp_config(self):
- return find_mroute(self._test,
- self.prefix.gaddr,
- self.prefix.saddr,
- self.prefix.length,
- self.table_id)
+ return find_mroute(
+ self._test,
+ self.prefix.gaddr,
+ self.prefix.saddr,
+ self.prefix.length,
+ self.table_id,
+ )
def object_id(self):
- return ("%d:(%s,%s/%d)" % (self.table_id,
- self.prefix.saddr,
- self.prefix.gaddr,
- self.prefix.length))
+ return "%d:(%s,%s/%d)" % (
+ self.table_id,
+ self.prefix.saddr,
+ self.prefix.gaddr,
+ self.prefix.length,
+ )
def get_stats(self):
c = self._test.statistics.get_counter("/net/mroute")
@@ -818,8 +846,16 @@ class VppMplsIpBind(VppObject):
MPLS to IP Binding
"""
- def __init__(self, test, local_label, dest_addr, dest_addr_len,
- table_id=0, ip_table_id=0, is_ip6=0):
+ def __init__(
+ self,
+ test,
+ local_label,
+ dest_addr,
+ dest_addr_len,
+ table_id=0,
+ ip_table_id=0,
+ is_ip6=0,
+ ):
self._test = test
self.dest_addr_len = dest_addr_len
self.dest_addr = dest_addr
@@ -830,54 +866,54 @@ class VppMplsIpBind(VppObject):
self.prefix = mk_network(dest_addr, dest_addr_len)
def add_vpp_config(self):
- self._test.vapi.mpls_ip_bind_unbind(self.local_label,
- self.prefix,
- table_id=self.table_id,
- ip_table_id=self.ip_table_id)
+ self._test.vapi.mpls_ip_bind_unbind(
+ self.local_label,
+ self.prefix,
+ table_id=self.table_id,
+ ip_table_id=self.ip_table_id,
+ )
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
- self._test.vapi.mpls_ip_bind_unbind(self.local_label,
- self.prefix,
- table_id=self.table_id,
- ip_table_id=self.ip_table_id,
- is_bind=0)
+ self._test.vapi.mpls_ip_bind_unbind(
+ self.local_label,
+ self.prefix,
+ table_id=self.table_id,
+ ip_table_id=self.ip_table_id,
+ is_bind=0,
+ )
def query_vpp_config(self):
dump = self._test.vapi.mpls_route_dump(self.table_id)
for e in dump:
- if self.local_label == e.mr_route.mr_label \
- and self.table_id == e.mr_route.mr_table_id:
+ if (
+ self.local_label == e.mr_route.mr_label
+ and self.table_id == e.mr_route.mr_table_id
+ ):
return True
return False
def object_id(self):
- return ("%d:%s binds %d:%s/%d"
- % (self.table_id,
- self.local_label,
- self.ip_table_id,
- self.dest_addr,
- self.dest_addr_len))
+ return "%d:%s binds %d:%s/%d" % (
+ self.table_id,
+ self.local_label,
+ self.ip_table_id,
+ self.dest_addr,
+ self.dest_addr_len,
+ )
class VppMplsTable(VppObject):
-
- def __init__(self,
- test,
- table_id):
+ def __init__(self, test, table_id):
self._test = test
self.table_id = table_id
def add_vpp_config(self):
- self._test.vapi.mpls_table_add_del(
- self.table_id,
- is_add=1)
+ self._test.vapi.mpls_table_add_del(self.table_id, is_add=1)
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
- self._test.vapi.mpls_table_add_del(
- self.table_id,
- is_add=0)
+ self._test.vapi.mpls_table_add_del(self.table_id, is_add=0)
def query_vpp_config(self):
dump = self._test.vapi.mpls_table_dump()
@@ -887,7 +923,7 @@ class VppMplsTable(VppObject):
return False
def object_id(self):
- return ("table-mpls-%d" % (self.table_id))
+ return "table-mpls-%d" % (self.table_id)
class VppMplsRoute(VppObject):
@@ -895,9 +931,16 @@ class VppMplsRoute(VppObject):
MPLS Route/LSP
"""
- def __init__(self, test, local_label, eos_bit, paths, table_id=0,
- is_multicast=0,
- eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP4):
+ def __init__(
+ self,
+ test,
+ local_label,
+ eos_bit,
+ paths,
+ table_id=0,
+ is_multicast=0,
+ eos_proto=FibPathProto.FIB_PATH_NH_PROTO_IP4,
+ ):
self._test = test
self.paths = paths
self.local_label = local_label
@@ -911,12 +954,16 @@ class VppMplsRoute(VppObject):
for path in self.paths:
paths.append(path.encode())
- r = self._test.vapi.mpls_route_add_del(self.table_id,
- self.local_label,
- self.eos_bit,
- self.eos_proto,
- self.is_multicast,
- paths, 1, 0)
+ r = self._test.vapi.mpls_route_add_del(
+ self.table_id,
+ self.local_label,
+ self.eos_bit,
+ self.eos_proto,
+ self.is_multicast,
+ paths,
+ 1,
+ 0,
+ )
self.stats_index = r.stats_index
self._test.registry.register(self, self._test.logger)
@@ -925,22 +972,28 @@ class VppMplsRoute(VppObject):
for path in self.paths:
paths.append(path.encode())
- self._test.vapi.mpls_route_add_del(self.table_id,
- self.local_label,
- self.eos_bit,
- self.eos_proto,
- self.is_multicast,
- paths, 0, 0)
+ self._test.vapi.mpls_route_add_del(
+ self.table_id,
+ self.local_label,
+ self.eos_bit,
+ self.eos_proto,
+ self.is_multicast,
+ paths,
+ 0,
+ 0,
+ )
def query_vpp_config(self):
- return find_mpls_route(self._test, self.table_id,
- self.local_label, self.eos_bit)
+ return find_mpls_route(
+ self._test, self.table_id, self.local_label, self.eos_bit
+ )
def object_id(self):
- return ("mpls-route-%d:%s/%d"
- % (self.table_id,
- self.local_label,
- 20 + self.eos_bit))
+ return "mpls-route-%d:%s/%d" % (
+ self.table_id,
+ self.local_label,
+ 20 + self.eos_bit,
+ )
def get_stats_to(self):
c = self._test.statistics.get_counter("/net/route/to")
diff --git a/test/vpp_ipip_tun_interface.py b/test/vpp_ipip_tun_interface.py
index 6517458d3d6..259767653bd 100644
--- a/test/vpp_ipip_tun_interface.py
+++ b/test/vpp_ipip_tun_interface.py
@@ -8,9 +8,9 @@ class VppIpIpTunInterface(VppTunnelInterface):
VPP IP-IP Tunnel interface
"""
- def __init__(self, test, parent_if, src, dst,
- table_id=0, dscp=0x0,
- flags=0, mode=None):
+ def __init__(
+ self, test, parent_if, src, dst, table_id=0, dscp=0x0, flags=0, mode=None
+ ):
super(VppIpIpTunInterface, self).__init__(test, parent_if)
self.src = src
self.dst = dst
@@ -19,23 +19,22 @@ class VppIpIpTunInterface(VppTunnelInterface):
self.flags = flags
self.mode = mode
if not self.mode:
- self.mode = (VppEnum.vl_api_tunnel_mode_t.
- TUNNEL_API_MODE_P2P)
+ self.mode = VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_P2P
def add_vpp_config(self):
r = self.test.vapi.ipip_add_tunnel(
tunnel={
- 'src': self.src,
- 'dst': self.dst,
- 'table_id': self.table_id,
- 'flags': self.flags,
- 'dscp': self.dscp,
- 'instance': 0xffffffff,
- 'mode': self.mode,
- })
+ "src": self.src,
+ "dst": self.dst,
+ "table_id": self.table_id,
+ "flags": self.flags,
+ "dscp": self.dscp,
+ "instance": 0xFFFFFFFF,
+ "mode": self.mode,
+ }
+ )
self.set_sw_if_index(r.sw_if_index)
- r = self.test.vapi.ipip_tunnel_dump(
- sw_if_index=self.sw_if_index)
+ r = self.test.vapi.ipip_tunnel_dump(sw_if_index=self.sw_if_index)
self.instance = r[0].tunnel.instance
self.test.registry.register(self, self.test.logger)
return self
@@ -44,7 +43,7 @@ class VppIpIpTunInterface(VppTunnelInterface):
self.test.vapi.ipip_del_tunnel(sw_if_index=self._sw_if_index)
def query_vpp_config(self):
- ts = self.test.vapi.ipip_tunnel_dump(sw_if_index=0xffffffff)
+ ts = self.test.vapi.ipip_tunnel_dump(sw_if_index=0xFFFFFFFF)
for t in ts:
if t.tunnel.sw_if_index == self._sw_if_index:
return True
diff --git a/test/vpp_ipsec.py b/test/vpp_ipsec.py
index 76080e05c3a..1db7f853e72 100644
--- a/test/vpp_ipsec.py
+++ b/test/vpp_ipsec.py
@@ -10,7 +10,7 @@ except NameError:
def mk_counter():
- return {'packets': 0, 'bytes': 0}
+ return {"packets": 0, "bytes": 0}
class VppIpsecSpd(VppObject):
@@ -52,14 +52,13 @@ class VppIpsecSpdItfBinding(VppObject):
self.itf = itf
def add_vpp_config(self):
- self.test.vapi.ipsec_interface_add_del_spd(self.spd.id,
- self.itf.sw_if_index)
+ self.test.vapi.ipsec_interface_add_del_spd(self.spd.id, self.itf.sw_if_index)
self.test.registry.register(self, self.test.logger)
def remove_vpp_config(self):
- self.test.vapi.ipsec_interface_add_del_spd(self.spd.id,
- self.itf.sw_if_index,
- is_add=0)
+ self.test.vapi.ipsec_interface_add_del_spd(
+ self.spd.id, self.itf.sw_if_index, is_add=0
+ )
def object_id(self):
return "bind-%s-to-%s" % (self.spd.id, self.itf)
@@ -77,17 +76,24 @@ class VppIpsecSpdEntry(VppObject):
VPP SPD DB Entry
"""
- def __init__(self, test, spd, sa_id,
- local_start, local_stop,
- remote_start, remote_stop,
- proto,
- priority=100,
- policy=None,
- is_outbound=1,
- remote_port_start=0,
- remote_port_stop=65535,
- local_port_start=0,
- local_port_stop=65535):
+ def __init__(
+ self,
+ test,
+ spd,
+ sa_id,
+ local_start,
+ local_stop,
+ remote_start,
+ remote_stop,
+ proto,
+ priority=100,
+ policy=None,
+ is_outbound=1,
+ remote_port_start=0,
+ remote_port_stop=65535,
+ local_port_start=0,
+ local_port_stop=65535,
+ ):
self.test = test
self.spd = spd
self.sa_id = sa_id
@@ -99,11 +105,10 @@ class VppIpsecSpdEntry(VppObject):
self.is_outbound = is_outbound
self.priority = priority
if not policy:
- self.policy = (VppEnum.vl_api_ipsec_spd_action_t.
- IPSEC_API_SPD_ACTION_BYPASS)
+ self.policy = VppEnum.vl_api_ipsec_spd_action_t.IPSEC_API_SPD_ACTION_BYPASS
else:
self.policy = policy
- self.is_ipv6 = (0 if self.local_start.version == 4 else 1)
+ self.is_ipv6 = 0 if self.local_start.version == 4 else 1
self.local_port_start = local_port_start
self.local_port_stop = local_port_stop
self.remote_port_start = remote_port_start
@@ -125,7 +130,8 @@ class VppIpsecSpdEntry(VppObject):
local_port_start=self.local_port_start,
local_port_stop=self.local_port_stop,
remote_port_start=self.remote_port_start,
- remote_port_stop=self.remote_port_stop)
+ remote_port_stop=self.remote_port_stop,
+ )
self.stat_index = rv.stat_index
self.test.registry.register(self, self.test.logger)
return self
@@ -147,25 +153,30 @@ class VppIpsecSpdEntry(VppObject):
local_port_stop=self.local_port_stop,
remote_port_start=self.remote_port_start,
remote_port_stop=self.remote_port_stop,
- is_add=0)
+ is_add=0,
+ )
def object_id(self):
- return "spd-entry-%d-%d-%d-%d-%d-%d" % (self.spd.id,
- self.priority,
- self.policy,
- self.is_outbound,
- self.is_ipv6,
- self.remote_port_start)
+ return "spd-entry-%d-%d-%d-%d-%d-%d" % (
+ self.spd.id,
+ self.priority,
+ self.policy,
+ self.is_outbound,
+ self.is_ipv6,
+ self.remote_port_start,
+ )
def query_vpp_config(self):
ss = self.test.vapi.ipsec_spd_dump(self.spd.id)
for s in ss:
- if s.entry.sa_id == self.sa_id and \
- s.entry.is_outbound == self.is_outbound and \
- s.entry.priority == self.priority and \
- s.entry.policy == self.policy and \
- s.entry.remote_address_start == self.remote_start and \
- s.entry.remote_port_start == self.remote_port_start:
+ if (
+ s.entry.sa_id == self.sa_id
+ and s.entry.is_outbound == self.is_outbound
+ and s.entry.priority == self.priority
+ and s.entry.policy == self.policy
+ and s.entry.remote_address_start == self.remote_start
+ and s.entry.remote_port_start == self.remote_port_start
+ ):
return True
return False
@@ -174,11 +185,11 @@ class VppIpsecSpdEntry(VppObject):
if worker is None:
total = mk_counter()
for t in c:
- total['packets'] += t[self.stat_index]['packets']
+ total["packets"] += t[self.stat_index]["packets"]
return total
else:
# +1 to skip main thread
- return c[worker+1][self.stat_index]
+ return c[worker + 1][self.stat_index]
class VppIpsecSA(VppObject):
@@ -188,14 +199,26 @@ class VppIpsecSA(VppObject):
DEFAULT_UDP_PORT = 4500
- def __init__(self, test, id, spi,
- integ_alg, integ_key,
- crypto_alg, crypto_key,
- proto,
- tun_src=None, tun_dst=None,
- flags=None, salt=0, tun_flags=None,
- dscp=None,
- udp_src=None, udp_dst=None, hop_limit=None):
+ def __init__(
+ self,
+ test,
+ id,
+ spi,
+ integ_alg,
+ integ_key,
+ crypto_alg,
+ crypto_key,
+ proto,
+ tun_src=None,
+ tun_dst=None,
+ flags=None,
+ salt=0,
+ tun_flags=None,
+ dscp=None,
+ udp_src=None,
+ udp_dst=None,
+ hop_limit=None,
+ ):
e = VppEnum.vl_api_ipsec_sad_flags_t
self.test = test
self.id = id
@@ -214,15 +237,16 @@ class VppIpsecSA(VppObject):
self.flags = e.IPSEC_API_SAD_FLAG_NONE
else:
self.flags = flags
- if (tun_src):
+ if tun_src:
self.tun_src = ip_address(text_type(tun_src))
self.flags = self.flags | e.IPSEC_API_SAD_FLAG_IS_TUNNEL
- if (tun_dst):
+ if tun_dst:
self.tun_dst = ip_address(text_type(tun_dst))
self.udp_src = udp_src
self.udp_dst = udp_dst
- self.tun_flags = (VppEnum.vl_api_tunnel_encap_decap_flags_t.
- TUNNEL_API_ENCAP_DECAP_FLAG_NONE)
+ self.tun_flags = (
+ VppEnum.vl_api_tunnel_encap_decap_flags_t.TUNNEL_API_ENCAP_DECAP_FLAG_NONE
+ )
if tun_flags:
self.tun_flags = tun_flags
self.dscp = VppEnum.vl_api_ip_dscp_t.IP_API_DSCP_CS0
@@ -233,38 +257,39 @@ class VppIpsecSA(VppObject):
self.hop_limit = hop_limit
def tunnel_encode(self):
- return {'src': (self.tun_src if self.tun_src else []),
- 'dst': (self.tun_dst if self.tun_dst else []),
- 'encap_decap_flags': self.tun_flags,
- 'dscp': self.dscp,
- 'hop_limit': self.hop_limit,
- 'table_id': self.table_id
- }
+ return {
+ "src": (self.tun_src if self.tun_src else []),
+ "dst": (self.tun_dst if self.tun_dst else []),
+ "encap_decap_flags": self.tun_flags,
+ "dscp": self.dscp,
+ "hop_limit": self.hop_limit,
+ "table_id": self.table_id,
+ }
def add_vpp_config(self):
entry = {
- 'sad_id': self.id,
- 'spi': self.spi,
- 'integrity_algorithm': self.integ_alg,
- 'integrity_key': {
- 'length': len(self.integ_key),
- 'data': self.integ_key,
+ "sad_id": self.id,
+ "spi": self.spi,
+ "integrity_algorithm": self.integ_alg,
+ "integrity_key": {
+ "length": len(self.integ_key),
+ "data": self.integ_key,
},
- 'crypto_algorithm': self.crypto_alg,
- 'crypto_key': {
- 'data': self.crypto_key,
- 'length': len(self.crypto_key),
+ "crypto_algorithm": self.crypto_alg,
+ "crypto_key": {
+ "data": self.crypto_key,
+ "length": len(self.crypto_key),
},
- 'protocol': self.proto,
- 'tunnel': self.tunnel_encode(),
- 'flags': self.flags,
- 'salt': self.salt
+ "protocol": self.proto,
+ "tunnel": self.tunnel_encode(),
+ "flags": self.flags,
+ "salt": self.salt,
}
# don't explicitly send the defaults, let papi fill them in
if self.udp_src:
- entry['udp_src_port'] = self.udp_src
+ entry["udp_src_port"] = self.udp_src
if self.udp_dst:
- entry['udp_dst_port'] = self.udp_dst
+ entry["udp_dst_port"] = self.udp_dst
r = self.test.vapi.ipsec_sad_entry_add(entry=entry)
self.stat_index = r.stat_index
self.test.registry.register(self, self.test.logger)
@@ -284,7 +309,7 @@ class VppIpsecSA(VppObject):
if b.entry.sad_id == self.id:
# if udp encap is configured then the ports should match
# those configured or the default
- if (self.flags & e.IPSEC_API_SAD_FLAG_UDP_ENCAP):
+ if self.flags & e.IPSEC_API_SAD_FLAG_UDP_ENCAP:
if not b.entry.flags & e.IPSEC_API_SAD_FLAG_UDP_ENCAP:
return False
if self.udp_src:
@@ -307,11 +332,11 @@ class VppIpsecSA(VppObject):
if worker is None:
total = mk_counter()
for t in c:
- total['packets'] += t[self.stat_index]['packets']
+ total["packets"] += t[self.stat_index]["packets"]
return total
else:
# +1 to skip main thread
- return c[worker+1][self.stat_index]
+ return c[worker + 1][self.stat_index]
def get_lost(self, worker=None):
c = self.test.statistics.get_counter("/net/ipsec/sa/lost")
@@ -322,7 +347,7 @@ class VppIpsecSA(VppObject):
return total
else:
# +1 to skip main thread
- return c[worker+1][self.stat_index]
+ return c[worker + 1][self.stat_index]
class VppIpsecTunProtect(VppObject):
@@ -348,11 +373,13 @@ class VppIpsecTunProtect(VppObject):
self.sa_out = sa_out.id
self.test.vapi.ipsec_tunnel_protect_update(
tunnel={
- 'sw_if_index': self.itf._sw_if_index,
- 'n_sa_in': len(self.sas_in),
- 'sa_out': self.sa_out,
- 'sa_in': self.sas_in,
- 'nh': self.nh})
+ "sw_if_index": self.itf._sw_if_index,
+ "n_sa_in": len(self.sas_in),
+ "sa_out": self.sa_out,
+ "sa_in": self.sas_in,
+ "nh": self.nh,
+ }
+ )
def object_id(self):
return "ipsec-tun-protect-%s-%s" % (self.itf, self.nh)
@@ -360,24 +387,24 @@ class VppIpsecTunProtect(VppObject):
def add_vpp_config(self):
self.test.vapi.ipsec_tunnel_protect_update(
tunnel={
- 'sw_if_index': self.itf._sw_if_index,
- 'n_sa_in': len(self.sas_in),
- 'sa_out': self.sa_out,
- 'sa_in': self.sas_in,
- 'nh': self.nh})
+ "sw_if_index": self.itf._sw_if_index,
+ "n_sa_in": len(self.sas_in),
+ "sa_out": self.sa_out,
+ "sa_in": self.sas_in,
+ "nh": self.nh,
+ }
+ )
self.test.registry.register(self, self.test.logger)
def remove_vpp_config(self):
self.test.vapi.ipsec_tunnel_protect_del(
- sw_if_index=self.itf.sw_if_index,
- nh=self.nh)
+ sw_if_index=self.itf.sw_if_index, nh=self.nh
+ )
def query_vpp_config(self):
- bs = self.test.vapi.ipsec_tunnel_protect_dump(
- sw_if_index=self.itf.sw_if_index)
+ bs = self.test.vapi.ipsec_tunnel_protect_dump(sw_if_index=self.itf.sw_if_index)
for b in bs:
- if b.tun.sw_if_index == self.itf.sw_if_index and \
- self.nh == str(b.tun.nh):
+ if b.tun.sw_if_index == self.itf.sw_if_index and self.nh == str(b.tun.nh):
return True
return False
@@ -387,20 +414,21 @@ class VppIpsecInterface(VppInterface):
VPP IPSec interface
"""
- def __init__(self, test, mode=None, instance=0xffffffff):
+ def __init__(self, test, mode=None, instance=0xFFFFFFFF):
super(VppIpsecInterface, self).__init__(test)
self.mode = mode
if not self.mode:
- self.mode = (VppEnum.vl_api_tunnel_mode_t.
- TUNNEL_API_MODE_P2P)
+ self.mode = VppEnum.vl_api_tunnel_mode_t.TUNNEL_API_MODE_P2P
self.instance = instance
def add_vpp_config(self):
- r = self.test.vapi.ipsec_itf_create(itf={
- 'user_instance': self.instance,
- 'mode': self.mode,
- })
+ r = self.test.vapi.ipsec_itf_create(
+ itf={
+ "user_instance": self.instance,
+ "mode": self.mode,
+ }
+ )
self.set_sw_if_index(r.sw_if_index)
self.test.registry.register(self, self.test.logger)
ts = self.test.vapi.ipsec_itf_dump(sw_if_index=self._sw_if_index)
@@ -411,7 +439,7 @@ class VppIpsecInterface(VppInterface):
self.test.vapi.ipsec_itf_delete(sw_if_index=self._sw_if_index)
def query_vpp_config(self):
- ts = self.test.vapi.ipsec_itf_dump(sw_if_index=0xffffffff)
+ ts = self.test.vapi.ipsec_itf_dump(sw_if_index=0xFFFFFFFF)
for t in ts:
if t.itf.sw_if_index == self._sw_if_index:
return True
diff --git a/test/vpp_l2.py b/test/vpp_l2.py
index 7307d28ad13..872f42851b9 100644
--- a/test/vpp_l2.py
+++ b/test/vpp_l2.py
@@ -7,6 +7,7 @@ from vpp_object import VppObject
from vpp_lo_interface import VppLoInterface
from vpp_papi import MACAddress
from vpp_sub_interface import L2_VTR_OP
+
try:
text_type = unicode
except NameError:
@@ -47,8 +48,7 @@ def find_bridge_domain_arp_entry(test, bd_id, mac, ip):
arps = test.vapi.bd_ip_mac_dump(bd_id)
for arp in arps:
# do IP addr comparison too once .api is fixed...
- if mac == str(arp.entry.mac) and \
- ip == str(arp.entry.ip):
+ if mac == str(arp.entry.mac) and ip == str(arp.entry.ip):
return True
return False
@@ -63,10 +63,17 @@ def find_l2_fib_entry(test, bd_id, mac, sw_if_index):
class VppBridgeDomain(VppObject):
-
- def __init__(self, test, bd_id,
- flood=1, uu_flood=1, forward=1,
- learn=1, arp_term=1, arp_ufwd=0):
+ def __init__(
+ self,
+ test,
+ bd_id,
+ flood=1,
+ uu_flood=1,
+ forward=1,
+ learn=1,
+ arp_term=1,
+ arp_ufwd=0,
+ ):
self._test = test
self.bd_id = bd_id
self.flood = flood
@@ -77,14 +84,16 @@ class VppBridgeDomain(VppObject):
self.arp_ufwd = arp_ufwd
def add_vpp_config(self):
- self._test.vapi.bridge_domain_add_del(bd_id=self.bd_id,
- flood=self.flood,
- uu_flood=self.uu_flood,
- forward=self.forward,
- learn=self.learn,
- arp_term=self.arp_term,
- arp_ufwd=self.arp_ufwd,
- is_add=1)
+ self._test.vapi.bridge_domain_add_del(
+ bd_id=self.bd_id,
+ flood=self.flood,
+ uu_flood=self.uu_flood,
+ forward=self.forward,
+ learn=self.learn,
+ arp_term=self.arp_term,
+ arp_ufwd=self.arp_ufwd,
+ is_add=1,
+ )
self._test.registry.register(self, self._test.logger)
return self
@@ -99,9 +108,7 @@ class VppBridgeDomain(VppObject):
class VppBridgeDomainPort(VppObject):
-
- def __init__(self, test, bd, itf,
- port_type=L2_PORT_TYPE.NORMAL):
+ def __init__(self, test, bd, itf, port_type=L2_PORT_TYPE.NORMAL):
self._test = test
self.bd = bd
self.itf = itf
@@ -109,27 +116,30 @@ class VppBridgeDomainPort(VppObject):
def add_vpp_config(self):
self._test.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.itf.sw_if_index, bd_id=self.bd.bd_id,
- port_type=self.port_type, enable=1)
+ rx_sw_if_index=self.itf.sw_if_index,
+ bd_id=self.bd.bd_id,
+ port_type=self.port_type,
+ enable=1,
+ )
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
self._test.vapi.sw_interface_set_l2_bridge(
- rx_sw_if_index=self.itf.sw_if_index, bd_id=self.bd.bd_id,
- port_type=self.port_type, enable=0)
+ rx_sw_if_index=self.itf.sw_if_index,
+ bd_id=self.bd.bd_id,
+ port_type=self.port_type,
+ enable=0,
+ )
def query_vpp_config(self):
- return find_bridge_domain_port(self._test,
- self.bd.bd_id,
- self.itf.sw_if_index)
+ return find_bridge_domain_port(self._test, self.bd.bd_id, self.itf.sw_if_index)
def object_id(self):
return "BD-Port-%s-%s" % (self.bd, self.itf)
class VppBridgeDomainArpEntry(VppObject):
-
def __init__(self, test, bd, mac, ip):
self._test = test
self.bd = bd
@@ -137,35 +147,28 @@ class VppBridgeDomainArpEntry(VppObject):
self.ip = ip
def add_vpp_config(self):
- self._test.vapi.bd_ip_mac_add_del(is_add=1,
- entry={
- 'bd_id': self.bd.bd_id,
- 'ip': self.ip,
- 'mac': self.mac})
+ self._test.vapi.bd_ip_mac_add_del(
+ is_add=1, entry={"bd_id": self.bd.bd_id, "ip": self.ip, "mac": self.mac}
+ )
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
- self._test.vapi.bd_ip_mac_add_del(is_add=0,
- entry={
- 'bd_id': self.bd.bd_id,
- 'ip': self.ip,
- 'mac': self.mac})
+ self._test.vapi.bd_ip_mac_add_del(
+ is_add=0, entry={"bd_id": self.bd.bd_id, "ip": self.ip, "mac": self.mac}
+ )
def query_vpp_config(self):
- return find_bridge_domain_arp_entry(self._test,
- self.bd.bd_id,
- self.mac,
- self.ip)
+ return find_bridge_domain_arp_entry(
+ self._test, self.bd.bd_id, self.mac, self.ip
+ )
def object_id(self):
return "BD-Arp-Entry-%s-%s-%s" % (self.bd, self.mac, self.ip)
class VppL2FibEntry(VppObject):
-
- def __init__(self, test, bd, mac, itf,
- static_mac=0, filter_mac=0, bvi_mac=-1):
+ def __init__(self, test, bd, mac, itf, static_mac=0, filter_mac=0, bvi_mac=-1):
self._test = test
self.bd = bd
self.mac = MACAddress(mac)
@@ -185,29 +188,26 @@ class VppL2FibEntry(VppObject):
is_add=1,
static_mac=self.static_mac,
filter_mac=self.filter_mac,
- bvi_mac=self.bvi_mac)
+ bvi_mac=self.bvi_mac,
+ )
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
self._test.vapi.l2fib_add_del(
- self.mac.packed,
- self.bd.bd_id,
- self.itf.sw_if_index,
- is_add=0)
+ self.mac.packed, self.bd.bd_id, self.itf.sw_if_index, is_add=0
+ )
def query_vpp_config(self):
- return find_l2_fib_entry(self._test,
- self.bd.bd_id,
- self.mac.packed,
- self.itf.sw_if_index)
+ return find_l2_fib_entry(
+ self._test, self.bd.bd_id, self.mac.packed, self.itf.sw_if_index
+ )
def object_id(self):
return "L2-Fib-Entry-%s-%s-%s" % (self.bd, self.mac, self.itf)
class VppL2Vtr(VppObject):
-
def __init__(self, test, itf, op):
self._test = test
self.itf = itf
@@ -226,7 +226,7 @@ class VppL2Vtr(VppObject):
d = self.itf.get_interface_config_from_dump(ds)
if d is not None:
- return (d.vtr_op == self.op)
+ return d.vtr_op == self.op
return False
def object_id(self):
diff --git a/test/vpp_lb.py b/test/vpp_lb.py
index d755cef70e5..56ae67b145f 100644
--- a/test/vpp_lb.py
+++ b/test/vpp_lb.py
@@ -16,7 +16,6 @@ import vpp_object
class VppLbVip(vpp_object.VppObject):
-
def __init__(self, test, pfx, sfx, port, protocol):
self._test = test
self.pfx = pfx
@@ -25,25 +24,21 @@ class VppLbVip(vpp_object.VppObject):
self.protocol = protocol
def add_vpp_config(self):
- self._test_vapi.lb_add_del_vip(pfx=self.pfx,
- sfx=self.pfx,
- port=self.port,
- protocol=self.protocol)
+ self._test_vapi.lb_add_del_vip(
+ pfx=self.pfx, sfx=self.pfx, port=self.port, protocol=self.protocol
+ )
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
- self._test.vapi.lb_add_del_vip(pfx=self.pfx,
- sfx=self.pfx,
- port=self.port,
- protocol=self.protocol,
- is_del=1)
+ self._test.vapi.lb_add_del_vip(
+ pfx=self.pfx, sfx=self.pfx, port=self.port, protocol=self.protocol, is_del=1
+ )
def query_vpp_config(self):
- details = self._test.vapi.lb_add_del_vip(fx=self.pfx,
- sfx=self.pfx,
- port=self.port,
- protocol=self.protocol)
+ details = self._test.vapi.lb_add_del_vip(
+ fx=self.pfx, sfx=self.pfx, port=self.port, protocol=self.protocol
+ )
return True if self == details else False
@@ -60,25 +55,28 @@ class VppLbAs(vpp_object.VppObject):
self.is_flush = is_flush
def add_vpp_config(self):
- self._test_vapi.lb_add_del_as(pfx=self.pfx,
- port=self.port,
- protocol=self.protocol,
- app_srv=self.app_srv,
- is_flush=self.is_flush,
- )
+ self._test_vapi.lb_add_del_as(
+ pfx=self.pfx,
+ port=self.port,
+ protocol=self.protocol,
+ app_srv=self.app_srv,
+ is_flush=self.is_flush,
+ )
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
- self._test.vapi.lb_add_del_as(pfx=self.pfx,
- port=self.port,
- protocol=self.protocol,
- app_srv=self.app_srv,
- is_flush=self.is_flush,
- is_del=1)
+ self._test.vapi.lb_add_del_as(
+ pfx=self.pfx,
+ port=self.port,
+ protocol=self.protocol,
+ app_srv=self.app_srv,
+ is_flush=self.is_flush,
+ is_del=1,
+ )
def query_vpp_config(self):
- details = self._test.vapi.lb_as_dump(pfx=self.pfx,
- port=self.port,
- protocol=self.protocol)
+ details = self._test.vapi.lb_as_dump(
+ pfx=self.pfx, port=self.port, protocol=self.protocol
+ )
return True if self == details else False
diff --git a/test/vpp_lo_interface.py b/test/vpp_lo_interface.py
index 36f56bed8d7..9478689811d 100644
--- a/test/vpp_lo_interface.py
+++ b/test/vpp_lo_interface.py
@@ -6,7 +6,7 @@ class VppLoInterface(VppInterface, VppObject):
"""VPP loopback interface."""
def __init__(self, test):
- """ Create VPP loopback interface """
+ """Create VPP loopback interface"""
super(VppLoInterface, self).__init__(test)
self.add_vpp_config()
diff --git a/test/vpp_memif.py b/test/vpp_memif.py
index 226f8af72b5..6a97c2b9884 100644
--- a/test/vpp_memif.py
+++ b/test/vpp_memif.py
@@ -7,7 +7,7 @@ from vpp_papi import VppEnum
def get_if_dump(dump, sw_if_index):
for d in dump:
- if (d.sw_if_index == sw_if_index):
+ if d.sw_if_index == sw_if_index:
return d
@@ -22,13 +22,11 @@ def remove_all_memif_vpp_config(_test):
dump = _test.vapi.memif_socket_filename_dump()
for d in dump:
if d.socket_id != 0:
- _test.vapi.memif_socket_filename_add_del(
- 0, d.socket_id, d.socket_filename)
+ _test.vapi.memif_socket_filename_add_del(0, d.socket_id, d.socket_filename)
class VppSocketFilename(VppObject):
- def __init__(self, test, socket_id, socket_filename,
- add_default_folder=False):
+ def __init__(self, test, socket_id, socket_filename, add_default_folder=False):
self._test = test
self.socket_id = socket_id
self.socket_filename = socket_filename
@@ -39,15 +37,16 @@ class VppSocketFilename(VppObject):
def add_vpp_config(self):
rv = self._test.vapi.memif_socket_filename_add_del(
- 1, self.socket_id, self.socket_filename)
+ 1, self.socket_id, self.socket_filename
+ )
if self.add_default_folder:
- self.socket_filename = "%s/%s" % (self._test.tempdir,
- self.socket_filename)
+ self.socket_filename = "%s/%s" % (self._test.tempdir, self.socket_filename)
return rv
def remove_vpp_config(self):
return self._test.vapi.memif_socket_filename_add_del(
- 0, self.socket_id, self.socket_filename)
+ 0, self.socket_id, self.socket_filename
+ )
def query_vpp_config(self):
return self._test.vapi.memif_socket_filename_dump()
@@ -57,9 +56,20 @@ class VppSocketFilename(VppObject):
class VppMemif(VppObject):
- def __init__(self, test, role, mode, rx_queues=0, tx_queues=0, if_id=0,
- socket_id=0, secret="", ring_size=0, buffer_size=0,
- hw_addr=""):
+ def __init__(
+ self,
+ test,
+ role,
+ mode,
+ rx_queues=0,
+ tx_queues=0,
+ if_id=0,
+ socket_id=0,
+ secret="",
+ ring_size=0,
+ buffer_size=0,
+ hw_addr="",
+ ):
self._test = test
self.role = role
self.mode = mode
@@ -72,9 +82,9 @@ class VppMemif(VppObject):
self.buffer_size = buffer_size
self.hw_addr = hw_addr
self.sw_if_index = None
- self.ip_prefix = IPv4Network("192.168.%d.%d/24" %
- (self.if_id + 1, self.role + 1),
- strict=False)
+ self.ip_prefix = IPv4Network(
+ "192.168.%d.%d/24" % (self.if_id + 1, self.role + 1), strict=False
+ )
def add_vpp_config(self):
rv = self._test.vapi.memif_create(
@@ -87,7 +97,8 @@ class VppMemif(VppObject):
secret=self.secret,
ring_size=self.ring_size,
buffer_size=self.buffer_size,
- hw_addr=self.hw_addr)
+ hw_addr=self.hw_addr,
+ )
try:
self.sw_if_index = rv.sw_if_index
except AttributeError:
@@ -99,12 +110,14 @@ class VppMemif(VppObject):
def admin_up(self):
if self.sw_if_index:
return self._test.vapi.sw_interface_set_flags(
- sw_if_index=self.sw_if_index, flags=1)
+ sw_if_index=self.sw_if_index, flags=1
+ )
def admin_down(self):
if self.sw_if_index:
return self._test.vapi.sw_interface_set_flags(
- sw_if_index=self.sw_if_index, flags=0)
+ sw_if_index=self.sw_if_index, flags=0
+ )
def wait_for_link_up(self, timeout, step=1):
if not self.sw_if_index:
@@ -121,7 +134,8 @@ class VppMemif(VppObject):
def config_ip4(self):
return self._test.vapi.sw_interface_add_del_address(
- sw_if_index=self.sw_if_index, prefix=self.ip_prefix)
+ sw_if_index=self.sw_if_index, prefix=self.ip_prefix
+ )
def remove_vpp_config(self):
self._test.vapi.memif_delete(self.sw_if_index)
diff --git a/test/vpp_mpls_tunnel_interface.py b/test/vpp_mpls_tunnel_interface.py
index 598936136ad..6c8941a3f19 100644
--- a/test/vpp_mpls_tunnel_interface.py
+++ b/test/vpp_mpls_tunnel_interface.py
@@ -1,4 +1,3 @@
-
from vpp_interface import VppInterface
@@ -8,7 +7,7 @@ class VppMPLSTunnelInterface(VppInterface):
"""
def __init__(self, test, paths, is_multicast=0, is_l2=0):
- """ Create MPLS Tunnel interface """
+ """Create MPLS Tunnel interface"""
super(VppMPLSTunnelInterface, self).__init__(test)
self.t_paths = paths
self.is_multicast = is_multicast
@@ -19,28 +18,29 @@ class VppMPLSTunnelInterface(VppInterface):
def add_vpp_config(self):
reply = self.test.vapi.mpls_tunnel_add_del(
- 0xffffffff,
+ 0xFFFFFFFF,
self.encoded_paths,
is_multicast=self.is_multicast,
- l2_only=self.is_l2)
+ l2_only=self.is_l2,
+ )
self.set_sw_if_index(reply.sw_if_index)
self.tunnel_index = reply.tunnel_index
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
reply = self.test.vapi.mpls_tunnel_add_del(
- self.sw_if_index,
- self.encoded_paths,
- is_add=0)
+ self.sw_if_index, self.encoded_paths, is_add=0
+ )
def query_vpp_config(self):
dump = self._test.vapi.mpls_tunnel_dump()
for t in dump:
- if self.sw_if_index == t.mt_tunnel.mt_sw_if_index and \
- self.tunnel_index == t.mt_tunnel.mt_tunnel_index:
+ if (
+ self.sw_if_index == t.mt_tunnel.mt_sw_if_index
+ and self.tunnel_index == t.mt_tunnel.mt_tunnel_index
+ ):
return True
return False
def object_id(self):
- return ("mpls-tunnel%d-%d" % (self.tunnel_index,
- self.sw_if_index))
+ return "mpls-tunnel%d-%d" % (self.tunnel_index, self.sw_if_index)
diff --git a/test/vpp_neighbor.py b/test/vpp_neighbor.py
index 9ba87005c46..d7940266605 100644
--- a/test/vpp_neighbor.py
+++ b/test/vpp_neighbor.py
@@ -7,6 +7,7 @@
from ipaddress import ip_address
from vpp_object import VppObject
from vpp_papi import mac_pton, VppEnum
+
try:
text_type = unicode
except NameError:
@@ -16,13 +17,14 @@ except NameError:
def find_nbr(test, sw_if_index, nbr_addr, is_static=0, mac=None):
ip_addr = ip_address(text_type(nbr_addr))
e = VppEnum.vl_api_ip_neighbor_flags_t
- nbrs = test.vapi.ip_neighbor_dump(sw_if_index=sw_if_index,
- af=ip_addr.vapi_af)
+ nbrs = test.vapi.ip_neighbor_dump(sw_if_index=sw_if_index, af=ip_addr.vapi_af)
for n in nbrs:
- if sw_if_index == n.neighbor.sw_if_index and \
- ip_addr == n.neighbor.ip_address and \
- is_static == (n.neighbor.flags & e.IP_API_NEIGHBOR_FLAG_STATIC):
+ if (
+ sw_if_index == n.neighbor.sw_if_index
+ and ip_addr == n.neighbor.ip_address
+ and is_static == (n.neighbor.flags & e.IP_API_NEIGHBOR_FLAG_STATIC)
+ ):
if mac:
if mac == str(n.neighbor.mac_address):
return True
@@ -36,8 +38,15 @@ class VppNeighbor(VppObject):
ARP Entry
"""
- def __init__(self, test, sw_if_index, mac_addr, nbr_addr,
- is_static=False, is_no_fib_entry=False):
+ def __init__(
+ self,
+ test,
+ sw_if_index,
+ mac_addr,
+ nbr_addr,
+ is_static=False,
+ is_no_fib_entry=False,
+ ):
self._test = test
self.sw_if_index = sw_if_index
self.mac_addr = mac_addr
@@ -52,35 +61,26 @@ class VppNeighbor(VppObject):
def add_vpp_config(self):
r = self._test.vapi.ip_neighbor_add_del(
- self.sw_if_index,
- self.mac_addr,
- self.nbr_addr,
- is_add=1,
- flags=self.flags)
+ self.sw_if_index, self.mac_addr, self.nbr_addr, is_add=1, flags=self.flags
+ )
self.stats_index = r.stats_index
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
self._test.vapi.ip_neighbor_add_del(
- self.sw_if_index,
- self.mac_addr,
- self.nbr_addr,
- is_add=0,
- flags=self.flags)
+ self.sw_if_index, self.mac_addr, self.nbr_addr, is_add=0, flags=self.flags
+ )
def is_static(self):
e = VppEnum.vl_api_ip_neighbor_flags_t
- return (self.flags & e.IP_API_NEIGHBOR_FLAG_STATIC)
+ return self.flags & e.IP_API_NEIGHBOR_FLAG_STATIC
def query_vpp_config(self):
- return find_nbr(self._test,
- self.sw_if_index,
- self.nbr_addr,
- self.is_static())
+ return find_nbr(self._test, self.sw_if_index, self.nbr_addr, self.is_static())
def object_id(self):
- return ("%d:%s" % (self.sw_if_index, self.nbr_addr))
+ return "%d:%s" % (self.sw_if_index, self.nbr_addr)
def get_stats(self):
c = self._test.statistics["/net/adjacency"]
diff --git a/test/vpp_object.py b/test/vpp_object.py
index 8dd2afac97c..d3652b1b62c 100644
--- a/test/vpp_object.py
+++ b/test/vpp_object.py
@@ -4,11 +4,11 @@ import abc
class VppObject(metaclass=abc.ABCMeta):
- """ Abstract vpp object """
+ """Abstract vpp object"""
@abc.abstractmethod
def add_vpp_config(self) -> None:
- """ Add the configuration for this object to vpp. """
+ """Add the configuration for this object to vpp."""
pass
@abc.abstractmethod
@@ -20,18 +20,18 @@ class VppObject(metaclass=abc.ABCMeta):
@abc.abstractmethod
def remove_vpp_config(self) -> None:
- """ Remove the configuration for this object from vpp. """
+ """Remove the configuration for this object from vpp."""
pass
def object_id(self) -> str:
- """ Return a unique string representing this object. """
+ """Return a unique string representing this object."""
return "Undefined. for <%s %s>" % (self.__class__.__name__, id(self))
def __str__(self) -> str:
return self.object_id()
def __repr__(self) -> str:
- return '<%s>' % self.object_id()
+ return "<%s>" % self.object_id()
def __hash__(self) -> int:
return hash(self.object_id())
@@ -49,7 +49,8 @@ class VppObject(metaclass=abc.ABCMeta):
class VppObjectRegistry:
- """ Class which handles automatic configuration cleanup. """
+ """Class which handles automatic configuration cleanup."""
+
_shared_state = {}
def __init__(self) -> None:
@@ -60,7 +61,7 @@ class VppObjectRegistry:
self._object_dict = dict()
def register(self, obj: VppObject, logger) -> None:
- """ Register an object in the registry. """
+ """Register an object in the registry."""
if obj.object_id() not in self._object_dict:
self._object_registry.append(obj)
self._object_dict[obj.object_id()] = obj
@@ -69,7 +70,7 @@ class VppObjectRegistry:
logger.debug("REG: duplicate add, ignoring (%s)" % obj)
def unregister_all(self, logger) -> None:
- """ Remove all object registrations from registry. """
+ """Remove all object registrations from registry."""
logger.debug("REG: removing all object registrations")
self._object_registry = []
self._object_dict = dict()
@@ -93,12 +94,14 @@ class VppObjectRegistry:
failed.append(obj)
else:
logger.info(
- "REG: Skipping removal for %s, configuration not present" %
- obj)
+ "REG: Skipping removal for %s, configuration not present" % obj
+ )
self.unregister_all(logger)
if failed:
logger.error("REG: Couldn't remove configuration for object(s):")
for obj in failed:
logger.error(repr(obj))
- raise Exception("Couldn't remove configuration for object(s): %s" %
- (", ".join(str(x) for x in failed)))
+ raise Exception(
+ "Couldn't remove configuration for object(s): %s"
+ % (", ".join(str(x) for x in failed))
+ )
diff --git a/test/vpp_papi_exceptions.py b/test/vpp_papi_exceptions.py
index 2f7da963f70..611e5a3845d 100644
--- a/test/vpp_papi_exceptions.py
+++ b/test/vpp_papi_exceptions.py
@@ -1,13 +1,13 @@
class CliFailedCommandError(Exception):
- """ cli command failed."""
+ """cli command failed."""
class CliSyntaxError(Exception):
- """ cli command had a syntax error."""
+ """cli command had a syntax error."""
class UnexpectedApiReturnValueError(Exception):
- """ exception raised when the API return value is unexpected """
+ """exception raised when the API return value is unexpected"""
def __init__(self, retval, message):
self.retval = retval
diff --git a/test/vpp_papi_provider.py b/test/vpp_papi_provider.py
index 9ff616c18e8..a4a3799f916 100644
--- a/test/vpp_papi_provider.py
+++ b/test/vpp_papi_provider.py
@@ -12,93 +12,215 @@ from six import moves, iteritems
from config import config
from vpp_papi import VPPApiClient
from hook import Hook
-from vpp_papi_exceptions import CliFailedCommandError, CliSyntaxError,\
- UnexpectedApiReturnValueError
+from vpp_papi_exceptions import (
+ CliFailedCommandError,
+ CliSyntaxError,
+ UnexpectedApiReturnValueError,
+)
#
# Dictionary keyed on message name to override default values for
# named parameters
#
defaultmapping = {
-
- 'acl_interface_add_del': {'is_add': 1, 'is_input': 1},
- 'bd_ip_mac_add_del': {'is_add': 1, },
- 'bfd_udp_add': {'is_authenticated': False, 'bfd_key_id': None,
- 'conf_key_id': None},
- 'bfd_udp_auth_activate': {'bfd_key_id': None, 'conf_key_id': None,
- 'is_delayed': False},
- 'bier_disp_entry_add_del': {'next_hop_rpf_id': -1, 'next_hop_is_ip4': 1,
- 'is_add': 1, },
- 'bier_disp_table_add_del': {'is_add': 1, },
- 'bier_imp_add': {'is_add': 1, },
- 'bier_route_add_del': {'is_add': 1, },
- 'bier_table_add_del': {'is_add': 1, },
- 'bridge_domain_add_del': {'flood': 1, 'uu_flood': 1, 'forward': 1,
- 'learn': 1, 'is_add': 1, },
- 'bvi_delete': {},
- 'geneve_add_del_tunnel': {'mcast_sw_if_index': 4294967295, 'is_add': 1,
- 'decap_next_index': 4294967295, },
- 'input_acl_set_interface': {'ip4_table_index': 4294967295,
- 'ip6_table_index': 4294967295,
- 'l2_table_index': 4294967295, },
- 'ip6_add_del_address_using_prefix': {'is_add': 1, },
- 'ip6nd_send_router_solicitation': {'irt': 1, 'mrt': 120, },
- 'ip_add_del_route': {'next_hop_sw_if_index': 4294967295,
- 'next_hop_weight': 1, 'next_hop_via_label': 1048576,
- 'classify_table_index': 4294967295, 'is_add': 1, },
- 'ip_mroute_add_del': {'is_add': 1, },
- 'ip_neighbor_add_del': {'is_add': 1, },
- 'ipsec_interface_add_del_spd': {'is_add': 1, },
- 'ipsec_spd_add_del': {'is_add': 1, },
- 'ipsec_spd_dump': {'sa_id': 4294967295, },
- 'ipsec_spd_entry_add_del': {'local_port_stop': 65535,
- 'remote_port_stop': 65535, 'priority': 100,
- 'is_outbound': 1,
- 'is_add': 1, },
- 'ipsec_tunnel_if_add_del': {'is_add': 1, 'anti_replay': 1, },
- 'l2_emulation': {'enable': 1, },
- 'l2fib_add_del': {'is_add': 1, },
- 'lisp_add_del_adjacency': {'is_add': 1, },
- 'lisp_add_del_local_eid': {'is_add': 1, },
- 'lisp_add_del_locator': {'priority': 1, 'weight': 1, 'is_add': 1, },
- 'lisp_add_del_locator_set': {'is_add': 1, },
- 'lisp_add_del_remote_mapping': {'is_add': 1, },
- 'macip_acl_interface_add_del': {'is_add': 1, },
- 'mpls_ip_bind_unbind': {'is_ip4': 1, 'is_bind': 1, },
- 'mpls_route_add_del': {'mr_next_hop_sw_if_index': 4294967295,
- 'mr_next_hop_weight': 1,
- 'mr_next_hop_via_label': 1048576,
- 'mr_is_add': 1,
- 'mr_classify_table_index': 4294967295, },
- 'mpls_table_add_del': {'is_add': 1, },
- 'mpls_tunnel_add_del': {'next_hop_sw_if_index': 4294967295,
- 'next_hop_weight': 1,
- 'next_hop_via_label': 1048576,
- 'is_add': 1, },
- 'output_acl_set_interface': {'ip4_table_index': 4294967295,
- 'ip6_table_index': 4294967295,
- 'l2_table_index': 4294967295, },
- 'pppoe_add_del_session': {'is_add': 1, },
- 'policer_add_del': {'is_add': 1, 'conform_action': {'type': 1}, },
- 'set_ipfix_exporter': {'collector_port': 4739, },
- 'sr_policy_add': {'weight': 1, 'is_encap': 1, },
- 'sw_interface_add_del_address': {'is_add': 1, },
- 'sw_interface_ip6nd_ra_prefix': {'val_lifetime': 4294967295,
- 'pref_lifetime': 4294967295, },
- 'sw_interface_set_ip_directed_broadcast': {'enable': 1, },
- 'sw_interface_set_l2_bridge': {'enable': 1, },
- 'sw_interface_set_mpls_enable': {'enable': 1, },
- 'sw_interface_set_mtu': {'mtu': [0, 0, 0, 0], },
- 'sw_interface_set_unnumbered': {'is_add': 1, },
- 'sw_interface_span_enable_disable': {'state': 1, },
- 'vxlan_add_del_tunnel': {'mcast_sw_if_index': 4294967295, 'is_add': 1,
- 'decap_next_index': 4294967295,
- 'instance': 4294967295, },
- 'want_bfd_events': {'enable_disable': 1, },
- 'want_igmp_events': {'enable': 1, },
- 'want_interface_events': {'enable_disable': 1, },
- 'want_l2_macs_events': {'enable_disable': 1, 'pid': os.getpid(), },
- 'want_l2_macs_events2': {'enable_disable': 1, 'pid': os.getpid(), },
+ "acl_interface_add_del": {"is_add": 1, "is_input": 1},
+ "bd_ip_mac_add_del": {
+ "is_add": 1,
+ },
+ "bfd_udp_add": {"is_authenticated": False, "bfd_key_id": None, "conf_key_id": None},
+ "bfd_udp_auth_activate": {
+ "bfd_key_id": None,
+ "conf_key_id": None,
+ "is_delayed": False,
+ },
+ "bier_disp_entry_add_del": {
+ "next_hop_rpf_id": -1,
+ "next_hop_is_ip4": 1,
+ "is_add": 1,
+ },
+ "bier_disp_table_add_del": {
+ "is_add": 1,
+ },
+ "bier_imp_add": {
+ "is_add": 1,
+ },
+ "bier_route_add_del": {
+ "is_add": 1,
+ },
+ "bier_table_add_del": {
+ "is_add": 1,
+ },
+ "bridge_domain_add_del": {
+ "flood": 1,
+ "uu_flood": 1,
+ "forward": 1,
+ "learn": 1,
+ "is_add": 1,
+ },
+ "bvi_delete": {},
+ "geneve_add_del_tunnel": {
+ "mcast_sw_if_index": 4294967295,
+ "is_add": 1,
+ "decap_next_index": 4294967295,
+ },
+ "input_acl_set_interface": {
+ "ip4_table_index": 4294967295,
+ "ip6_table_index": 4294967295,
+ "l2_table_index": 4294967295,
+ },
+ "ip6_add_del_address_using_prefix": {
+ "is_add": 1,
+ },
+ "ip6nd_send_router_solicitation": {
+ "irt": 1,
+ "mrt": 120,
+ },
+ "ip_add_del_route": {
+ "next_hop_sw_if_index": 4294967295,
+ "next_hop_weight": 1,
+ "next_hop_via_label": 1048576,
+ "classify_table_index": 4294967295,
+ "is_add": 1,
+ },
+ "ip_mroute_add_del": {
+ "is_add": 1,
+ },
+ "ip_neighbor_add_del": {
+ "is_add": 1,
+ },
+ "ipsec_interface_add_del_spd": {
+ "is_add": 1,
+ },
+ "ipsec_spd_add_del": {
+ "is_add": 1,
+ },
+ "ipsec_spd_dump": {
+ "sa_id": 4294967295,
+ },
+ "ipsec_spd_entry_add_del": {
+ "local_port_stop": 65535,
+ "remote_port_stop": 65535,
+ "priority": 100,
+ "is_outbound": 1,
+ "is_add": 1,
+ },
+ "ipsec_tunnel_if_add_del": {
+ "is_add": 1,
+ "anti_replay": 1,
+ },
+ "l2_emulation": {
+ "enable": 1,
+ },
+ "l2fib_add_del": {
+ "is_add": 1,
+ },
+ "lisp_add_del_adjacency": {
+ "is_add": 1,
+ },
+ "lisp_add_del_local_eid": {
+ "is_add": 1,
+ },
+ "lisp_add_del_locator": {
+ "priority": 1,
+ "weight": 1,
+ "is_add": 1,
+ },
+ "lisp_add_del_locator_set": {
+ "is_add": 1,
+ },
+ "lisp_add_del_remote_mapping": {
+ "is_add": 1,
+ },
+ "macip_acl_interface_add_del": {
+ "is_add": 1,
+ },
+ "mpls_ip_bind_unbind": {
+ "is_ip4": 1,
+ "is_bind": 1,
+ },
+ "mpls_route_add_del": {
+ "mr_next_hop_sw_if_index": 4294967295,
+ "mr_next_hop_weight": 1,
+ "mr_next_hop_via_label": 1048576,
+ "mr_is_add": 1,
+ "mr_classify_table_index": 4294967295,
+ },
+ "mpls_table_add_del": {
+ "is_add": 1,
+ },
+ "mpls_tunnel_add_del": {
+ "next_hop_sw_if_index": 4294967295,
+ "next_hop_weight": 1,
+ "next_hop_via_label": 1048576,
+ "is_add": 1,
+ },
+ "output_acl_set_interface": {
+ "ip4_table_index": 4294967295,
+ "ip6_table_index": 4294967295,
+ "l2_table_index": 4294967295,
+ },
+ "pppoe_add_del_session": {
+ "is_add": 1,
+ },
+ "policer_add_del": {
+ "is_add": 1,
+ "conform_action": {"type": 1},
+ },
+ "set_ipfix_exporter": {
+ "collector_port": 4739,
+ },
+ "sr_policy_add": {
+ "weight": 1,
+ "is_encap": 1,
+ },
+ "sw_interface_add_del_address": {
+ "is_add": 1,
+ },
+ "sw_interface_ip6nd_ra_prefix": {
+ "val_lifetime": 4294967295,
+ "pref_lifetime": 4294967295,
+ },
+ "sw_interface_set_ip_directed_broadcast": {
+ "enable": 1,
+ },
+ "sw_interface_set_l2_bridge": {
+ "enable": 1,
+ },
+ "sw_interface_set_mpls_enable": {
+ "enable": 1,
+ },
+ "sw_interface_set_mtu": {
+ "mtu": [0, 0, 0, 0],
+ },
+ "sw_interface_set_unnumbered": {
+ "is_add": 1,
+ },
+ "sw_interface_span_enable_disable": {
+ "state": 1,
+ },
+ "vxlan_add_del_tunnel": {
+ "mcast_sw_if_index": 4294967295,
+ "is_add": 1,
+ "decap_next_index": 4294967295,
+ "instance": 4294967295,
+ },
+ "want_bfd_events": {
+ "enable_disable": 1,
+ },
+ "want_igmp_events": {
+ "enable": 1,
+ },
+ "want_interface_events": {
+ "enable_disable": 1,
+ },
+ "want_l2_macs_events": {
+ "enable_disable": 1,
+ "pid": os.getpid(),
+ },
+ "want_l2_macs_events2": {
+ "enable_disable": 1,
+ "pid": os.getpid(),
+ },
}
@@ -125,35 +247,37 @@ class VppPapiProvider(object):
# calling the constructor.
VPPApiClient.apidir = config.vpp_install_dir
- self.vpp = VPPApiClient(logger=test_class.logger,
- read_timeout=read_timeout,
- use_socket=True,
- server_address=test_class.get_api_sock_path())
+ self.vpp = VPPApiClient(
+ logger=test_class.logger,
+ read_timeout=read_timeout,
+ use_socket=True,
+ server_address=test_class.get_api_sock_path(),
+ )
self._events = queue.Queue()
def __enter__(self):
return self
def assert_negative_api_retval(self):
- """ Expect API failure - used with with, e.g.::
+ """Expect API failure - used with with, e.g.::
- with self.vapi.assert_negative_api_retval():
- self.vapi.<api call expected to fail>
+ with self.vapi.assert_negative_api_retval():
+ self.vapi.<api call expected to fail>
- ..
+ ..
"""
self._expect_stack.append(self._expect_api_retval)
self._expect_api_retval = self._negative
return self
def assert_zero_api_retval(self):
- """ Expect API success - used with with, e.g.::
+ """Expect API success - used with with, e.g.::
- with self.vapi.assert_negative_api_retval():
- self.vapi.<api call expected to succeed>
+ with self.vapi.assert_negative_api_retval():
+ self.vapi.<api call expected to succeed>
- :note: this is useful only inside another with block
- as success is the default expected value
+ :note: this is useful only inside another with block
+ as success is the default expected value
"""
self._expect_stack.append(self._expect_api_retval)
self._expect_api_retval = self._zero
@@ -171,7 +295,7 @@ class VppPapiProvider(object):
self.hook = hook
def collect_events(self):
- """ Collect all events from the internal queue and clear the queue. """
+ """Collect all events from the internal queue and clear the queue."""
result = []
while True:
try:
@@ -182,26 +306,25 @@ class VppPapiProvider(object):
return result
def wait_for_event(self, timeout, name=None):
- """ Wait for and return next event. """
+ """Wait for and return next event."""
if name:
- self.test_class.logger.debug("Expecting event '%s' within %ss",
- name, timeout)
+ self.test_class.logger.debug(
+ "Expecting event '%s' within %ss", name, timeout
+ )
else:
- self.test_class.logger.debug("Expecting event within %ss",
- timeout)
+ self.test_class.logger.debug("Expecting event within %ss", timeout)
try:
e = self._events.get(timeout=timeout)
except queue.Empty:
raise Exception("Event did not occur within timeout")
msgname = type(e).__name__
if name and msgname != name:
- raise Exception("Unexpected event received: %s, expected: %s"
- % msgname)
+ raise Exception("Unexpected event received: %s, expected: %s" % msgname)
self.test_class.logger.debug("Returning event %s:%s" % (name, e))
return e
def __call__(self, name, event):
- """ Enqueue event in the internal event queue. """
+ """Enqueue event in the internal event queue."""
self.test_class.logger.debug("New event: %s: %s" % (name, event))
self._events.put(event)
@@ -255,7 +378,7 @@ class VppPapiProvider(object):
self.vpp.disconnect()
def api(self, api_fn, api_args, expected_retval=0):
- """ Call API function and check it's return value.
+ """Call API function and check it's return value.
Call the appropriate hooks before and after the API call
:param api_fn: API function to call
@@ -267,32 +390,44 @@ class VppPapiProvider(object):
self.hook.before_api(api_fn.__name__, api_args)
reply = api_fn(**api_args)
if self._expect_api_retval == self._negative:
- if hasattr(reply, 'retval') and reply.retval >= 0:
- msg = "%s(%s) passed unexpectedly: expected negative " \
- "return value instead of %d in %s" % \
- (api_fn.__name__, as_fn_signature(api_args),
- reply.retval,
- moves.reprlib.repr(reply))
+ if hasattr(reply, "retval") and reply.retval >= 0:
+ msg = (
+ "%s(%s) passed unexpectedly: expected negative "
+ "return value instead of %d in %s"
+ % (
+ api_fn.__name__,
+ as_fn_signature(api_args),
+ reply.retval,
+ moves.reprlib.repr(reply),
+ )
+ )
self.test_class.logger.info(msg)
raise UnexpectedApiReturnValueError(reply.retval, msg)
elif self._expect_api_retval == self._zero:
- if hasattr(reply, 'retval') and reply.retval != expected_retval:
- msg = "%s(%s) failed, expected %d return value instead " \
- "of %d in %s" % (api_fn.__name__,
- as_fn_signature(api_args),
- expected_retval, reply.retval,
- repr(reply))
+ if hasattr(reply, "retval") and reply.retval != expected_retval:
+ msg = (
+ "%s(%s) failed, expected %d return value instead "
+ "of %d in %s"
+ % (
+ api_fn.__name__,
+ as_fn_signature(api_args),
+ expected_retval,
+ reply.retval,
+ repr(reply),
+ )
+ )
self.test_class.logger.info(msg)
raise UnexpectedApiReturnValueError(reply.retval, msg)
else:
- raise Exception("Internal error, unexpected value for "
- "self._expect_api_retval %s" %
- self._expect_api_retval)
+ raise Exception(
+ "Internal error, unexpected value for "
+ "self._expect_api_retval %s" % self._expect_api_retval
+ )
self.hook.after_api(api_fn.__name__, api_args)
return reply
def cli_return_response(self, cli):
- """ Execute a CLI, calling the before/after hooks appropriately.
+ """Execute a CLI, calling the before/after hooks appropriately.
Return the reply without examining it
:param cli: CLI to execute
@@ -300,13 +435,13 @@ class VppPapiProvider(object):
"""
self.hook.before_cli(cli)
- cli += '\n'
+ cli += "\n"
r = self.papi.cli_inband(cmd=cli)
self.hook.after_cli(cli)
return r
def cli(self, cli):
- """ Execute a CLI, calling the before/after hooks appropriately.
+ """Execute a CLI, calling the before/after hooks appropriately.
:param cli: CLI to execute
:returns: CLI output
@@ -317,35 +452,43 @@ class VppPapiProvider(object):
raise CliSyntaxError(r.reply)
if r.retval != 0:
raise CliFailedCommandError(r.reply)
- if hasattr(r, 'reply'):
+ if hasattr(r, "reply"):
return r.reply
def ppcli(self, cli):
- """ Helper method to print CLI command in case of info logging level.
+ """Helper method to print CLI command in case of info logging level.
:param cli: CLI to execute
:returns: CLI output
"""
return cli + "\n" + self.cli(cli)
- def ip6nd_send_router_solicitation(self, sw_if_index, irt=1, mrt=120,
- mrc=0, mrd=0):
- return self.api(self.papi.ip6nd_send_router_solicitation,
- {'irt': irt,
- 'mrt': mrt,
- 'mrc': mrc,
- 'mrd': mrd,
- 'sw_if_index': sw_if_index})
+ def ip6nd_send_router_solicitation(self, sw_if_index, irt=1, mrt=120, mrc=0, mrd=0):
+ return self.api(
+ self.papi.ip6nd_send_router_solicitation,
+ {
+ "irt": irt,
+ "mrt": mrt,
+ "mrc": mrc,
+ "mrd": mrd,
+ "sw_if_index": sw_if_index,
+ },
+ )
def want_interface_events(self, enable_disable=1):
- return self.api(self.papi.want_interface_events,
- {'enable_disable': enable_disable,
- 'pid': os.getpid(), })
+ return self.api(
+ self.papi.want_interface_events,
+ {
+ "enable_disable": enable_disable,
+ "pid": os.getpid(),
+ },
+ )
def sw_interface_set_mac_address(self, sw_if_index, mac):
- return self.api(self.papi.sw_interface_set_mac_address,
- {'sw_if_index': sw_if_index,
- 'mac_address': mac})
+ return self.api(
+ self.papi.sw_interface_set_mac_address,
+ {"sw_if_index": sw_if_index, "mac_address": mac},
+ )
def p2p_ethernet_add(self, sw_if_index, remote_mac, subif_id):
"""Create p2p ethernet subinterface
@@ -356,9 +499,12 @@ class VppPapiProvider(object):
"""
return self.api(
self.papi.p2p_ethernet_add,
- {'parent_if_index': sw_if_index,
- 'remote_mac': remote_mac,
- 'subif_id': subif_id})
+ {
+ "parent_if_index": sw_if_index,
+ "remote_mac": remote_mac,
+ "subif_id": subif_id,
+ },
+ )
def p2p_ethernet_del(self, sw_if_index, remote_mac):
"""Delete p2p ethernet subinterface
@@ -369,8 +515,8 @@ class VppPapiProvider(object):
"""
return self.api(
self.papi.p2p_ethernet_del,
- {'parent_if_index': sw_if_index,
- 'remote_mac': remote_mac})
+ {"parent_if_index": sw_if_index, "remote_mac": remote_mac},
+ )
def create_vlan_subif(self, sw_if_index, vlan):
"""
@@ -379,42 +525,32 @@ class VppPapiProvider(object):
:param sw_if_index:
"""
- return self.api(self.papi.create_vlan_subif,
- {'sw_if_index': sw_if_index,
- 'vlan_id': vlan})
+ return self.api(
+ self.papi.create_vlan_subif, {"sw_if_index": sw_if_index, "vlan_id": vlan}
+ )
- def create_loopback(self, mac=''):
+ def create_loopback(self, mac=""):
"""
:param mac: (Optional)
"""
- return self.api(self.papi.create_loopback,
- {'mac_address': mac})
+ return self.api(self.papi.create_loopback, {"mac_address": mac})
def ip_route_dump(self, table_id, is_ip6=False):
- return self.api(self.papi.ip_route_dump,
- {'table': {
- 'table_id': table_id,
- 'is_ip6': is_ip6
- }})
+ return self.api(
+ self.papi.ip_route_dump, {"table": {"table_id": table_id, "is_ip6": is_ip6}}
+ )
def ip_route_v2_dump(self, table_id, is_ip6=False, src=0):
- return self.api(self.papi.ip_route_v2_dump,
- {
- 'src': src,
- 'table': {
- 'table_id': table_id,
- 'is_ip6': is_ip6
- }
- })
-
- def ip_neighbor_add_del(self,
- sw_if_index,
- mac_address,
- ip_address,
- is_add=1,
- flags=0):
- """ Add neighbor MAC to IPv4 or IPv6 address.
+ return self.api(
+ self.papi.ip_route_v2_dump,
+ {"src": src, "table": {"table_id": table_id, "is_ip6": is_ip6}},
+ )
+
+ def ip_neighbor_add_del(
+ self, sw_if_index, mac_address, ip_address, is_add=1, flags=0
+ ):
+ """Add neighbor MAC to IPv4 or IPv6 address.
:param sw_if_index:
:param mac_address:
@@ -425,23 +561,18 @@ class VppPapiProvider(object):
return self.api(
self.papi.ip_neighbor_add_del,
{
- 'is_add': is_add,
- 'neighbor': {
- 'sw_if_index': sw_if_index,
- 'flags': flags,
- 'mac_address': mac_address,
- 'ip_address': ip_address
- }
- }
+ "is_add": is_add,
+ "neighbor": {
+ "sw_if_index": sw_if_index,
+ "flags": flags,
+ "mac_address": mac_address,
+ "ip_address": ip_address,
+ },
+ },
)
- def udp_encap_add(self,
- src_ip,
- dst_ip,
- src_port,
- dst_port,
- table_id=0):
- """ Add a GRE tunnel
+ def udp_encap_add(self, src_ip, dst_ip, src_port, dst_port, table_id=0):
+ """Add a GRE tunnel
:param src_ip:
:param dst_ip:
:param src_port:
@@ -452,39 +583,34 @@ class VppPapiProvider(object):
return self.api(
self.papi.udp_encap_add,
{
- 'udp_encap': {
- 'src_ip': src_ip,
- 'dst_ip': dst_ip,
- 'src_port': src_port,
- 'dst_port': dst_port,
- 'table_id': table_id
+ "udp_encap": {
+ "src_ip": src_ip,
+ "dst_ip": dst_ip,
+ "src_port": src_port,
+ "dst_port": dst_port,
+ "table_id": table_id,
}
- })
+ },
+ )
def udp_encap_del(self, id):
- return self.api(self.papi.udp_encap_del, {'id': id})
+ return self.api(self.papi.udp_encap_del, {"id": id})
def udp_encap_dump(self):
return self.api(self.papi.udp_encap_dump, {})
def want_udp_encap_stats(self, enable=1):
- return self.api(self.papi.want_udp_encap_stats,
- {'enable': enable,
- 'pid': os.getpid()})
+ return self.api(
+ self.papi.want_udp_encap_stats, {"enable": enable, "pid": os.getpid()}
+ )
def mpls_route_dump(self, table_id):
- return self.api(self.papi.mpls_route_dump,
- {'table': {
- 'mt_table_id': table_id
- }})
+ return self.api(self.papi.mpls_route_dump, {"table": {"mt_table_id": table_id}})
def mpls_table_dump(self):
return self.api(self.papi.mpls_table_dump, {})
- def mpls_table_add_del(
- self,
- table_id,
- is_add=1):
+ def mpls_table_add_del(self, table_id, is_add=1):
"""
:param table_id
@@ -494,82 +620,74 @@ class VppPapiProvider(object):
return self.api(
self.papi.mpls_table_add_del,
- {'mt_table':
- {
- 'mt_table_id': table_id,
- },
- 'mt_is_add': is_add})
-
- def mpls_route_add_del(self,
- table_id,
- label,
- eos,
- eos_proto,
- is_multicast,
- paths,
- is_add,
- is_multipath):
- """ MPLS Route add/del """
+ {
+ "mt_table": {
+ "mt_table_id": table_id,
+ },
+ "mt_is_add": is_add,
+ },
+ )
+
+ def mpls_route_add_del(
+ self, table_id, label, eos, eos_proto, is_multicast, paths, is_add, is_multipath
+ ):
+ """MPLS Route add/del"""
return self.api(
self.papi.mpls_route_add_del,
- {'mr_route':
- {
- 'mr_table_id': table_id,
- 'mr_label': label,
- 'mr_eos': eos,
- 'mr_eos_proto': eos_proto,
- 'mr_is_multicast': is_multicast,
- 'mr_n_paths': len(paths),
- 'mr_paths': paths,
- },
- 'mr_is_add': is_add,
- 'mr_is_multipath': is_multipath})
-
- def mpls_ip_bind_unbind(
- self,
- label,
- prefix,
- table_id=0,
- ip_table_id=0,
- is_bind=1):
- """
- """
+ {
+ "mr_route": {
+ "mr_table_id": table_id,
+ "mr_label": label,
+ "mr_eos": eos,
+ "mr_eos_proto": eos_proto,
+ "mr_is_multicast": is_multicast,
+ "mr_n_paths": len(paths),
+ "mr_paths": paths,
+ },
+ "mr_is_add": is_add,
+ "mr_is_multipath": is_multipath,
+ },
+ )
+
+ def mpls_ip_bind_unbind(self, label, prefix, table_id=0, ip_table_id=0, is_bind=1):
+ """ """
return self.api(
self.papi.mpls_ip_bind_unbind,
- {'mb_mpls_table_id': table_id,
- 'mb_label': label,
- 'mb_ip_table_id': ip_table_id,
- 'mb_is_bind': is_bind,
- 'mb_prefix': prefix})
+ {
+ "mb_mpls_table_id": table_id,
+ "mb_label": label,
+ "mb_ip_table_id": ip_table_id,
+ "mb_is_bind": is_bind,
+ "mb_prefix": prefix,
+ },
+ )
def mpls_tunnel_add_del(
- self,
- tun_sw_if_index,
- paths,
- is_add=1,
- l2_only=0,
- is_multicast=0):
- """
- """
+ self, tun_sw_if_index, paths, is_add=1, l2_only=0, is_multicast=0
+ ):
+ """ """
return self.api(
self.papi.mpls_tunnel_add_del,
- {'mt_is_add': is_add,
- 'mt_tunnel':
- {
- 'mt_sw_if_index': tun_sw_if_index,
- 'mt_l2_only': l2_only,
- 'mt_is_multicast': is_multicast,
- 'mt_n_paths': len(paths),
- 'mt_paths': paths,
- }})
+ {
+ "mt_is_add": is_add,
+ "mt_tunnel": {
+ "mt_sw_if_index": tun_sw_if_index,
+ "mt_l2_only": l2_only,
+ "mt_is_multicast": is_multicast,
+ "mt_n_paths": len(paths),
+ "mt_paths": paths,
+ },
+ },
+ )
def input_acl_set_interface(
- self,
- is_add,
- sw_if_index,
- ip4_table_index=0xFFFFFFFF,
- ip6_table_index=0xFFFFFFFF,
- l2_table_index=0xFFFFFFFF):
+ self,
+ is_add,
+ sw_if_index,
+ ip4_table_index=0xFFFFFFFF,
+ ip6_table_index=0xFFFFFFFF,
+ l2_table_index=0xFFFFFFFF,
+ ):
"""
:param is_add:
:param sw_if_index:
@@ -580,19 +698,23 @@ class VppPapiProvider(object):
return self.api(
self.papi.input_acl_set_interface,
- {'sw_if_index': sw_if_index,
- 'ip4_table_index': ip4_table_index,
- 'ip6_table_index': ip6_table_index,
- 'l2_table_index': l2_table_index,
- 'is_add': is_add})
+ {
+ "sw_if_index": sw_if_index,
+ "ip4_table_index": ip4_table_index,
+ "ip6_table_index": ip6_table_index,
+ "l2_table_index": l2_table_index,
+ "is_add": is_add,
+ },
+ )
def output_acl_set_interface(
- self,
- is_add,
- sw_if_index,
- ip4_table_index=0xFFFFFFFF,
- ip6_table_index=0xFFFFFFFF,
- l2_table_index=0xFFFFFFFF):
+ self,
+ is_add,
+ sw_if_index,
+ ip4_table_index=0xFFFFFFFF,
+ ip6_table_index=0xFFFFFFFF,
+ l2_table_index=0xFFFFFFFF,
+ ):
"""
:param is_add:
:param sw_if_index:
@@ -603,50 +725,50 @@ class VppPapiProvider(object):
return self.api(
self.papi.output_acl_set_interface,
- {'sw_if_index': sw_if_index,
- 'ip4_table_index': ip4_table_index,
- 'ip6_table_index': ip6_table_index,
- 'l2_table_index': l2_table_index,
- 'is_add': is_add})
+ {
+ "sw_if_index": sw_if_index,
+ "ip4_table_index": ip4_table_index,
+ "ip6_table_index": ip6_table_index,
+ "l2_table_index": l2_table_index,
+ "is_add": is_add,
+ },
+ )
def set_ipfix_exporter(
- self,
- collector_address,
- src_address,
- path_mtu,
- template_interval,
- vrf_id=0,
- collector_port=4739,
- udp_checksum=0):
+ self,
+ collector_address,
+ src_address,
+ path_mtu,
+ template_interval,
+ vrf_id=0,
+ collector_port=4739,
+ udp_checksum=0,
+ ):
return self.api(
self.papi.set_ipfix_exporter,
{
- 'collector_address': collector_address,
- 'collector_port': collector_port,
- 'src_address': src_address,
- 'vrf_id': vrf_id,
- 'path_mtu': path_mtu,
- 'template_interval': template_interval,
- 'udp_checksum': udp_checksum,
- })
+ "collector_address": collector_address,
+ "collector_port": collector_port,
+ "src_address": src_address,
+ "vrf_id": vrf_id,
+ "path_mtu": path_mtu,
+ "template_interval": template_interval,
+ "udp_checksum": udp_checksum,
+ },
+ )
def mfib_signal_dump(self):
return self.api(self.papi.mfib_signal_dump, {})
def ip_mroute_dump(self, table_id, is_ip6=False):
- return self.api(self.papi.ip_mroute_dump,
- {'table': {
- 'table_id': table_id,
- 'is_ip6': is_ip6
- }})
+ return self.api(
+ self.papi.ip_mroute_dump,
+ {"table": {"table_id": table_id, "is_ip6": is_ip6}},
+ )
def pppoe_add_del_session(
- self,
- client_ip,
- client_mac,
- session_id=0,
- is_add=1,
- decap_vrf_id=0):
+ self, client_ip, client_mac, session_id=0, is_add=1, decap_vrf_id=0
+ ):
"""
:param is_add: (Default value = 1)
@@ -657,139 +779,155 @@ class VppPapiProvider(object):
:param decap_vrf_id: (Default value = 0)
"""
- return self.api(self.papi.pppoe_add_del_session,
- {'is_add': is_add,
- 'session_id': session_id,
- 'client_ip': client_ip,
- 'decap_vrf_id': decap_vrf_id,
- 'client_mac': client_mac})
+ return self.api(
+ self.papi.pppoe_add_del_session,
+ {
+ "is_add": is_add,
+ "session_id": session_id,
+ "client_ip": client_ip,
+ "decap_vrf_id": decap_vrf_id,
+ "client_mac": client_mac,
+ },
+ )
def sr_mpls_policy_add(self, bsid, weight, type, segments):
- return self.api(self.papi.sr_mpls_policy_add,
- {'bsid': bsid,
- 'weight': weight,
- 'is_spray': type,
- 'n_segments': len(segments),
- 'segments': segments})
+ return self.api(
+ self.papi.sr_mpls_policy_add,
+ {
+ "bsid": bsid,
+ "weight": weight,
+ "is_spray": type,
+ "n_segments": len(segments),
+ "segments": segments,
+ },
+ )
def sr_mpls_policy_del(self, bsid):
- return self.api(self.papi.sr_mpls_policy_del,
- {'bsid': bsid})
+ return self.api(self.papi.sr_mpls_policy_del, {"bsid": bsid})
- def bier_table_add_del(self,
- bti,
- mpls_label,
- is_add=1):
- """ BIER Table add/del """
+ def bier_table_add_del(self, bti, mpls_label, is_add=1):
+ """BIER Table add/del"""
return self.api(
self.papi.bier_table_add_del,
- {'bt_tbl_id': {"bt_set": bti.set_id,
- "bt_sub_domain": bti.sub_domain_id,
- "bt_hdr_len_id": bti.hdr_len_id},
- 'bt_label': mpls_label,
- 'bt_is_add': is_add})
+ {
+ "bt_tbl_id": {
+ "bt_set": bti.set_id,
+ "bt_sub_domain": bti.sub_domain_id,
+ "bt_hdr_len_id": bti.hdr_len_id,
+ },
+ "bt_label": mpls_label,
+ "bt_is_add": is_add,
+ },
+ )
def bier_table_dump(self):
return self.api(self.papi.bier_table_dump, {})
- def bier_route_add_del(self,
- bti,
- bp,
- paths,
- is_add=1,
- is_replace=0):
- """ BIER Route add/del """
+ def bier_route_add_del(self, bti, bp, paths, is_add=1, is_replace=0):
+ """BIER Route add/del"""
return self.api(
self.papi.bier_route_add_del,
{
- 'br_route': {
- 'br_tbl_id': {"bt_set": bti.set_id,
- "bt_sub_domain": bti.sub_domain_id,
- "bt_hdr_len_id": bti.hdr_len_id},
- 'br_bp': bp,
- 'br_n_paths': len(paths),
- 'br_paths': paths,
+ "br_route": {
+ "br_tbl_id": {
+ "bt_set": bti.set_id,
+ "bt_sub_domain": bti.sub_domain_id,
+ "bt_hdr_len_id": bti.hdr_len_id,
+ },
+ "br_bp": bp,
+ "br_n_paths": len(paths),
+ "br_paths": paths,
},
- 'br_is_add': is_add,
- 'br_is_replace': is_replace
- })
+ "br_is_add": is_add,
+ "br_is_replace": is_replace,
+ },
+ )
def bier_route_dump(self, bti):
return self.api(
self.papi.bier_route_dump,
- {'br_tbl_id': {"bt_set": bti.set_id,
- "bt_sub_domain": bti.sub_domain_id,
- "bt_hdr_len_id": bti.hdr_len_id}})
+ {
+ "br_tbl_id": {
+ "bt_set": bti.set_id,
+ "bt_sub_domain": bti.sub_domain_id,
+ "bt_hdr_len_id": bti.hdr_len_id,
+ }
+ },
+ )
- def bier_imp_add(self,
- bti,
- src,
- ibytes,
- is_add=1):
- """ BIER Imposition Add """
+ def bier_imp_add(self, bti, src, ibytes, is_add=1):
+ """BIER Imposition Add"""
return self.api(
self.papi.bier_imp_add,
- {'bi_tbl_id': {"bt_set": bti.set_id,
- "bt_sub_domain": bti.sub_domain_id,
- "bt_hdr_len_id": bti.hdr_len_id},
- 'bi_src': src,
- 'bi_n_bytes': len(ibytes),
- 'bi_bytes': ibytes})
+ {
+ "bi_tbl_id": {
+ "bt_set": bti.set_id,
+ "bt_sub_domain": bti.sub_domain_id,
+ "bt_hdr_len_id": bti.hdr_len_id,
+ },
+ "bi_src": src,
+ "bi_n_bytes": len(ibytes),
+ "bi_bytes": ibytes,
+ },
+ )
def bier_imp_del(self, bi_index):
- """ BIER Imposition del """
- return self.api(
- self.papi.bier_imp_del,
- {'bi_index': bi_index})
+ """BIER Imposition del"""
+ return self.api(self.papi.bier_imp_del, {"bi_index": bi_index})
def bier_imp_dump(self):
return self.api(self.papi.bier_imp_dump, {})
- def bier_disp_table_add_del(self,
- bdti,
- is_add=1):
- """ BIER Disposition Table add/del """
+ def bier_disp_table_add_del(self, bdti, is_add=1):
+ """BIER Disposition Table add/del"""
return self.api(
self.papi.bier_disp_table_add_del,
- {'bdt_tbl_id': bdti,
- 'bdt_is_add': is_add})
+ {"bdt_tbl_id": bdti, "bdt_is_add": is_add},
+ )
def bier_disp_table_dump(self):
return self.api(self.papi.bier_disp_table_dump, {})
- def bier_disp_entry_add_del(self,
- bdti,
- bp,
- payload_proto,
- next_hop_afi,
- next_hop,
- next_hop_tbl_id=0,
- next_hop_rpf_id=~0,
- next_hop_is_ip4=1,
- is_add=1):
- """ BIER Route add/del """
+ def bier_disp_entry_add_del(
+ self,
+ bdti,
+ bp,
+ payload_proto,
+ next_hop_afi,
+ next_hop,
+ next_hop_tbl_id=0,
+ next_hop_rpf_id=~0,
+ next_hop_is_ip4=1,
+ is_add=1,
+ ):
+ """BIER Route add/del"""
lstack = []
- while (len(lstack) < 16):
+ while len(lstack) < 16:
lstack.append({})
return self.api(
self.papi.bier_disp_entry_add_del,
- {'bde_tbl_id': bdti,
- 'bde_bp': bp,
- 'bde_payload_proto': payload_proto,
- 'bde_n_paths': 1,
- 'bde_paths': [{'table_id': next_hop_tbl_id,
- 'rpf_id': next_hop_rpf_id,
- 'n_labels': 0,
- 'label_stack': lstack}],
- 'bde_is_add': is_add})
+ {
+ "bde_tbl_id": bdti,
+ "bde_bp": bp,
+ "bde_payload_proto": payload_proto,
+ "bde_n_paths": 1,
+ "bde_paths": [
+ {
+ "table_id": next_hop_tbl_id,
+ "rpf_id": next_hop_rpf_id,
+ "n_labels": 0,
+ "label_stack": lstack,
+ }
+ ],
+ "bde_is_add": is_add,
+ },
+ )
def bier_disp_entry_dump(self, bdti):
- return self.api(
- self.papi.bier_disp_entry_dump,
- {'bde_tbl_id': bdti})
+ return self.api(self.papi.bier_disp_entry_dump, {"bde_tbl_id": bdti})
def ipsec_spd_add_del(self, spd_id, is_add=1):
- """ SPD add/del - Wrapper to add or del ipsec SPD
+ """SPD add/del - Wrapper to add or del ipsec SPD
Sample CLI : 'ipsec spd add 1'
:param spd_id - SPD ID to be created in the vpp . mandatory
@@ -798,8 +936,8 @@ class VppPapiProvider(object):
:returns: reply from the API
"""
return self.api(
- self.papi.ipsec_spd_add_del, {
- 'spd_id': spd_id, 'is_add': is_add})
+ self.papi.ipsec_spd_add_del, {"spd_id": spd_id, "is_add": is_add}
+ )
def ipsec_spds_dump(self):
return self.api(self.papi.ipsec_spds_dump, {})
@@ -818,32 +956,39 @@ class VppPapiProvider(object):
"""
return self.api(
self.papi.ipsec_interface_add_del_spd,
- {'spd_id': spd_id, 'sw_if_index': sw_if_index, 'is_add': is_add})
+ {"spd_id": spd_id, "sw_if_index": sw_if_index, "is_add": is_add},
+ )
def ipsec_spd_interface_dump(self, spd_index=None):
- return self.api(self.papi.ipsec_spd_interface_dump,
- {'spd_index': spd_index if spd_index else 0,
- 'spd_index_valid': 1 if spd_index else 0})
-
- def ipsec_spd_entry_add_del(self,
- spd_id,
- sa_id,
- local_address_start,
- local_address_stop,
- remote_address_start,
- remote_address_stop,
- local_port_start=0,
- local_port_stop=65535,
- remote_port_start=0,
- remote_port_stop=65535,
- protocol=0,
- policy=0,
- priority=100,
- is_outbound=1,
- is_add=1,
- is_ipv6=0,
- is_ip_any=0):
- """ IPSEC policy SPD add/del -
+ return self.api(
+ self.papi.ipsec_spd_interface_dump,
+ {
+ "spd_index": spd_index if spd_index else 0,
+ "spd_index_valid": 1 if spd_index else 0,
+ },
+ )
+
+ def ipsec_spd_entry_add_del(
+ self,
+ spd_id,
+ sa_id,
+ local_address_start,
+ local_address_stop,
+ remote_address_start,
+ remote_address_stop,
+ local_port_start=0,
+ local_port_stop=65535,
+ remote_port_start=0,
+ remote_port_stop=65535,
+ protocol=0,
+ policy=0,
+ priority=100,
+ is_outbound=1,
+ is_add=1,
+ is_ipv6=0,
+ is_ip_any=0,
+ ):
+ """IPSEC policy SPD add/del -
Wrapper to configure ipsec SPD policy entries in VPP
:param spd_id: SPD ID for the policy
@@ -867,130 +1012,144 @@ class VppPapiProvider(object):
return self.api(
self.papi.ipsec_spd_entry_add_del,
{
- 'is_add': is_add,
- 'entry':
- {
- 'spd_id': spd_id,
- 'sa_id': sa_id,
- 'local_address_start': local_address_start,
- 'local_address_stop': local_address_stop,
- 'remote_address_start': remote_address_start,
- 'remote_address_stop': remote_address_stop,
- 'local_port_start': local_port_start,
- 'local_port_stop': local_port_stop,
- 'remote_port_start': remote_port_start,
- 'remote_port_stop': remote_port_stop,
- 'protocol': protocol,
- 'policy': policy,
- 'priority': priority,
- 'is_outbound': is_outbound,
- }
- })
-
- def ipsec_spd_dump(self, spd_id, sa_id=0xffffffff):
- return self.api(self.papi.ipsec_spd_dump,
- {'spd_id': spd_id,
- 'sa_id': sa_id})
+ "is_add": is_add,
+ "entry": {
+ "spd_id": spd_id,
+ "sa_id": sa_id,
+ "local_address_start": local_address_start,
+ "local_address_stop": local_address_stop,
+ "remote_address_start": remote_address_start,
+ "remote_address_stop": remote_address_stop,
+ "local_port_start": local_port_start,
+ "local_port_stop": local_port_stop,
+ "remote_port_start": remote_port_start,
+ "remote_port_stop": remote_port_stop,
+ "protocol": protocol,
+ "policy": policy,
+ "priority": priority,
+ "is_outbound": is_outbound,
+ },
+ },
+ )
- def ipsec_tunnel_if_add_del(self, local_ip, remote_ip, local_spi,
- remote_spi, crypto_alg, local_crypto_key,
- remote_crypto_key, integ_alg, local_integ_key,
- remote_integ_key, is_add=1, esn=0, salt=0,
- anti_replay=1, renumber=0,
- udp_encap=0, show_instance=0xffffffff):
+ def ipsec_spd_dump(self, spd_id, sa_id=0xFFFFFFFF):
+ return self.api(self.papi.ipsec_spd_dump, {"spd_id": spd_id, "sa_id": sa_id})
+
+ def ipsec_tunnel_if_add_del(
+ self,
+ local_ip,
+ remote_ip,
+ local_spi,
+ remote_spi,
+ crypto_alg,
+ local_crypto_key,
+ remote_crypto_key,
+ integ_alg,
+ local_integ_key,
+ remote_integ_key,
+ is_add=1,
+ esn=0,
+ salt=0,
+ anti_replay=1,
+ renumber=0,
+ udp_encap=0,
+ show_instance=0xFFFFFFFF,
+ ):
return self.api(
self.papi.ipsec_tunnel_if_add_del,
{
- 'local_ip': local_ip,
- 'remote_ip': remote_ip,
- 'local_spi': local_spi,
- 'remote_spi': remote_spi,
- 'crypto_alg': crypto_alg,
- 'local_crypto_key_len': len(local_crypto_key),
- 'local_crypto_key': local_crypto_key,
- 'remote_crypto_key_len': len(remote_crypto_key),
- 'remote_crypto_key': remote_crypto_key,
- 'integ_alg': integ_alg,
- 'local_integ_key_len': len(local_integ_key),
- 'local_integ_key': local_integ_key,
- 'remote_integ_key_len': len(remote_integ_key),
- 'remote_integ_key': remote_integ_key,
- 'is_add': is_add,
- 'esn': esn,
- 'anti_replay': anti_replay,
- 'renumber': renumber,
- 'show_instance': show_instance,
- 'udp_encap': udp_encap,
- 'salt': salt
- })
+ "local_ip": local_ip,
+ "remote_ip": remote_ip,
+ "local_spi": local_spi,
+ "remote_spi": remote_spi,
+ "crypto_alg": crypto_alg,
+ "local_crypto_key_len": len(local_crypto_key),
+ "local_crypto_key": local_crypto_key,
+ "remote_crypto_key_len": len(remote_crypto_key),
+ "remote_crypto_key": remote_crypto_key,
+ "integ_alg": integ_alg,
+ "local_integ_key_len": len(local_integ_key),
+ "local_integ_key": local_integ_key,
+ "remote_integ_key_len": len(remote_integ_key),
+ "remote_integ_key": remote_integ_key,
+ "is_add": is_add,
+ "esn": esn,
+ "anti_replay": anti_replay,
+ "renumber": renumber,
+ "show_instance": show_instance,
+ "udp_encap": udp_encap,
+ "salt": salt,
+ },
+ )
def ipsec_select_backend(self, protocol, index):
- return self.api(self.papi.ipsec_select_backend,
- {'protocol': protocol, 'index': index})
+ return self.api(
+ self.papi.ipsec_select_backend, {"protocol": protocol, "index": index}
+ )
def ipsec_backend_dump(self):
return self.api(self.papi.ipsec_backend_dump, {})
- def punt_socket_register(self, reg, pathname,
- header_version=1):
- """ Register punt socket """
- return self.api(self.papi.punt_socket_register,
- {'header_version': header_version,
- 'punt': reg,
- 'pathname': pathname})
+ def punt_socket_register(self, reg, pathname, header_version=1):
+ """Register punt socket"""
+ return self.api(
+ self.papi.punt_socket_register,
+ {"header_version": header_version, "punt": reg, "pathname": pathname},
+ )
def punt_socket_deregister(self, reg):
- """ Unregister punt socket """
- return self.api(self.papi.punt_socket_deregister,
- {'punt': reg})
+ """Unregister punt socket"""
+ return self.api(self.papi.punt_socket_deregister, {"punt": reg})
def igmp_enable_disable(self, sw_if_index, enable, host):
- """ Enable/disable IGMP on a given interface """
- return self.api(self.papi.igmp_enable_disable,
- {'enable': enable,
- 'mode': host,
- 'sw_if_index': sw_if_index})
+ """Enable/disable IGMP on a given interface"""
+ return self.api(
+ self.papi.igmp_enable_disable,
+ {"enable": enable, "mode": host, "sw_if_index": sw_if_index},
+ )
def igmp_proxy_device_add_del(self, vrf_id, sw_if_index, add):
- """ Add/del IGMP proxy device """
- return self.api(self.papi.igmp_proxy_device_add_del,
- {'vrf_id': vrf_id, 'sw_if_index': sw_if_index,
- 'add': add})
+ """Add/del IGMP proxy device"""
+ return self.api(
+ self.papi.igmp_proxy_device_add_del,
+ {"vrf_id": vrf_id, "sw_if_index": sw_if_index, "add": add},
+ )
def igmp_proxy_device_add_del_interface(self, vrf_id, sw_if_index, add):
- """ Add/del interface to/from IGMP proxy device """
- return self.api(self.papi.igmp_proxy_device_add_del_interface,
- {'vrf_id': vrf_id, 'sw_if_index': sw_if_index,
- 'add': add})
+ """Add/del interface to/from IGMP proxy device"""
+ return self.api(
+ self.papi.igmp_proxy_device_add_del_interface,
+ {"vrf_id": vrf_id, "sw_if_index": sw_if_index, "add": add},
+ )
def igmp_listen(self, filter, sw_if_index, saddrs, gaddr):
- """ Listen for new (S,G) on specified interface
+ """Listen for new (S,G) on specified interface
:param enable: add/delas
:param sw_if_index: interface sw index
:param saddr: source ip4 addr
:param gaddr: group ip4 addr
"""
- return self.api(self.papi.igmp_listen,
- {
- 'group':
- {
- 'filter': filter,
- 'sw_if_index': sw_if_index,
- 'n_srcs': len(saddrs),
- 'saddrs': saddrs,
- 'gaddr': gaddr
- }
- })
+ return self.api(
+ self.papi.igmp_listen,
+ {
+ "group": {
+ "filter": filter,
+ "sw_if_index": sw_if_index,
+ "n_srcs": len(saddrs),
+ "saddrs": saddrs,
+ "gaddr": gaddr,
+ }
+ },
+ )
def igmp_clear_interface(self, sw_if_index):
- """ Remove all (S,G)s from specified interface
- doesn't send IGMP report!
+ """Remove all (S,G)s from specified interface
+ doesn't send IGMP report!
"""
- return self.api(
- self.papi.igmp_clear_interface, {
- 'sw_if_index': sw_if_index})
+ return self.api(self.papi.igmp_clear_interface, {"sw_if_index": sw_if_index})
def want_igmp_events(self, enable=1):
- return self.api(self.papi.want_igmp_events, {'enable': enable,
- 'pid': os.getpid()})
+ return self.api(
+ self.papi.want_igmp_events, {"enable": enable, "pid": os.getpid()}
+ )
diff --git a/test/vpp_pg_interface.py b/test/vpp_pg_interface.py
index 779eb0be6d9..2682774caab 100644
--- a/test/vpp_pg_interface.py
+++ b/test/vpp_pg_interface.py
@@ -13,20 +13,28 @@ from vpp_interface import VppInterface
from vpp_papi import VppEnum
from scapy.layers.l2 import Ether, ARP
-from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\
- ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, \
- IPv6ExtHdrHopByHop
+from scapy.layers.inet6 import (
+ IPv6,
+ ICMPv6ND_NS,
+ ICMPv6ND_NA,
+ ICMPv6NDOptSrcLLAddr,
+ ICMPv6NDOptDstLLAddr,
+ ICMPv6ND_RA,
+ RouterAlert,
+ IPv6ExtHdrHopByHop,
+)
from util import ppp, ppc, UnexpectedPacketError
from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr
class CaptureTimeoutError(Exception):
- """ Exception raised if capture or packet doesn't appear within timeout """
+ """Exception raised if capture or packet doesn't appear within timeout"""
+
pass
def is_ipv6_misc(p):
- """ Is packet one of uninteresting IPv6 broadcasts? """
+ """Is packet one of uninteresting IPv6 broadcasts?"""
if p.haslayer(ICMPv6ND_RA):
if in6_ismaddr(p[IPv6].dst):
return True
@@ -72,10 +80,9 @@ class VppPGInterface(VppInterface):
return self._out_path
def get_in_path(self, worker):
- """ pcap file path - injected packets"""
+ """pcap file path - injected packets"""
if worker is not None:
- return "%s/pg%u_wrk%u_in.pcap" % (self.test.tempdir, self.pg_index,
- worker)
+ return "%s/pg%u_wrk%u_in.pcap" % (self.test.tempdir, self.pg_index, worker)
return "%s/pg%u_in.pcap" % (self.test.tempdir, self.pg_index)
@property
@@ -92,7 +99,10 @@ class VppPGInterface(VppInterface):
def get_input_cli(self, nb_replays=None, worker=None):
"""return CLI string to load the injected packets"""
input_cli = "packet-generator new pcap %s source pg%u name %s" % (
- self.get_in_path(worker), self.pg_index, self.get_cap_name(worker))
+ self.get_in_path(worker),
+ self.pg_index,
+ self.get_cap_name(worker),
+ )
if nb_replays is not None:
return "%s limit %d" % (input_cli, nb_replays)
if worker is not None:
@@ -114,7 +124,7 @@ class VppPGInterface(VppInterface):
return v
def __init__(self, test, pg_index, gso, gso_size, mode):
- """ Create VPP packet-generator interface """
+ """Create VPP packet-generator interface"""
super().__init__(test)
r = test.vapi.pg_create_interface_v2(pg_index, gso, gso_size, mode)
@@ -130,9 +140,10 @@ class VppPGInterface(VppInterface):
self._out_file = "pg%u_out.pcap" % self.pg_index
self._out_path = self.test.tempdir + "/" + self._out_file
self._capture_cli = "packet-generator capture pg%u pcap %s" % (
- self.pg_index, self.out_path)
- self._cap_name = "pcap%u-sw_if_index-%s" % (
- self.pg_index, self.sw_if_index)
+ self.pg_index,
+ self.out_path,
+ )
+ self._cap_name = "pcap%u-sw_if_index-%s" % (self.pg_index, self.sw_if_index)
def handle_old_pcap_file(self, path, counter):
filename = os.path.basename(path)
@@ -149,22 +160,22 @@ class VppPGInterface(VppInterface):
try:
if os.path.isfile(path):
- name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % \
- (self.test.tempdir,
- time.time(),
- self.name,
- counter,
- filename)
+ name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % (
+ self.test.tempdir,
+ time.time(),
+ self.name,
+ counter,
+ filename,
+ )
self.test.logger.debug("Renaming %s->%s" % (path, name))
os.rename(path, name)
except OSError:
- self.test.logger.debug("OSError: Could not rename %s %s" %
- (path, filename))
+ self.test.logger.debug("OSError: Could not rename %s %s" % (path, filename))
def enable_capture(self):
- """ Enable capture on this packet-generator interface
- of at most n packets.
- If n < 0, this is no limit
+ """Enable capture on this packet-generator interface
+ of at most n packets.
+ If n < 0, this is no limit
"""
# disable the capture to flush the capture
self.disable_capture()
@@ -177,16 +188,14 @@ class VppPGInterface(VppInterface):
self.test.vapi.cli("%s disable" % self.capture_cli)
def coalesce_enable(self):
- """ Enable packet coalesce on this packet-generator interface"""
+ """Enable packet coalesce on this packet-generator interface"""
self._coalesce_enabled = 1
- self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index,
- 1)
+ self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 1)
def coalesce_disable(self):
- """ Disable packet coalesce on this packet-generator interface"""
+ """Disable packet coalesce on this packet-generator interface"""
self._coalesce_enabled = 0
- self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index,
- 0)
+ self.test.vapi.pg_interface_enable_disable_coalesce(self.sw_if_index, 0)
def add_stream(self, pkts, nb_replays=None, worker=None):
"""
@@ -201,31 +210,31 @@ class VppPGInterface(VppInterface):
self.test.vapi.cli(self.get_input_cli(nb_replays, worker))
def generate_debug_aid(self, kind):
- """ Create a hardlink to the out file with a counter and a file
+ """Create a hardlink to the out file with a counter and a file
containing stack trace to ease debugging in case of multiple capture
- files present. """
- self.test.logger.debug("Generating debug aid for %s on %s" %
- (kind, self._name))
- link_path, stack_path = ["%s/debug_%s_%s_%s.%s" %
- (self.test.tempdir, self._name,
- self._out_assert_counter, kind, suffix)
- for suffix in ["pcap", "stack"]
- ]
+ files present."""
+ self.test.logger.debug("Generating debug aid for %s on %s" % (kind, self._name))
+ link_path, stack_path = [
+ "%s/debug_%s_%s_%s.%s"
+ % (self.test.tempdir, self._name, self._out_assert_counter, kind, suffix)
+ for suffix in ["pcap", "stack"]
+ ]
os.link(self.out_path, link_path)
with open(stack_path, "w") as f:
f.writelines(format_stack())
self._out_assert_counter += 1
def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
- """ Helper method to get capture and filter it """
+ """Helper method to get capture and filter it"""
try:
if not self.wait_for_capture_file(timeout):
return None
output = rdpcap(self.out_path)
self.test.logger.debug("Capture has %s packets" % len(output.res))
except:
- self.test.logger.debug("Exception in scapy.rdpcap (%s): %s" %
- (self.out_path, format_exc()))
+ self.test.logger.debug(
+ "Exception in scapy.rdpcap (%s): %s" % (self.out_path, format_exc())
+ )
return None
before = len(output.res)
if filter_out_fn:
@@ -233,13 +242,15 @@ class VppPGInterface(VppInterface):
removed = before - len(output.res)
if removed:
self.test.logger.debug(
- "Filtered out %s packets from capture (returning %s)" %
- (removed, len(output.res)))
+ "Filtered out %s packets from capture (returning %s)"
+ % (removed, len(output.res))
+ )
return output
- def get_capture(self, expected_count=None, remark=None, timeout=1,
- filter_out_fn=is_ipv6_misc):
- """ Get captured packets
+ def get_capture(
+ self, expected_count=None, remark=None, timeout=1, filter_out_fn=is_ipv6_misc
+ ):
+ """Get captured packets
:param expected_count: expected number of packets to capture, if None,
then self.test.packet_count_for_dst_pg_idx is
@@ -255,15 +266,16 @@ class VppPGInterface(VppInterface):
name = self.name if remark is None else "%s (%s)" % (self.name, remark)
based_on = "based on provided argument"
if expected_count is None:
- expected_count = \
- self.test.get_packet_count_for_if_idx(self.sw_if_index)
+ expected_count = self.test.get_packet_count_for_if_idx(self.sw_if_index)
based_on = "based on stored packet_infos"
if expected_count == 0:
raise Exception(
- "Internal error, expected packet count for %s is 0!" %
- name)
- self.test.logger.debug("Expecting to capture %s (%s) packets on %s" % (
- expected_count, based_on, name))
+ "Internal error, expected packet count for %s is 0!" % name
+ )
+ self.test.logger.debug(
+ "Expecting to capture %s (%s) packets on %s"
+ % (expected_count, based_on, name)
+ )
while remaining_time > 0:
before = time.time()
capture = self._get_capture(remaining_time, filter_out_fn)
@@ -273,14 +285,14 @@ class VppPGInterface(VppInterface):
# bingo, got the packets we expected
return capture
elif len(capture.res) > expected_count:
- self.test.logger.error(
- ppc("Unexpected packets captured:", capture))
+ self.test.logger.error(ppc("Unexpected packets captured:", capture))
break
else:
- self.test.logger.debug("Partial capture containing %s "
- "packets doesn't match expected "
- "count %s (yet?)" %
- (len(capture.res), expected_count))
+ self.test.logger.debug(
+ "Partial capture containing %s "
+ "packets doesn't match expected "
+ "count %s (yet?)" % (len(capture.res), expected_count)
+ )
elif expected_count == 0:
# bingo, got None as we expected - return empty capture
return PacketList()
@@ -290,26 +302,29 @@ class VppPGInterface(VppInterface):
if len(capture) > 0 and 0 == expected_count:
rem = f"\n{remark}" if remark else ""
raise UnexpectedPacketError(
- capture[0],
- f"\n({len(capture)} packets captured in total){rem}")
- raise Exception("Captured packets mismatch, captured %s packets, "
- "expected %s packets on %s" %
- (len(capture.res), expected_count, name))
+ capture[0], f"\n({len(capture)} packets captured in total){rem}"
+ )
+ raise Exception(
+ "Captured packets mismatch, captured %s packets, "
+ "expected %s packets on %s" % (len(capture.res), expected_count, name)
+ )
else:
if 0 == expected_count:
return
raise Exception("No packets captured on %s" % name)
- def assert_nothing_captured(self, timeout=1, remark=None,
- filter_out_fn=is_ipv6_misc):
- """ Assert that nothing unfiltered was captured on interface
+ def assert_nothing_captured(
+ self, timeout=1, remark=None, filter_out_fn=is_ipv6_misc
+ ):
+ """Assert that nothing unfiltered was captured on interface
:param remark: remark printed into debug logs
:param filter_out_fn: filter applied to each packet, packets for which
the filter returns True are removed from capture
"""
- capture = self.get_capture(0, timeout=timeout, remark=remark,
- filter_out_fn=filter_out_fn)
+ capture = self.get_capture(
+ 0, timeout=timeout, remark=remark, filter_out_fn=filter_out_fn
+ )
if not capture or len(capture.res) == 0:
# junk filtered out, we're good
return
@@ -322,7 +337,7 @@ class VppPGInterface(VppInterface):
#
# also have a 5-minute timeout just in case things go terribly wrong...
deadline = time.time() + 300
- while self.test.vapi.cli('show packet-generator').find("Yes") != -1:
+ while self.test.vapi.cli("show packet-generator").find("Yes") != -1:
self._test.sleep(0.01) # yield
if time.time() > deadline:
self.test.logger.debug("Timeout waiting for pg to stop")
@@ -339,19 +354,21 @@ class VppPGInterface(VppInterface):
self.wait_for_pg_stop()
deadline = time.time() + timeout
if not os.path.isfile(self.out_path):
- self.test.logger.debug("Waiting for capture file %s to appear, "
- "timeout is %ss" % (self.out_path, timeout))
+ self.test.logger.debug(
+ "Waiting for capture file %s to appear, "
+ "timeout is %ss" % (self.out_path, timeout)
+ )
else:
- self.test.logger.debug("Capture file %s already exists" %
- self.out_path)
+ self.test.logger.debug("Capture file %s already exists" % self.out_path)
return True
while time.time() < deadline:
if os.path.isfile(self.out_path):
break
self._test.sleep(0) # yield
if os.path.isfile(self.out_path):
- self.test.logger.debug("Capture file appeared after %fs" %
- (time.time() - (deadline - timeout)))
+ self.test.logger.debug(
+ "Capture file appeared after %fs" % (time.time() - (deadline - timeout))
+ )
else:
self.test.logger.debug("Timeout - capture file still nowhere")
return False
@@ -374,7 +391,8 @@ class VppPGInterface(VppInterface):
if len(hdr) == packet_header_size:
# parse the capture length - caplen
sec, usec, caplen, wirelen = struct.unpack(
- self._pcap_reader.endian + "IIII", hdr)
+ self._pcap_reader.endian + "IIII", hdr
+ )
self._pcap_reader.f.seek(0, 2) # seek to end of file
end_pos = self._pcap_reader.f.tell() # get position at end
if end_pos >= orig_pos + len(hdr) + caplen:
@@ -394,19 +412,22 @@ class VppPGInterface(VppInterface):
deadline = time.time() + timeout
if self._pcap_reader is None:
if not self.wait_for_capture_file(timeout):
- raise CaptureTimeoutError("Capture file %s did not appear "
- "within timeout" % self.out_path)
+ raise CaptureTimeoutError(
+ "Capture file %s did not appear within timeout" % self.out_path
+ )
while time.time() < deadline:
try:
self._pcap_reader = PcapReader(self.out_path)
break
except:
self.test.logger.debug(
- "Exception in scapy.PcapReader(%s): %s" %
- (self.out_path, format_exc()))
+ "Exception in scapy.PcapReader(%s): %s"
+ % (self.out_path, format_exc())
+ )
if not self._pcap_reader:
- raise CaptureTimeoutError("Capture file %s did not appear within "
- "timeout" % self.out_path)
+ raise CaptureTimeoutError(
+ "Capture file %s did not appear within timeout" % self.out_path
+ )
poll = False
if timeout > 0:
@@ -423,12 +444,14 @@ class VppPGInterface(VppInterface):
if p is not None:
if filter_out_fn is not None and filter_out_fn(p):
self.test.logger.debug(
- "Packet received after %ss was filtered out" %
- (time.time() - (deadline - timeout)))
+ "Packet received after %ss was filtered out"
+ % (time.time() - (deadline - timeout))
+ )
else:
self.test.logger.debug(
- "Packet received after %fs" %
- (time.time() - (deadline - timeout)))
+ "Packet received after %fs"
+ % (time.time() - (deadline - timeout))
+ )
return p
self._test.sleep(0) # yield
poll = False
@@ -437,9 +460,12 @@ class VppPGInterface(VppInterface):
def create_arp_req(self):
"""Create ARP request applicable for this interface"""
- return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
- ARP(op=ARP.who_has, pdst=self.local_ip4,
- psrc=self.remote_ip4, hwsrc=self.remote_mac))
+ return Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) / ARP(
+ op=ARP.who_has,
+ pdst=self.local_ip4,
+ psrc=self.remote_ip4,
+ hwsrc=self.remote_mac,
+ )
def create_ndp_req(self, addr=None):
"""Create NDP - NS applicable for this interface"""
@@ -448,10 +474,12 @@ class VppPGInterface(VppInterface):
nsma = in6_getnsma(inet_pton(socket.AF_INET6, addr))
d = inet_ntop(socket.AF_INET6, nsma)
- return (Ether(dst=in6_getnsmac(nsma)) /
- IPv6(dst=d, src=self.remote_ip6) /
- ICMPv6ND_NS(tgt=addr) /
- ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))
+ return (
+ Ether(dst=in6_getnsmac(nsma))
+ / IPv6(dst=d, src=self.remote_ip6)
+ / ICMPv6ND_NS(tgt=addr)
+ / ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac)
+ )
def resolve_arp(self, pg_interface=None):
"""Resolve ARP using provided packet-generator interface
@@ -462,8 +490,10 @@ class VppPGInterface(VppInterface):
"""
if pg_interface is None:
pg_interface = self
- self.test.logger.info("Sending ARP request for %s on port %s" %
- (self.local_ip4, pg_interface.name))
+ self.test.logger.info(
+ "Sending ARP request for %s on port %s"
+ % (self.local_ip4, pg_interface.name)
+ )
arp_req = self.create_arp_req()
pg_interface.add_stream(arp_req)
pg_interface.enable_capture()
@@ -472,21 +502,21 @@ class VppPGInterface(VppInterface):
try:
captured_packet = pg_interface.wait_for_packet(1)
except:
- self.test.logger.info("No ARP received on port %s" %
- pg_interface.name)
+ self.test.logger.info("No ARP received on port %s" % pg_interface.name)
return
arp_reply = captured_packet.copy() # keep original for exception
try:
if arp_reply[ARP].op == ARP.is_at:
- self.test.logger.info("VPP %s MAC address is %s " %
- (self.name, arp_reply[ARP].hwsrc))
+ self.test.logger.info(
+ "VPP %s MAC address is %s " % (self.name, arp_reply[ARP].hwsrc)
+ )
self._local_mac = arp_reply[ARP].hwsrc
else:
- self.test.logger.info("No ARP received on port %s" %
- pg_interface.name)
+ self.test.logger.info("No ARP received on port %s" % pg_interface.name)
except:
self.test.logger.error(
- ppp("Unexpected response to ARP request:", captured_packet))
+ ppp("Unexpected response to ARP request:", captured_packet)
+ )
raise
def resolve_ndp(self, pg_interface=None, timeout=1, link_layer=False):
@@ -502,8 +532,9 @@ class VppPGInterface(VppInterface):
if pg_interface is None:
pg_interface = self
addr = self.local_ip6_ll if link_layer else self.local_ip6
- self.test.logger.info("Sending NDP request for %s on port %s" %
- (addr, pg_interface.name))
+ self.test.logger.info(
+ "Sending NDP request for %s on port %s" % (addr, pg_interface.name)
+ )
ndp_req = self.create_ndp_req(addr)
pg_interface.add_stream(ndp_req)
pg_interface.enable_capture()
@@ -516,25 +547,26 @@ class VppPGInterface(VppInterface):
while now < deadline:
try:
captured_packet = pg_interface.wait_for_packet(
- deadline - now, filter_out_fn=None)
+ deadline - now, filter_out_fn=None
+ )
except:
- self.test.logger.error(
- "Timeout while waiting for NDP response")
+ self.test.logger.error("Timeout while waiting for NDP response")
raise
ndp_reply = captured_packet.copy() # keep original for exception
try:
ndp_na = ndp_reply[ICMPv6ND_NA]
opt = ndp_na[ICMPv6NDOptDstLLAddr]
- self.test.logger.info("VPP %s MAC address is %s " %
- (self.name, opt.lladdr))
+ self.test.logger.info(
+ "VPP %s MAC address is %s " % (self.name, opt.lladdr)
+ )
self._local_mac = opt.lladdr
self.test.logger.debug(self.test.vapi.cli("show trace"))
# we now have the MAC we've been after
return
except:
self.test.logger.info(
- ppp("Unexpected response to NDP request:",
- captured_packet))
+ ppp("Unexpected response to NDP request:", captured_packet)
+ )
now = time.time()
self.test.logger.debug(self.test.vapi.cli("show trace"))
diff --git a/test/vpp_policer.py b/test/vpp_policer.py
index 0f3b073d6e3..b0097b370e5 100644
--- a/test/vpp_policer.py
+++ b/test/vpp_policer.py
@@ -8,25 +8,36 @@ class Dir(Enum):
TX = 1
-class PolicerAction():
- """ sse2 qos action """
+class PolicerAction:
+ """sse2 qos action"""
def __init__(self, type, dscp):
self.type = type
self.dscp = dscp
def encode(self):
- return {'type': self.type, 'dscp': self.dscp}
+ return {"type": self.type, "dscp": self.dscp}
class VppPolicer(VppObject):
- """ Policer """
-
- def __init__(self, test, name, cir, eir, commited_burst, excess_burst,
- rate_type=0, round_type=0, type=0, color_aware=False,
- conform_action=PolicerAction(1, 0),
- exceed_action=PolicerAction(0, 0),
- violate_action=PolicerAction(0, 0)):
+ """Policer"""
+
+ def __init__(
+ self,
+ test,
+ name,
+ cir,
+ eir,
+ commited_burst,
+ excess_burst,
+ rate_type=0,
+ round_type=0,
+ type=0,
+ color_aware=False,
+ conform_action=PolicerAction(1, 0),
+ exceed_action=PolicerAction(0, 0),
+ violate_action=PolicerAction(0, 0),
+ ):
self._test = test
self.name = name
self.cir = cir
@@ -48,13 +59,19 @@ class VppPolicer(VppObject):
def add_vpp_config(self):
r = self._test.vapi.policer_add_del(
- name=self.name, cir=self.cir,
- eir=self.eir, cb=self.commited_burst, eb=self.excess_burst,
- rate_type=self.rate_type, round_type=self.round_type,
- type=self.type, color_aware=self.color_aware,
+ name=self.name,
+ cir=self.cir,
+ eir=self.eir,
+ cb=self.commited_burst,
+ eb=self.excess_burst,
+ rate_type=self.rate_type,
+ round_type=self.round_type,
+ type=self.type,
+ color_aware=self.color_aware,
conform_action=self.conform_action.encode(),
exceed_action=self.exceed_action.encode(),
- violate_action=self.violate_action.encode())
+ violate_action=self.violate_action.encode(),
+ )
self._test.registry.register(self, self._test.logger)
self._policer_index = r.policer_index
return self
@@ -64,27 +81,29 @@ class VppPolicer(VppObject):
self._policer_index = INVALID_INDEX
def bind_vpp_config(self, worker, bind):
- self._test.vapi.policer_bind(name=self.name, worker_index=worker,
- bind_enable=bind)
+ self._test.vapi.policer_bind(
+ name=self.name, worker_index=worker, bind_enable=bind
+ )
def apply_vpp_config(self, if_index, dir: Dir, apply):
if dir == Dir.RX:
self._test.vapi.policer_input(
- name=self.name, sw_if_index=if_index, apply=apply)
+ name=self.name, sw_if_index=if_index, apply=apply
+ )
else:
self._test.vapi.policer_output(
- name=self.name, sw_if_index=if_index, apply=apply)
+ name=self.name, sw_if_index=if_index, apply=apply
+ )
def query_vpp_config(self):
- dump = self._test.vapi.policer_dump(
- match_name_valid=True, match_name=self.name)
+ dump = self._test.vapi.policer_dump(match_name_valid=True, match_name=self.name)
for policer in dump:
if policer.name == self.name:
return True
return False
def object_id(self):
- return ("policer-%s" % (self.name))
+ return "policer-%s" % (self.name)
def get_stats(self, worker=None):
conform = self._test.statistics.get_counter("/net/policer/conform")
@@ -95,14 +114,14 @@ class VppPolicer(VppObject):
total = {}
for name, c in counters.items():
- total[f'{name}_packets'] = 0
- total[f'{name}_bytes'] = 0
+ total[f"{name}_packets"] = 0
+ total[f"{name}_bytes"] = 0
for i in range(len(c)):
t = c[i]
if worker is not None and i != worker + 1:
continue
stat_index = self._policer_index
- total[f'{name}_packets'] += t[stat_index]['packets']
- total[f'{name}_bytes'] += t[stat_index]['bytes']
+ total[f"{name}_packets"] += t[stat_index]["packets"]
+ total[f"{name}_bytes"] += t[stat_index]["bytes"]
return total
diff --git a/test/vpp_pppoe_interface.py b/test/vpp_pppoe_interface.py
index 505ac4c6425..0d5516eab60 100644
--- a/test/vpp_pppoe_interface.py
+++ b/test/vpp_pppoe_interface.py
@@ -1,4 +1,3 @@
-
from vpp_interface import VppInterface
import socket
from vpp_papi import mac_pton
@@ -9,9 +8,8 @@ class VppPppoeInterface(VppInterface):
VPP Pppoe interface
"""
- def __init__(self, test, client_ip, client_mac,
- session_id, decap_vrf_id=0):
- """ Create VPP PPPoE4 interface """
+ def __init__(self, test, client_ip, client_mac, session_id, decap_vrf_id=0):
+ """Create VPP PPPoE4 interface"""
super(VppPppoeInterface, self).__init__(test)
self.client_ip = client_ip
self.client_mac = client_mac
@@ -21,9 +19,11 @@ class VppPppoeInterface(VppInterface):
def add_vpp_config(self):
r = self.test.vapi.pppoe_add_del_session(
- self.client_ip, self.client_mac,
- session_id=self.session_id,
- decap_vrf_id=self.decap_vrf_id)
+ self.client_ip,
+ self.client_mac,
+ session_id=self.session_id,
+ decap_vrf_id=self.decap_vrf_id,
+ )
self.set_sw_if_index(r.sw_if_index)
self.vpp_sw_if_index = r.sw_if_index
self.generate_remote_hosts()
@@ -31,12 +31,12 @@ class VppPppoeInterface(VppInterface):
def remove_vpp_config(self):
self.unconfig()
self.test.vapi.pppoe_add_del_session(
- self.client_ip, self.client_mac,
- session_id=self.session_id,
- decap_vrf_id=self.decap_vrf_id,
- is_add=0)
+ self.client_ip,
+ self.client_mac,
+ session_id=self.session_id,
+ decap_vrf_id=self.decap_vrf_id,
+ is_add=0,
+ )
def set_unnumbered(self, swif_iface):
- self.test.vapi.sw_interface_set_unnumbered(
- swif_iface,
- self.vpp_sw_if_index)
+ self.test.vapi.sw_interface_set_unnumbered(swif_iface, self.vpp_sw_if_index)
diff --git a/test/vpp_qos.py b/test/vpp_qos.py
index a7fa9e748aa..a7374d1b1d8 100644
--- a/test/vpp_qos.py
+++ b/test/vpp_qos.py
@@ -8,7 +8,7 @@ from vpp_object import VppObject
class VppQosRecord(VppObject):
- """ QoS Record(ing) configuration """
+ """QoS Record(ing) configuration"""
def __init__(self, test, intf, source):
self._test = test
@@ -18,32 +18,34 @@ class VppQosRecord(VppObject):
def add_vpp_config(self):
self._test.vapi.qos_record_enable_disable(
enable=1,
- record={'sw_if_index': self.intf.sw_if_index,
- 'input_source': self.source})
+ record={"sw_if_index": self.intf.sw_if_index, "input_source": self.source},
+ )
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
self._test.vapi.qos_record_enable_disable(
enable=0,
- record={'sw_if_index': self.intf.sw_if_index,
- 'input_source': self.source})
+ record={"sw_if_index": self.intf.sw_if_index, "input_source": self.source},
+ )
def query_vpp_config(self):
rs = self._test.vapi.qos_record_dump()
for r in rs:
- if self.intf.sw_if_index == r.record.sw_if_index and \
- self.source == r.record.input_source:
+ if (
+ self.intf.sw_if_index == r.record.sw_if_index
+ and self.source == r.record.input_source
+ ):
return True
return False
def object_id(self):
- return ("qos-record-%s-%d" % (self.intf, self.source))
+ return "qos-record-%s-%d" % (self.intf, self.source)
class VppQosStore(VppObject):
- """ QoS Store(ing) configuration """
+ """QoS Store(ing) configuration"""
def __init__(self, test, intf, source, value):
self._test = test
@@ -54,34 +56,39 @@ class VppQosStore(VppObject):
def add_vpp_config(self):
self._test.vapi.qos_store_enable_disable(
enable=1,
- store={'sw_if_index': self.intf.sw_if_index,
- 'input_source': self.source,
- 'value': self.value})
+ store={
+ "sw_if_index": self.intf.sw_if_index,
+ "input_source": self.source,
+ "value": self.value,
+ },
+ )
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
self._test.vapi.qos_store_enable_disable(
enable=0,
- store={'sw_if_index': self.intf.sw_if_index,
- 'input_source': self.source})
+ store={"sw_if_index": self.intf.sw_if_index, "input_source": self.source},
+ )
def query_vpp_config(self):
rs = self._test.vapi.qos_store_dump()
for r in rs:
- if self.intf.sw_if_index == r.store.sw_if_index and \
- self.source == r.store.input_source and \
- self.value == r.store.value:
+ if (
+ self.intf.sw_if_index == r.store.sw_if_index
+ and self.source == r.store.input_source
+ and self.value == r.store.value
+ ):
return True
return False
def object_id(self):
- return ("qos-store-%s-%d" % (self.intf, self.source))
+ return "qos-store-%s-%d" % (self.intf, self.source)
class VppQosEgressMap(VppObject):
- """ QoS Egress Map(ping) configuration """
+ """QoS Egress Map(ping) configuration"""
def __init__(self, test, id, rows):
self._test = test
@@ -89,9 +96,7 @@ class VppQosEgressMap(VppObject):
self.rows = rows
def add_vpp_config(self):
- self._test.vapi.qos_egress_map_update(
- map={'id': self.id,
- 'rows': self.rows})
+ self._test.vapi.qos_egress_map_update(map={"id": self.id, "rows": self.rows})
self._test.registry.register(self, self._test.logger)
return self
@@ -107,11 +112,11 @@ class VppQosEgressMap(VppObject):
return False
def object_id(self):
- return ("qos-map-%d" % (self.id))
+ return "qos-map-%d" % (self.id)
class VppQosMark(VppObject):
- """ QoS Mark(ing) configuration """
+ """QoS Mark(ing) configuration"""
def __init__(self, test, intf, map, source):
self._test = test
@@ -122,27 +127,32 @@ class VppQosMark(VppObject):
def add_vpp_config(self):
self._test.vapi.qos_mark_enable_disable(
enable=1,
- mark={'sw_if_index': self.intf.sw_if_index,
- 'map_id': self.map.id,
- 'output_source': self.source})
+ mark={
+ "sw_if_index": self.intf.sw_if_index,
+ "map_id": self.map.id,
+ "output_source": self.source,
+ },
+ )
self._test.registry.register(self, self._test.logger)
return self
def remove_vpp_config(self):
self._test.vapi.qos_mark_enable_disable(
enable=0,
- mark={'sw_if_index': self.intf.sw_if_index,
- 'output_source': self.source})
+ mark={"sw_if_index": self.intf.sw_if_index, "output_source": self.source},
+ )
def query_vpp_config(self):
ms = self._test.vapi.qos_mark_dump()
for m in ms:
- if self.intf.sw_if_index == m.mark.sw_if_index and \
- self.source == m.mark.output_source and \
- self.map.id == m.mark.map_id:
+ if (
+ self.intf.sw_if_index == m.mark.sw_if_index
+ and self.source == m.mark.output_source
+ and self.map.id == m.mark.map_id
+ ):
return True
return False
def object_id(self):
- return ("qos-mark-%s-%d" % (self.intf, self.source))
+ return "qos-mark-%s-%d" % (self.intf, self.source)
diff --git a/test/vpp_srv6.py b/test/vpp_srv6.py
index d6efedc9f3e..d789105d7a7 100644
--- a/test/vpp_srv6.py
+++ b/test/vpp_srv6.py
@@ -8,12 +8,12 @@ from vpp_object import VppObject
from socket import inet_pton, inet_ntop, AF_INET, AF_INET6
-class SRv6LocalSIDBehaviors():
+class SRv6LocalSIDBehaviors:
# from src/vnet/srv6/sr.h
SR_BEHAVIOR_END = 1
SR_BEHAVIOR_X = 2
SR_BEHAVIOR_T = 3
- SR_BEHAVIOR_D_FIRST = 4 # Unused. Separator in between regular and D
+ SR_BEHAVIOR_D_FIRST = 4 # Unused. Separator in between regular and D
SR_BEHAVIOR_DX2 = 5
SR_BEHAVIOR_DX6 = 6
SR_BEHAVIOR_DX4 = 7
@@ -21,16 +21,16 @@ class SRv6LocalSIDBehaviors():
SR_BEHAVIOR_DT4 = 9
SR_BEHAVIOR_END_UN_PERF = 10
SR_BEHAVIOR_END_UN = 11
- SR_BEHAVIOR_LAST = 12 # Must always be the last one
+ SR_BEHAVIOR_LAST = 12 # Must always be the last one
-class SRv6PolicyType():
+class SRv6PolicyType:
# from src/vnet/srv6/sr.h
SR_POLICY_TYPE_DEFAULT = 0
SR_POLICY_TYPE_SPRAY = 1
-class SRv6PolicySteeringTypes():
+class SRv6PolicySteeringTypes:
# from src/vnet/srv6/sr.h
SR_STEER_L2 = 2
SR_STEER_IPV4 = 4
@@ -42,8 +42,17 @@ class VppSRv6LocalSID(VppObject):
SRv6 LocalSID
"""
- def __init__(self, test, localsid, behavior, nh_addr,
- end_psp, sw_if_index, vlan_index, fib_table):
+ def __init__(
+ self,
+ test,
+ localsid,
+ behavior,
+ nh_addr,
+ end_psp,
+ sw_if_index,
+ vlan_index,
+ fib_table,
+ ):
self._test = test
self.localsid = localsid
self.behavior = behavior
@@ -63,7 +72,8 @@ class VppSRv6LocalSID(VppObject):
end_psp=self.end_psp,
sw_if_index=self.sw_if_index,
vlan_index=self.vlan_index,
- fib_table=self.fib_table)
+ fib_table=self.fib_table,
+ )
self._configured = True
def remove_vpp_config(self):
@@ -75,7 +85,8 @@ class VppSRv6LocalSID(VppObject):
end_psp=self.end_psp,
sw_if_index=self.sw_if_index,
vlan_index=self.vlan_index,
- fib_table=self.fib_table)
+ fib_table=self.fib_table,
+ )
self._configured = False
def query_vpp_config(self):
@@ -84,10 +95,7 @@ class VppSRv6LocalSID(VppObject):
return self._configured
def object_id(self):
- return ("%d;%s,%d"
- % (self.fib_table,
- self.localsid,
- self.behavior))
+ return "%d;%s,%d" % (self.fib_table, self.localsid, self.behavior)
class VppSRv6Policy(VppObject):
@@ -95,9 +103,9 @@ class VppSRv6Policy(VppObject):
SRv6 Policy
"""
- def __init__(self, test, bsid,
- is_encap, sr_type, weight, fib_table,
- segments, source):
+ def __init__(
+ self, test, bsid, is_encap, sr_type, weight, fib_table, segments, source
+ ):
self._test = test
self.bsid = bsid
self.is_encap = is_encap
@@ -113,17 +121,17 @@ class VppSRv6Policy(VppObject):
def add_vpp_config(self):
self._test.vapi.sr_policy_add(
- bsid=self.bsid,
- weight=self.weight,
- is_encap=self.is_encap,
- is_spray=self.sr_type,
- fib_table=self.fib_table,
- sids={'num_sids': self.n_segments, 'sids': self.segments})
+ bsid=self.bsid,
+ weight=self.weight,
+ is_encap=self.is_encap,
+ is_spray=self.sr_type,
+ fib_table=self.fib_table,
+ sids={"num_sids": self.n_segments, "sids": self.segments},
+ )
self._configured = True
def remove_vpp_config(self):
- self._test.vapi.sr_policy_del(
- self.bsid)
+ self._test.vapi.sr_policy_del(self.bsid)
self._configured = False
def query_vpp_config(self):
@@ -132,11 +140,12 @@ class VppSRv6Policy(VppObject):
return self._configured
def object_id(self):
- return ("%d;%s-><%s>;%d"
- % (self.sr_type,
- self.bsid,
- ','.join(self.segments),
- self.is_encap))
+ return "%d;%s-><%s>;%d" % (
+ self.sr_type,
+ self.bsid,
+ ",".join(self.segments),
+ self.is_encap,
+ )
class VppSRv6Steering(VppObject):
@@ -144,14 +153,17 @@ class VppSRv6Steering(VppObject):
SRv6 Steering
"""
- def __init__(self, test,
- bsid,
- prefix,
- mask_width,
- traffic_type,
- sr_policy_index,
- table_id,
- sw_if_index):
+ def __init__(
+ self,
+ test,
+ bsid,
+ prefix,
+ mask_width,
+ traffic_type,
+ sr_policy_index,
+ table_id,
+ sw_if_index,
+ ):
self._test = test
self.bsid = bsid
self.prefix = prefix
@@ -164,24 +176,26 @@ class VppSRv6Steering(VppObject):
def add_vpp_config(self):
self._test.vapi.sr_steering_add_del(
- is_del=0,
- bsid=self.bsid,
- sr_policy_index=self.sr_policy_index,
- table_id=self.table_id,
- prefix={'address': self.prefix, 'len': self.mask_width},
- sw_if_index=self.sw_if_index,
- traffic_type=self.traffic_type)
+ is_del=0,
+ bsid=self.bsid,
+ sr_policy_index=self.sr_policy_index,
+ table_id=self.table_id,
+ prefix={"address": self.prefix, "len": self.mask_width},
+ sw_if_index=self.sw_if_index,
+ traffic_type=self.traffic_type,
+ )
self._configured = True
def remove_vpp_config(self):
self._test.vapi.sr_steering_add_del(
- is_del=1,
- bsid=self.bsid,
- sr_policy_index=self.sr_policy_index,
- table_id=self.table_id,
- prefix={'address': self.prefix, 'len': self.mask_width},
- sw_if_index=self.sw_if_index,
- traffic_type=self.traffic_type)
+ is_del=1,
+ bsid=self.bsid,
+ sr_policy_index=self.sr_policy_index,
+ table_id=self.table_id,
+ prefix={"address": self.prefix, "len": self.mask_width},
+ sw_if_index=self.sw_if_index,
+ traffic_type=self.traffic_type,
+ )
self._configured = False
def query_vpp_config(self):
@@ -190,9 +204,10 @@ class VppSRv6Steering(VppObject):
return self._configured
def object_id(self):
- return ("%d;%d;%s/%d->%s"
- % (self.table_id,
- self.traffic_type,
- self.prefix,
- self.mask_width,
- self.bsid))
+ return "%d;%d;%s/%d->%s" % (
+ self.table_id,
+ self.traffic_type,
+ self.prefix,
+ self.mask_width,
+ self.bsid,
+ )
diff --git a/test/vpp_sub_interface.py b/test/vpp_sub_interface.py
index 21560cb99d0..b896a6efbe3 100644
--- a/test/vpp_sub_interface.py
+++ b/test/vpp_sub_interface.py
@@ -18,7 +18,6 @@ class L2_VTR_OP:
class VppSubInterface(VppPGInterface, metaclass=abc.ABCMeta):
-
@property
def parent(self):
"""Parent interface for this sub-interface"""
@@ -117,26 +116,33 @@ class VppSubInterface(VppPGInterface, metaclass=abc.ABCMeta):
self._tag2 = 0
self._push1q = 0
- if (vtr == L2_VTR_OP.L2_PUSH_1 or
- vtr == L2_VTR_OP.L2_TRANSLATE_1_1 or
- vtr == L2_VTR_OP.L2_TRANSLATE_2_1):
+ if (
+ vtr == L2_VTR_OP.L2_PUSH_1
+ or vtr == L2_VTR_OP.L2_TRANSLATE_1_1
+ or vtr == L2_VTR_OP.L2_TRANSLATE_2_1
+ ):
self._tag1 = tag
self._push1q = push1q
- if (vtr == L2_VTR_OP.L2_PUSH_2 or
- vtr == L2_VTR_OP.L2_TRANSLATE_1_2 or
- vtr == L2_VTR_OP.L2_TRANSLATE_2_2):
+ if (
+ vtr == L2_VTR_OP.L2_PUSH_2
+ or vtr == L2_VTR_OP.L2_TRANSLATE_1_2
+ or vtr == L2_VTR_OP.L2_TRANSLATE_2_2
+ ):
self._tag1 = outer
self._tag2 = inner
self._push1q = push1q
self.test.vapi.l2_interface_vlan_tag_rewrite(
- sw_if_index=self.sw_if_index, vtr_op=vtr, push_dot1q=self._push1q,
- tag1=self._tag1, tag2=self._tag2)
+ sw_if_index=self.sw_if_index,
+ vtr_op=vtr,
+ push_dot1q=self._push1q,
+ tag1=self._tag1,
+ tag2=self._tag2,
+ )
self._vtr = vtr
class VppDot1QSubint(VppSubInterface):
-
@property
def vlan(self):
"""VLAN tag"""
@@ -168,7 +174,6 @@ class VppDot1QSubint(VppSubInterface):
class VppDot1ADSubint(VppSubInterface):
-
@property
def outer_vlan(self):
"""Outer VLAN tag"""
@@ -181,13 +186,18 @@ class VppDot1ADSubint(VppSubInterface):
def __init__(self, test, parent, sub_id, outer_vlan, inner_vlan):
super(VppDot1ADSubint, self).__init__(test, parent, sub_id)
- flags = (VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_DOT1AD |
- VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_TWO_TAGS |
- VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_EXACT_MATCH)
- r = test.vapi.create_subif(sw_if_index=parent.sw_if_index,
- sub_id=sub_id, outer_vlan_id=outer_vlan,
- inner_vlan_id=inner_vlan,
- sub_if_flags=flags)
+ flags = (
+ VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_DOT1AD
+ | VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_TWO_TAGS
+ | VppEnum.vl_api_sub_if_flags_t.SUB_IF_API_FLAG_EXACT_MATCH
+ )
+ r = test.vapi.create_subif(
+ sw_if_index=parent.sw_if_index,
+ sub_id=sub_id,
+ outer_vlan_id=outer_vlan,
+ inner_vlan_id=inner_vlan,
+ sub_if_flags=flags,
+ )
self.set_sw_if_index(r.sw_if_index)
self._outer_vlan = outer_vlan
self._inner_vlan = inner_vlan
@@ -204,16 +214,13 @@ class VppDot1ADSubint(VppSubInterface):
return self.add_dot1ad_layer(packet, self.outer_vlan, self.inner_vlan)
def remove_dot1_layer(self, packet):
- return self.remove_dot1ad_layer(packet, self.outer_vlan,
- self.inner_vlan)
+ return self.remove_dot1ad_layer(packet, self.outer_vlan, self.inner_vlan)
class VppP2PSubint(VppSubInterface):
-
def __init__(self, test, parent, sub_id, remote_mac):
super(VppP2PSubint, self).__init__(test, parent, sub_id)
- r = test.vapi.p2p_ethernet_add(parent.sw_if_index,
- remote_mac, sub_id)
+ r = test.vapi.p2p_ethernet_add(parent.sw_if_index, remote_mac, sub_id)
self.set_sw_if_index(r.sw_if_index)
self.parent_sw_if_index = parent.sw_if_index
self.p2p_remote_mac = remote_mac
diff --git a/test/vpp_teib.py b/test/vpp_teib.py
index ee2d89fe080..14688181582 100644
--- a/test/vpp_teib.py
+++ b/test/vpp_teib.py
@@ -9,14 +9,12 @@ from vpp_object import VppObject
def find_teib(test, ne):
ns = test.vapi.teib_dump()
for n in ns:
- if ne.peer == str(n.entry.peer) \
- and ne.itf._sw_if_index == n.entry.sw_if_index:
+ if ne.peer == str(n.entry.peer) and ne.itf._sw_if_index == n.entry.sw_if_index:
return True
return False
class VppTeib(VppObject):
-
def __init__(self, test, itf, peer, nh, table_id=0):
self._test = test
self.table_id = table_id
@@ -28,11 +26,12 @@ class VppTeib(VppObject):
r = self._test.vapi.teib_entry_add_del(
is_add=1,
entry={
- 'nh_table_id': self.table_id,
- 'sw_if_index': self.itf.sw_if_index,
- 'peer': self.peer,
- 'nh': self.nh,
- })
+ "nh_table_id": self.table_id,
+ "sw_if_index": self.itf.sw_if_index,
+ "peer": self.peer,
+ "nh": self.nh,
+ },
+ )
self._test.registry.register(self, self._test.logger)
return self
@@ -40,13 +39,14 @@ class VppTeib(VppObject):
r = self._test.vapi.teib_entry_add_del(
is_add=0,
entry={
- 'nh_table_id': self.table_id,
- 'sw_if_index': self.itf.sw_if_index,
- 'peer': self.peer,
- })
+ "nh_table_id": self.table_id,
+ "sw_if_index": self.itf.sw_if_index,
+ "peer": self.peer,
+ },
+ )
def query_vpp_config(self):
return find_teib(self._test, self)
def object_id(self):
- return ("teib-%s-%s" % (self.itf, self.peer))
+ return "teib-%s-%s" % (self.itf, self.peer)
diff --git a/test/vpp_tunnel_interface.py b/test/vpp_tunnel_interface.py
index 6a336eb72d9..d70328eb239 100644
--- a/test/vpp_tunnel_interface.py
+++ b/test/vpp_tunnel_interface.py
@@ -4,7 +4,7 @@ from vpp_interface import VppInterface
class VppTunnelInterface(VppInterface, metaclass=abc.ABCMeta):
- """ VPP tunnel interface abstraction """
+ """VPP tunnel interface abstraction"""
def __init__(self, test, parent_if):
super(VppTunnelInterface, self).__init__(test)
@@ -24,7 +24,9 @@ class VppTunnelInterface(VppInterface, metaclass=abc.ABCMeta):
def add_stream(self, pkts):
return self.parent_if.add_stream(pkts)
- def get_capture(self, expected_count=None, remark=None, timeout=1,
- filter_out_fn=is_ipv6_misc):
- return self.parent_if.get_capture(expected_count, remark, timeout,
- filter_out_fn)
+ def get_capture(
+ self, expected_count=None, remark=None, timeout=1, filter_out_fn=is_ipv6_misc
+ ):
+ return self.parent_if.get_capture(
+ expected_count, remark, timeout, filter_out_fn
+ )
diff --git a/test/vpp_udp_decap.py b/test/vpp_udp_decap.py
index 2bd03ce75c0..3231826f31b 100644
--- a/test/vpp_udp_decap.py
+++ b/test/vpp_udp_decap.py
@@ -8,19 +8,10 @@ from socket import inet_pton, inet_ntop, AF_INET, AF_INET6
class VppUdpDecap(VppObject):
-
- def __init__(self,
- test,
- is_ip4,
- dst_port,
- next_proto):
+ def __init__(self, test, is_ip4, dst_port, next_proto):
self._test = test
self.active = False
- self.udp_decap = {
- 'is_ip4': is_ip4,
- 'port': dst_port,
- 'next_proto': next_proto
- }
+ self.udp_decap = {"is_ip4": is_ip4, "port": dst_port, "next_proto": next_proto}
def add_vpp_config(self):
self._test.vapi.udp_decap_add_del(True, self.udp_decap)
diff --git a/test/vpp_udp_encap.py b/test/vpp_udp_encap.py
index aad87bd5912..b89e9411e6a 100644
--- a/test/vpp_udp_encap.py
+++ b/test/vpp_udp_encap.py
@@ -10,25 +10,20 @@ from socket import inet_pton, inet_ntop, AF_INET, AF_INET6
def find_udp_encap(test, ue):
encaps = test.vapi.udp_encap_dump()
for e in encaps:
- if ue.id == e.udp_encap.id \
- and ue.src_ip == str(e.udp_encap.src_ip) \
- and ue.dst_ip == str(e.udp_encap.dst_ip) \
- and e.udp_encap.dst_port == ue.dst_port \
- and e.udp_encap.src_port == ue.src_port:
+ if (
+ ue.id == e.udp_encap.id
+ and ue.src_ip == str(e.udp_encap.src_ip)
+ and ue.dst_ip == str(e.udp_encap.dst_ip)
+ and e.udp_encap.dst_port == ue.dst_port
+ and e.udp_encap.src_port == ue.src_port
+ ):
return True
return False
class VppUdpEncap(VppObject):
-
- def __init__(self,
- test,
- src_ip,
- dst_ip,
- src_port,
- dst_port,
- table_id=0):
+ def __init__(self, test, src_ip, dst_ip, src_port, dst_port, table_id=0):
self._test = test
self.table_id = table_id
self.src_ip_s = src_ip
@@ -40,11 +35,8 @@ class VppUdpEncap(VppObject):
def add_vpp_config(self):
r = self._test.vapi.udp_encap_add(
- self.src_ip,
- self.dst_ip,
- self.src_port,
- self.dst_port,
- self.table_id)
+ self.src_ip, self.dst_ip, self.src_port, self.dst_port, self.table_id
+ )
self.id = r.id
self._test.registry.register(self, self._test.logger)
@@ -55,7 +47,7 @@ class VppUdpEncap(VppObject):
return find_udp_encap(self._test, self)
def object_id(self):
- return ("udp-encap-%d" % self.id)
+ return "udp-encap-%d" % self.id
def get_stats(self):
c = self._test.statistics.get_counter("/net/udp-encap")
diff --git a/test/vpp_vhost_interface.py b/test/vpp_vhost_interface.py
index 8fa2d7172f1..a20504ba1ce 100644
--- a/test/vpp_vhost_interface.py
+++ b/test/vpp_vhost_interface.py
@@ -4,13 +4,24 @@ from vpp_interface import VppInterface
class VppVhostInterface(VppInterface):
"""VPP vhost interface."""
- def __init__(self, test, sock_filename, is_server=0, renumber=0,
- disable_mrg_rxbuf=0, disable_indirect_desc=0, enable_gso=0,
- enable_packed_ring=0, enable_event_idx=0,
- custom_dev_instance=0xFFFFFFFF, use_custom_mac=0,
- mac_address='', tag=''):
+ def __init__(
+ self,
+ test,
+ sock_filename,
+ is_server=0,
+ renumber=0,
+ disable_mrg_rxbuf=0,
+ disable_indirect_desc=0,
+ enable_gso=0,
+ enable_packed_ring=0,
+ enable_event_idx=0,
+ custom_dev_instance=0xFFFFFFFF,
+ use_custom_mac=0,
+ mac_address="",
+ tag="",
+ ):
- """ Create VPP Vhost interface """
+ """Create VPP Vhost interface"""
super(VppVhostInterface, self).__init__(test)
self.is_server = is_server
self.sock_filename = sock_filename
@@ -26,18 +37,20 @@ class VppVhostInterface(VppInterface):
self.tag = tag
def add_vpp_config(self):
- r = self.test.vapi.create_vhost_user_if_v2(self.is_server,
- self.sock_filename,
- self.renumber,
- self.disable_mrg_rxbuf,
- self.disable_indirect_desc,
- self.enable_gso,
- self.enable_packed_ring,
- self.enable_event_idx,
- self.custom_dev_instance,
- self.use_custom_mac,
- self.mac_address,
- self.tag)
+ r = self.test.vapi.create_vhost_user_if_v2(
+ self.is_server,
+ self.sock_filename,
+ self.renumber,
+ self.disable_mrg_rxbuf,
+ self.disable_indirect_desc,
+ self.enable_gso,
+ self.enable_packed_ring,
+ self.enable_event_idx,
+ self.custom_dev_instance,
+ self.use_custom_mac,
+ self.mac_address,
+ self.tag,
+ )
self.set_sw_if_index(r.sw_if_index)
def remove_vpp_config(self):
diff --git a/test/vpp_vxlan_gpe_tunnel.py b/test/vpp_vxlan_gpe_tunnel.py
index cff5e456aee..2826c29c6b3 100644
--- a/test/vpp_vxlan_gpe_tunnel.py
+++ b/test/vpp_vxlan_gpe_tunnel.py
@@ -2,7 +2,7 @@ from vpp_interface import VppInterface
from vpp_papi import VppEnum
-INDEX_INVALID = 0xffffffff
+INDEX_INVALID = 0xFFFFFFFF
DEFAULT_PORT = 4790
UNDEFINED_PORT = 0
@@ -19,11 +19,13 @@ def find_vxlan_gpe_tunnel(test, src, dst, s_port, d_port, vni):
dst_port = d_port
for t in ts:
- if src == str(t.local) and \
- dst == str(t.remote) and \
- src_port == t.local_port and \
- dst_port == t.remote_port and \
- t.vni == vni:
+ if (
+ src == str(t.local)
+ and dst == str(t.remote)
+ and src_port == t.local_port
+ and dst_port == t.remote_port
+ and t.vni == vni
+ ):
return t.sw_if_index
return INDEX_INVALID
@@ -33,12 +35,20 @@ class VppVxlanGpeTunnel(VppInterface):
VPP VXLAN GPE interface
"""
- def __init__(self, test, src_addr, dst_addr, vni,
- src_port=UNDEFINED_PORT, dst_port=UNDEFINED_PORT,
- mcast_sw_if_index=INDEX_INVALID,
- encap_vrf_id=None,
- decap_vrf_id=None, protocol=3):
- """ Create VXLAN GPE Tunnel interface """
+ def __init__(
+ self,
+ test,
+ src_addr,
+ dst_addr,
+ vni,
+ src_port=UNDEFINED_PORT,
+ dst_port=UNDEFINED_PORT,
+ mcast_sw_if_index=INDEX_INVALID,
+ encap_vrf_id=None,
+ decap_vrf_id=None,
+ protocol=3,
+ ):
+ """Create VXLAN GPE Tunnel interface"""
super(VppVxlanGpeTunnel, self).__init__(test)
self.src = src_addr
self.dst = dst_addr
@@ -52,32 +62,38 @@ class VppVxlanGpeTunnel(VppInterface):
def add_vpp_config(self):
reply = self.test.vapi.vxlan_gpe_add_del_tunnel_v2(
- is_add=1, local=self.src, remote=self.dst, vni=self.vni,
- local_port=self.src_port, remote_port=self.dst_port,
+ is_add=1,
+ local=self.src,
+ remote=self.dst,
+ vni=self.vni,
+ local_port=self.src_port,
+ remote_port=self.dst_port,
mcast_sw_if_index=self.mcast_sw_if_index,
encap_vrf_id=self.encap_vrf_id,
decap_vrf_id=self.decap_vrf_id,
- protocol=self.protocol)
+ protocol=self.protocol,
+ )
self.set_sw_if_index(reply.sw_if_index)
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
self.test.vapi.vxlan_gpe_add_del_tunnel_v2(
- is_add=0, local=self.src, remote=self.dst, vni=self.vni,
- local_port=self.src_port, remote_port=self.dst_port,
+ is_add=0,
+ local=self.src,
+ remote=self.dst,
+ vni=self.vni,
+ local_port=self.src_port,
+ remote_port=self.dst_port,
mcast_sw_if_index=self.mcast_sw_if_index,
encap_vrf_id=self.encap_vrf_id,
decap_vrf_id=self.decap_vrf_id,
- protocol=self.protocol)
+ protocol=self.protocol,
+ )
def query_vpp_config(self):
- return (INDEX_INVALID != find_vxlan_gpe_tunnel(self._test,
- self.src,
- self.dst,
- self.src_port,
- self.dst_port,
- self.vni))
+ return INDEX_INVALID != find_vxlan_gpe_tunnel(
+ self._test, self.src, self.dst, self.src_port, self.dst_port, self.vni
+ )
def object_id(self):
- return "vxlan-%d-%d-%s-%s" % (self.sw_if_index, self.vni,
- self.src, self.dst)
+ return "vxlan-%d-%d-%s-%s" % (self.sw_if_index, self.vni, self.src, self.dst)
diff --git a/test/vpp_vxlan_tunnel.py b/test/vpp_vxlan_tunnel.py
index d7e087da6f8..8c993b09196 100644
--- a/test/vpp_vxlan_tunnel.py
+++ b/test/vpp_vxlan_tunnel.py
@@ -2,7 +2,7 @@ from vpp_interface import VppInterface
from vpp_papi import VppEnum
-INDEX_INVALID = 0xffffffff
+INDEX_INVALID = 0xFFFFFFFF
DEFAULT_PORT = 4789
UNDEFINED_PORT = 0
@@ -19,11 +19,13 @@ def find_vxlan_tunnel(test, src, dst, s_port, d_port, vni):
dst_port = d_port
for t in ts:
- if src == str(t.src_address) and \
- dst == str(t.dst_address) and \
- src_port == t.src_port and \
- dst_port == t.dst_port and \
- t.vni == vni:
+ if (
+ src == str(t.src_address)
+ and dst == str(t.dst_address)
+ and src_port == t.src_port
+ and dst_port == t.dst_port
+ and t.vni == vni
+ ):
return t.sw_if_index
return INDEX_INVALID
@@ -33,13 +35,22 @@ class VppVxlanTunnel(VppInterface):
VPP VXLAN interface
"""
- def __init__(self, test, src, dst, vni,
- src_port=UNDEFINED_PORT, dst_port=UNDEFINED_PORT,
- mcast_itf=None,
- mcast_sw_if_index=INDEX_INVALID,
- decap_next_index=INDEX_INVALID,
- encap_vrf_id=None, instance=0xffffffff, is_l3=False):
- """ Create VXLAN Tunnel interface """
+ def __init__(
+ self,
+ test,
+ src,
+ dst,
+ vni,
+ src_port=UNDEFINED_PORT,
+ dst_port=UNDEFINED_PORT,
+ mcast_itf=None,
+ mcast_sw_if_index=INDEX_INVALID,
+ decap_next_index=INDEX_INVALID,
+ encap_vrf_id=None,
+ instance=0xFFFFFFFF,
+ is_l3=False,
+ ):
+ """Create VXLAN Tunnel interface"""
super(VppVxlanTunnel, self).__init__(test)
self.src = src
self.dst = dst
@@ -53,35 +64,44 @@ class VppVxlanTunnel(VppInterface):
self.instance = instance
self.is_l3 = is_l3
- if (self.mcast_itf):
+ if self.mcast_itf:
self.mcast_sw_if_index = self.mcast_itf.sw_if_index
def add_vpp_config(self):
reply = self.test.vapi.vxlan_add_del_tunnel_v3(
- is_add=1, src_address=self.src, dst_address=self.dst, vni=self.vni,
- src_port=self.src_port, dst_port=self.dst_port,
+ is_add=1,
+ src_address=self.src,
+ dst_address=self.dst,
+ vni=self.vni,
+ src_port=self.src_port,
+ dst_port=self.dst_port,
mcast_sw_if_index=self.mcast_sw_if_index,
- encap_vrf_id=self.encap_vrf_id, is_l3=self.is_l3,
- instance=self.instance, decap_next_index=self.decap_next_index)
+ encap_vrf_id=self.encap_vrf_id,
+ is_l3=self.is_l3,
+ instance=self.instance,
+ decap_next_index=self.decap_next_index,
+ )
self.set_sw_if_index(reply.sw_if_index)
self._test.registry.register(self, self._test.logger)
def remove_vpp_config(self):
self.test.vapi.vxlan_add_del_tunnel_v2(
- is_add=0, src_address=self.src, dst_address=self.dst, vni=self.vni,
- src_port=self.src_port, dst_port=self.dst_port,
+ is_add=0,
+ src_address=self.src,
+ dst_address=self.dst,
+ vni=self.vni,
+ src_port=self.src_port,
+ dst_port=self.dst_port,
mcast_sw_if_index=self.mcast_sw_if_index,
- encap_vrf_id=self.encap_vrf_id, instance=self.instance,
- decap_next_index=self.decap_next_index)
+ encap_vrf_id=self.encap_vrf_id,
+ instance=self.instance,
+ decap_next_index=self.decap_next_index,
+ )
def query_vpp_config(self):
- return (INDEX_INVALID != find_vxlan_tunnel(self._test,
- self.src,
- self.dst,
- self.src_port,
- self.dst_port,
- self.vni))
+ return INDEX_INVALID != find_vxlan_tunnel(
+ self._test, self.src, self.dst, self.src_port, self.dst_port, self.vni
+ )
def object_id(self):
- return "vxlan-%d-%d-%s-%s" % (self.sw_if_index, self.vni,
- self.src, self.dst)
+ return "vxlan-%d-%d-%s-%s" % (self.sw_if_index, self.vni, self.src, self.dst)
diff --git a/test/vrf.py b/test/vrf.py
index b3daceed2c1..2db18c4824b 100644
--- a/test/vrf.py
+++ b/test/vrf.py
@@ -4,7 +4,8 @@ from util import NumericConstant
class VRFState(NumericConstant):
- """ VRF State """
+ """VRF State"""
+
not_configured = 0
configured = 1
reset = 2