aboutsummaryrefslogtreecommitdiffstats
path: root/src/vpp-api/python/vpp_papi/tests/test_vpp_format.py
blob: 5c179c02e0a3a0766d0ccd1dc18d498040c0f2a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#  Copyright (c) 2019. Vinci Consulting Corp. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import ipaddress
import socket
import unittest

try:
    text_type = unicode
except NameError:
    text_type = str

from vpp_papi import vpp_format

from parameterized import parameterized

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)
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'
ip6_prefix_len = 127
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}


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)):
            res = vpp_format.format_vl_api_address_t(ip4_addrn)

        res = vpp_format.format_vl_api_address_t(ip6_addr)
        self.assertEqual(res, ip6_addr_format_vl_api_address_t)

        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),
                           ])
    def test_format_vl_api_prefix_t(self, _, arg, expected):
        res = vpp_format.format_vl_api_prefix_t(arg)
        self.assertEqual(res, expected)

    def test_format_vl_api_ip6_prefix_t(self):
        res = vpp_format.format_vl_api_ip6_prefix_t(ip6_prefix)
        self.assertEqual(res, ip6_addr_format_vl_api_prefix_packed_t)

        res = vpp_format.format_vl_api_ip6_prefix_t(ipv6_network)
        self.assertEqual(res, ip6_addr_format_vl_api_prefix_packed_t)

    def test_format_vl_api_ip4_prefix_t(self):
        res = vpp_format.format_vl_api_ip4_prefix_t(ip4_prefix)
        self.assertEqual(res, ip4_addr_format_vl_api_prefix_packed_t)

        res = vpp_format.format_vl_api_ip4_prefix_t(ipv4_network)
        self.assertEqual(res, ip4_addr_format_vl_api_prefix_packed_t)

    def test_format_vl_api_ip6_prefix_t_raises(self):
        # PY2: raises socket.error
        # PY3: raises OSError
        with self.assertRaises((socket.error, OSError)):
            res = vpp_format.format_vl_api_ip6_prefix_t(ip4_prefix)

    def test_format_vl_api_ip4_prefix_t_raises(self):
        # PY2: raises socket.error
        # PY3: raises OSError
        with self.assertRaises((socket.error, OSError)):
            res = vpp_format.format_vl_api_ip4_prefix_t(ip6_prefix)
("Failed to attach thread\n"); rm->control_ping_retval = VNET_API_ERROR_FAILED_TO_ATTACH_TO_JAVA_THREAD; goto out; } // workaround as we can't use pthread_cleanup_push pthread_key_create(&rm->cleanup_rx_thread_key, cleanup_rx_thread); // destructor is only called if the value of key is non null pthread_setspecific(rm->cleanup_rx_thread_key, (void *) 1); was_thread_connected = 1; } else if (getEnvStat == JNI_EVERSION) { clib_warning("Unsupported JNI version\n"); rm->control_ping_retval = VNET_API_ERROR_UNSUPPORTED_JNI_VERSION; goto out; } if (was_thread_connected == 0) { JNIEnv *env = jm->jenv; if (mp->retval < 0) { call_on_error("controlPing", mp->context, mp->retval, rm->registryClass, rm->registryObject, rm->callbackExceptionClass); } else { jmethodID constructor = (*env)->GetMethodID(env, rm->controlPingReplyClass, "<init>", "()V"); jmethodID callbackMethod = (*env)->GetMethodID(env, rm->registryClass, "onControlPingReply", "(Lio/fd/vpp/jvpp/dto/ControlPingReply;)V"); jobject dto = (*env)->NewObject(env, rm->controlPingReplyClass, constructor); jfieldID contextFieldId = (*env)->GetFieldID(env, rm->controlPingReplyClass, "context", "I"); (*env)->SetIntField(env, dto, contextFieldId, clib_net_to_host_u32(mp->context)); jfieldID clientIndexFieldId = (*env)->GetFieldID(env, rm->controlPingReplyClass, "clientIndex", "I"); (*env)->SetIntField(env, dto, clientIndexFieldId, clib_net_to_host_u32(mp->client_index)); jfieldID vpePidFieldId = (*env)->GetFieldID(env, rm->controlPingReplyClass, "vpePid", "I"); (*env)->SetIntField(env, dto, vpePidFieldId, clib_net_to_host_u32(mp->vpe_pid)); (*env)->CallVoidMethod(env, rm->registryObject, callbackMethod, dto); } } out: rm->control_ping_result_ready = 1; } static int send_initial_control_ping() { f64 timeout; clib_time_t clib_time; vl_api_control_ping_t * mp; jvpp_main_t * jm = &jvpp_main; jvpp_registry_main_t * rm = &jvpp_registry_main; clib_time_init(&clib_time); rm->control_ping_result_ready = 0; mp = vl_msg_api_alloc(sizeof(*mp)); memset(mp, 0, sizeof(*mp)); mp->_vl_msg_id = ntohs(VL_API_CONTROL_PING); mp->client_index = jm->my_client_index; // send message: vl_msg_api_send_shmem(jm->vl_input_queue, (u8 *) &mp); // wait for results: Current time + 10 seconds is the timeout timeout = clib_time_now(&clib_time) + 10.0; int rv = VNET_API_ERROR_RESPONSE_NOT_READY; while (clib_time_now(&clib_time) < timeout) { if (rm->control_ping_result_ready == 1) { rv = rm->control_ping_retval; break; } } if (rv != 0) { clib_warning("common: first control ping failed: %d", rv); } return rv; } static int connect_to_vpe(char *name) { jvpp_main_t * jm = &jvpp_main; api_main_t * am = &api_main; if (vl_client_connect_to_vlib("/vpe-api", name, 32) < 0) return -1; jm->my_client_index = am->my_client_index; jm->vl_input_queue = am->shmem_hdr->vl_input_queue; vl_msg_api_set_handlers(VL_API_CONTROL_PING_REPLY, "control_ping_reply", vl_api_control_ping_reply_t_handler, vl_noop_handler, vl_api_control_ping_reply_t_endian, vl_api_control_ping_reply_t_print, sizeof(vl_api_control_ping_reply_t), 1); send_initial_control_ping(); return 0; } JNIEXPORT jobject JNICALL Java_io_fd_vpp_jvpp_VppJNIConnection_clientConnect( JNIEnv *env, jclass obj, jstring clientName) { int rv; const char *client_name; void vl_msg_reply_handler_hookup(void); jvpp_main_t * jm = &jvpp_main; jvpp_registry_main_t * rm = &jvpp_registry_main; jclass connectionInfoClass = (*env)->FindClass(env, "io/fd/vpp/jvpp/VppJNIConnection$ConnectionInfo"); jmethodID connectionInfoConstructor = (*env)->GetMethodID(env, connectionInfoClass, "<init>", "(JII)V"); /* * Bail out now if we're not running as root */ if (geteuid() != 0) { return (*env)->NewObject(env, connectionInfoClass, connectionInfoConstructor, 0, 0, VNET_API_ERROR_NOT_RUNNING_AS_ROOT); } if (rm->is_connected) { return (*env)->NewObject(env, connectionInfoClass, connectionInfoConstructor, 0, 0, VNET_API_ERROR_ALREADY_CONNECTED); } client_name = (*env)->GetStringUTFChars(env, clientName, 0); if (!client_name) { return (*env)->NewObject(env, connectionInfoClass, connectionInfoConstructor, 0, 0, VNET_API_ERROR_INVALID_VALUE); } rv = connect_to_vpe((char *) client_name); if (rv < 0) clib_warning("connection failed, rv %d", rv); (*env)->ReleaseStringUTFChars(env, clientName, client_name); return (*env)->NewObject(env, connectionInfoClass, connectionInfoConstructor, (jlong) jm->vl_input_queue, (jint) jm->my_client_index, (jint) rv); } JNIEXPORT jint JNICALL Java_io_fd_vpp_jvpp_JVppRegistryImpl_controlPing0( JNIEnv *env, jobject regstryObject) { jvpp_main_t * jm = &jvpp_main; vl_api_control_ping_t * mp; u32 my_context_id = vppjni_get_context_id(&jvpp_main); jvpp_registry_main_t * rm = &jvpp_registry_main; if (rm->registryObject == 0) { rm->registryObject = (*env)->NewGlobalRef(env, regstryObject); } if (rm->registryClass == 0) { rm->registryClass = (jclass) (*env)->NewGlobalRef(env, (*env)->GetObjectClass(env, regstryObject)); } mp = vl_msg_api_alloc(sizeof(*mp)); memset(mp, 0, sizeof(*mp)); mp->_vl_msg_id = ntohs(VL_API_CONTROL_PING); mp->client_index = jm->my_client_index; mp->context = clib_host_to_net_u32(my_context_id); // send message: vl_msg_api_send_shmem(jm->vl_input_queue, (u8 *) &mp); return my_context_id; } JNIEXPORT void JNICALL Java_io_fd_vpp_jvpp_VppJNIConnection_clientDisconnect( JNIEnv *env, jclass clazz) { jvpp_registry_main_t * rm = &jvpp_registry_main; rm->is_connected = 0; // TODO make thread safe vl_client_disconnect_from_vlib(); // cleanup: if (rm->registryObject) { (*env)->DeleteGlobalRef(env, rm->registryObject); rm->registryObject = 0; } if (rm->registryClass) { (*env)->DeleteGlobalRef(env, rm->registryClass); rm->registryClass = 0; } } jint JNI_OnLoad(JavaVM *vm, void *reserved) { jvpp_main_t * jm = &jvpp_main; jvpp_registry_main_t * rm = &jvpp_registry_main; JNIEnv* env; if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_8) != JNI_OK) { return JNI_EVERSION; } rm->controlPingReplyClass = (jclass) (*env)->NewGlobalRef(env, (*env)->FindClass(env, "io/fd/vpp/jvpp/dto/ControlPingReply")); if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionDescribe(env); clib_warning("Failed to cache class references\n"); return JNI_ERR; } rm->callbackExceptionClass = (jclass) (*env)->NewGlobalRef(env, (*env)->FindClass(env, "io/fd/vpp/jvpp/VppCallbackException")); if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionDescribe(env); return JNI_ERR; } jm->jvm = vm; return JNI_VERSION_1_8; } void JNI_OnUnload(JavaVM *vm, void *reserved) { jvpp_main_t * jm = &jvpp_main; JNIEnv* env; if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_8) != JNI_OK) { return; } jm->jenv = NULL; jm->jvm = NULL; }