update from RIFT as of 696b75d2fe9fb046261b08c616f1bcf6c0b54a9b second try
Signed-off-by: Jeremy Mordkoff <Jeremy.Mordkoff@riftio.com>
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
index ff329dd..c4ff5df 100644
--- a/examples/CMakeLists.txt
+++ b/examples/CMakeLists.txt
@@ -19,10 +19,6 @@
cmake_minimum_required(VERSION 2.8)
-set(PKG_NAME rwmano_examples)
-set(PKG_VERSION 1.0)
-set(PKG_RELEASE 1)
-set(PKG_LONG_NAME ${PKG_NAME}-${PKG_VERSION})
##
diff --git a/examples/ping_pong_ns/CMakeLists.txt b/examples/ping_pong_ns/CMakeLists.txt
index 7aa4976..6919dd7 100644
--- a/examples/ping_pong_ns/CMakeLists.txt
+++ b/examples/ping_pong_ns/CMakeLists.txt
@@ -15,7 +15,7 @@
#
# Author(s): Anil Gunturu
# Creation Date: 03/26/2014
-#
+
cmake_minimum_required(VERSION 2.8)
@@ -34,12 +34,41 @@
${CMAKE_CURRENT_BINARY_DIR}/pong_vnfd_aws.tar.gz
${CMAKE_CURRENT_BINARY_DIR}/ping_pong_nsd_with_epa.tar.gz
${CMAKE_CURRENT_BINARY_DIR}/ping_vnfd_with_epa.tar.gz
- ${CMAKE_CURRENT_BINARY_DIR}/pong_vnfd_with_epa.tar.gz)
+ ${CMAKE_CURRENT_BINARY_DIR}/ping_vnfd_with_vca.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/pong_vnfd_with_vca.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/ping_pong_nsd_with_vca.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/pong_vnfd_with_epa.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/ping_vnfd_with_vip.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/pong_vnfd_with_vip.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/ping_pong_nsd_with_vip.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/ping_vnfd_with_image.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/pong_vnfd_with_image.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/ping_vnfd_with_vca.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/pong_vnfd_with_vca.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/ping_pong_nsd_with_vca.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/ping_vnfd_with_image.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/pong_vnfd_with_image.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/ping_vnfd_with_vnf_input_parameters.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/pong_vnfd_with_vnf_input_parameters.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/ping_pong_nsd_with_vnf_input_parameters.tar.gz)
add_custom_command(
OUTPUT ${PACKAGE_OUTPUT}
COMMAND ${CMAKE_CURRENT_BINARY_DIR}/generate_packages.sh
- DEPENDS mano_yang rwcloud_yang ${CMAKE_CURRENT_SOURCE_DIR}/ping_pong_nsd.py
+ DEPENDS
+ mano_yang
+ rwcloud_yang
+ ${CMAKE_CURRENT_SOURCE_DIR}/ping_pong_nsd.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/ping_setup.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/ping_rate.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/ping_start_stop.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/pong_setup.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/pong_start_stop.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/ping_initial_config.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/pong_initial_config.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/start_traffic.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/stop_traffic.py
+ ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/primitive_test.py
)
add_custom_target(ping_pong_pkg_gen ALL
@@ -50,22 +79,31 @@
FILES ${PACKAGE_OUTPUT}
DESTINATION
usr/rift/mano/examples/ping_pong_ns
- COMPONENT ${PKG_LONG_NAME}
+ COMPONENT ${INSTALL_COMPONENT}
)
rift_python_install_tree(
- COMPONENT ${PKG_LONG_NAME}
+ COMPONENT ${INSTALL_COMPONENT}
FILES
rift/mano/examples/ping_pong_nsd.py
+ rift/mano/examples/ping_setup.py
+ rift/mano/examples/ping_start_stop.py
+ rift/mano/examples/pong_setup.py
+ rift/mano/examples/pong_start_stop.py
rift/mano/examples/start_traffic.py
rift/mano/examples/ping_set_rate.py
+ rift/mano/examples/stop_traffic.py
+ rift/mano/examples/ping_initial_config.py
+ rift/mano/examples/pong_initial_config.py
+ rift/mano/examples/ping_set_rate.py
+ rift/mano/examples/primitive_test.py
)
install(
PROGRAMS
- rift/mano/examples/ping_config.py
+ rift/mano/examples/ping_scale.py
stand_up_ping_pong
DESTINATION usr/bin
- COMPONENT ${PKG_LONG_NAME}
+ COMPONENT ${INSTALL_COMPONENT}
)
diff --git a/examples/ping_pong_ns/config_desc.py b/examples/ping_pong_ns/config_desc.py
index fcd1400..c8a01ef 100755
--- a/examples/ping_pong_ns/config_desc.py
+++ b/examples/ping_pong_ns/config_desc.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
-#
-# Copyright 2016 RIFT.IO Inc
+#
+# Copyright 2016-2017 RIFT.IO Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -25,12 +25,19 @@
import gi
gi.require_version('RwYang', '1.0')
-from gi.repository import NsdYang, VldYang, VnfdYang, RwYang
+# TODO (Philip): Relook at this code
+
+from gi.repository import (
+ NsdYang,
+ VldYang,
+ VnfdYang,
+ RwYang
+ )
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
-model = RwYang.Model.create_libncx()
+model = RwYang.Model.create_libyang()
model.load_schema_ypbc(VldYang.get_schema())
model.load_schema_ypbc(NsdYang.get_schema())
model.load_schema_ypbc(VnfdYang.get_schema())
@@ -39,7 +46,7 @@
def configure_vld(proxy, vld_xml_hdl):
vld_xml = vld_xml_hdl.read()
logger.debug("Attempting to deserialize XML into VLD protobuf: %s", vld_xml)
- vld = VldYang.YangData_Vld_VldCatalog_Vld()
+ vld = VldYang.YangData_RwProject_Project_VldCatalog_Vld()
vld.from_xml_v2(model, vld_xml)
logger.debug("Sending VLD to netconf: %s", vld)
@@ -49,7 +56,7 @@
def configure_vnfd(proxy, vnfd_xml_hdl):
vnfd_xml = vnfd_xml_hdl.read()
logger.debug("Attempting to deserialize XML into VNFD protobuf: %s", vnfd_xml)
- vnfd = VnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd()
+ vnfd = VnfdYang.YangData_VnfdCatalog_Vnfd()
vnfd.from_xml_v2(model, vnfd_xml)
logger.debug("Sending VNFD to netconf: %s", vnfd)
@@ -59,7 +66,7 @@
def configure_nsd(proxy, nsd_xml_hdl):
nsd_xml = nsd_xml_hdl.read()
logger.debug("Attempting to deserialize XML into NSD protobuf: %s", nsd_xml)
- nsd = NsdYang.YangData_Nsd_NsdCatalog_Nsd()
+ nsd = NsdYang.YangData_NsdCatalog_Nsd()
nsd.from_xml_v2(model, nsd_xml)
logger.debug("Sending NSD to netconf: %s", nsd)
@@ -86,7 +93,9 @@
action="append",
default=[],
type=argparse.FileType(),
- help="VLD XML File Path",
+ #help="VLD XML File Path",
+ # We do not support uploading VLD separately
+ help=argparse.SUPRESS,
)
parser.add_argument(
diff --git a/examples/ping_pong_ns/generate_packages.sh.in b/examples/ping_pong_ns/generate_packages.sh.in
index 5fa0a8f..6255c6b 100755
--- a/examples/ping_pong_ns/generate_packages.sh.in
+++ b/examples/ping_pong_ns/generate_packages.sh.in
@@ -38,6 +38,22 @@
rm -rf ${BINARY_DIR}/pong_vnfd_with_epa
rm -rf ${BINARY_DIR}/ping_pong_nsd_with_epa
+rm -rf ${BINARY_DIR}/ping_vnfd_with_vca
+rm -rf ${BINARY_DIR}/pong_vnfd_with_vca
+rm -rf ${BINARY_DIR}/ping_pong_nsd_with_vca
+
+rm -rf ${BINARY_DIR}/ping_vnfd_with_vip
+rm -rf ${BINARY_DIR}/pong_vnfd_with_vip
+rm -rf ${BINARY_DIR}/ping_pong_nsd_with_vip
+
+rm -rf ${BINARY_DIR}/ping_vnfd_with_scaling
+rm -rf ${BINARY_DIR}/pong_vnfd_with_scaling
+rm -rf ${BINARY_DIR}/ping_pong_nsd_with_scaling
+
+rm -rf ${BINARY_DIR}/ping_vnfd_with_vnf_input_parameters
+rm -rf ${BINARY_DIR}/pong_vnfd_with_vnf_input_parameters
+rm -rf ${BINARY_DIR}/ping_pong_nsd_with_vnf_input_parameters
+
# Generate image md5sum
ping_md5sum="$(md5sum ${PING_QCOW_IMAGE} | cut -f1 -d" ")"
@@ -52,9 +68,8 @@
cp -r ${BINARY_DIR}/pong_vnfd ${BINARY_DIR}/pong_vnfd_with_image
mkdir -p ${BINARY_DIR}/ping_vnfd_with_image/images
mkdir -p ${BINARY_DIR}/pong_vnfd_with_image/images
-
### Generate descriptors for AWS
-${SOURCE_DIR}/ping_pong_nsd.py --outdir=${BINARY_DIR}/aws --format=json --aws
+${SOURCE_DIR}/ping_pong_nsd.py --outdir=${BINARY_DIR}/aws --format=yaml --aws
### Move the generated artifacts to appropriate directories
mv ${BINARY_DIR}/aws/ping_vnfd ${BINARY_DIR}/ping_vnfd_aws
@@ -64,8 +79,19 @@
### ReMove the original directories
rm -rf ${BINARY_DIR}/aws
+### Generate descriptors for VNF Input Parameters
+${SOURCE_DIR}/ping_pong_nsd.py --outdir=${BINARY_DIR}/vnf_input_parameters --format=yaml --ping-image-md5=${ping_md5sum} --pong-image-md5=${pong_md5sum} --pong-cloud-init=pong_cloud_init.cfg --ping-cloud-init=ping_cloud_init.cfg --vnf-input-parameter
+
+### Move the generated artifacts to appropriate directories
+mv ${BINARY_DIR}/vnf_input_parameters/ping_vnfd ${BINARY_DIR}/ping_vnfd_with_vnf_input_parameters
+mv ${BINARY_DIR}/vnf_input_parameters/pong_vnfd ${BINARY_DIR}/pong_vnfd_with_vnf_input_parameters
+mv ${BINARY_DIR}/vnf_input_parameters/ping_pong_nsd ${BINARY_DIR}/ping_pong_nsd_with_vnf_input_parameters
+
+### ReMove the original directories
+rm -rf ${BINARY_DIR}/vnf_input_parameters
+
### Generate descriptors with EPA
-${SOURCE_DIR}/ping_pong_nsd.py --outdir=${BINARY_DIR}/with_epa --format=json --epa --ping-image-md5=${ping_md5sum} --pong-image-md5=${pong_md5sum}
+${SOURCE_DIR}/ping_pong_nsd.py --outdir=${BINARY_DIR}/with_epa --format=yaml --epa --ping-image-md5=${ping_md5sum} --pong-image-md5=${pong_md5sum}
### Move the generated artifacts to appropriate directories
mv ${BINARY_DIR}/with_epa/ping_vnfd ${BINARY_DIR}/ping_vnfd_with_epa
@@ -75,6 +101,40 @@
### ReMove the original directories
rm -rf ${BINARY_DIR}/with_epa
+### Generate descriptors with VCA conf
+${SOURCE_DIR}/ping_pong_nsd.py --outdir=${BINARY_DIR}/with_vca --format=yaml --vca_conf --ping-image-md5=${ping_md5sum} --pong-image-md5=${pong_md5sum}
+
+### Move the generated artifacts to appropriate directories
+mv ${BINARY_DIR}/with_vca/ping_vnfd ${BINARY_DIR}/ping_vnfd_with_vca
+mv ${BINARY_DIR}/with_vca/pong_vnfd ${BINARY_DIR}/pong_vnfd_with_vca
+mv ${BINARY_DIR}/with_vca/ping_pong_nsd ${BINARY_DIR}/ping_pong_nsd_with_vca
+
+### ReMove the original directories
+rm -rf ${BINARY_DIR}/with_vca
+
+### Generate descriptors with Virtual-IP
+${SOURCE_DIR}/ping_pong_nsd.py --outdir=${BINARY_DIR}/with_vip --format=yaml --virtual-ip --ping-image-md5=${ping_md5sum} --pong-image-md5=${pong_md5sum}
+
+### Move the generated artifacts to appropriate directories
+mv ${BINARY_DIR}/with_vip/ping_vnfd ${BINARY_DIR}/ping_vnfd_with_vip
+mv ${BINARY_DIR}/with_vip/pong_vnfd ${BINARY_DIR}/pong_vnfd_with_vip
+mv ${BINARY_DIR}/with_vip/ping_pong_nsd ${BINARY_DIR}/ping_pong_nsd_with_vip
+
+### ReMove the original directories
+rm -rf ${BINARY_DIR}/with_vip
+
+### Generate descriptors with scaling
+${SOURCE_DIR}/ping_pong_nsd.py --outdir=${BINARY_DIR}/with_scaling --format=yaml --scale --ping-image-md5=${ping_md5sum} --pong-image-md5=${pong_md5sum}
+
+### Move the generated artifacts to appropriate directories
+mv ${BINARY_DIR}/with_scaling/ping_vnfd ${BINARY_DIR}/ping_vnfd_with_scaling
+mv ${BINARY_DIR}/with_scaling/pong_vnfd ${BINARY_DIR}/pong_vnfd_with_scaling
+mv ${BINARY_DIR}/with_scaling/ping_pong_nsd ${BINARY_DIR}/ping_pong_nsd_with_scaling
+
+### ReMove the original directories
+rm -rf ${BINARY_DIR}/with_scaling
+
+
# copy a dummy image for now
if [ -e ${PING_QCOW_IMAGE} ]; then
# Add RIFT Logos
@@ -127,6 +187,19 @@
${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} ping_pong_nsd_aws
# Add RIFT Logos
+mkdir -p ${BINARY_DIR}/ping_vnfd_with_vnf_input_parameters/icons
+mkdir -p ${BINARY_DIR}/pong_vnfd_with_vnf_input_parameters/icons
+mkdir -p ${BINARY_DIR}/ping_pong_nsd_with_vnf_input_parameters/icons
+
+cp ${PING_VNFD_LOGO} ${BINARY_DIR}/ping_vnfd_with_vnf_input_parameters/icons/
+cp ${PONG_VNFD_LOGO} ${BINARY_DIR}/pong_vnfd_with_vnf_input_parameters/icons/
+cp ${PING_PONG_NSD_LOGO} ${BINARY_DIR}/ping_pong_nsd_with_vnf_input_parameters/icons/
+
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} ping_vnfd_with_vnf_input_parameters
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} pong_vnfd_with_vnf_input_parameters
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} ping_pong_nsd_with_vnf_input_parameters
+
+# Add RIFT Logos
mkdir -p ${BINARY_DIR}/ping_vnfd_with_epa/icons
mkdir -p ${BINARY_DIR}/pong_vnfd_with_epa/icons
mkdir -p ${BINARY_DIR}/ping_pong_nsd_with_epa/icons
@@ -138,3 +211,41 @@
${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} ping_vnfd_with_epa
${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} pong_vnfd_with_epa
${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} ping_pong_nsd_with_epa
+
+# Add RIFT Logos
+mkdir -p ${BINARY_DIR}/ping_vnfd_with_vca/icons
+mkdir -p ${BINARY_DIR}/pong_vnfd_with_vca/icons
+mkdir -p ${BINARY_DIR}/ping_pong_nsd_with_vca/icons
+
+cp ${PING_VNFD_LOGO} ${BINARY_DIR}/ping_vnfd_with_vca/icons/
+cp ${PONG_VNFD_LOGO} ${BINARY_DIR}/pong_vnfd_with_vca/icons/
+cp ${PING_PONG_NSD_LOGO} ${BINARY_DIR}/ping_pong_nsd_with_vca/icons/
+
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} ping_vnfd_with_vca
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} pong_vnfd_with_vca
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} ping_pong_nsd_with_vca
+
+
+mkdir -p ${BINARY_DIR}/ping_vnfd_with_vip/icons
+mkdir -p ${BINARY_DIR}/pong_vnfd_with_vip/icons
+mkdir -p ${BINARY_DIR}/ping_pong_nsd_with_vip/icons
+
+cp ${PING_VNFD_LOGO} ${BINARY_DIR}/ping_vnfd_with_vip/icons/
+cp ${PONG_VNFD_LOGO} ${BINARY_DIR}/pong_vnfd_with_vip/icons/
+cp ${PING_PONG_NSD_LOGO} ${BINARY_DIR}/ping_pong_nsd_with_vip/icons/
+
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} ping_vnfd_with_vip
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} pong_vnfd_with_vip
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} ping_pong_nsd_with_vip
+
+mkdir -p ${BINARY_DIR}/ping_vnfd_with_scaling/icons
+mkdir -p ${BINARY_DIR}/pong_vnfd_with_scaling/icons
+mkdir -p ${BINARY_DIR}/ping_pong_nsd_with_scaling/icons
+
+cp ${PING_VNFD_LOGO} ${BINARY_DIR}/ping_vnfd_with_scaling/icons/
+cp ${PONG_VNFD_LOGO} ${BINARY_DIR}/pong_vnfd_with_scaling/icons/
+cp ${PING_PONG_NSD_LOGO} ${BINARY_DIR}/ping_pong_nsd_with_scaling/icons/
+
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} ping_vnfd_with_scaling
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} pong_vnfd_with_scaling
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} ping_pong_nsd_with_scaling
diff --git a/examples/ping_pong_ns/rift/mano/examples/ping_initial_config.py b/examples/ping_pong_ns/rift/mano/examples/ping_initial_config.py
new file mode 100755
index 0000000..1aac832
--- /dev/null
+++ b/examples/ping_pong_ns/rift/mano/examples/ping_initial_config.py
@@ -0,0 +1,218 @@
+#!/usr/bin/env python3
+
+############################################################################
+# Copyright 2016 RIFT.IO Inc #
+# #
+# 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 argparse
+import logging
+import os
+import subprocess
+import sys
+import time
+
+import yaml
+
+
+def ping_initial_config(yaml_cfg, logger):
+ '''Use curl to configure ping and set the ping rate'''
+
+ def find_vnfr(vnfr_dict, name):
+ try:
+ for k, v in vnfr_dict.items():
+ if v['name'] == name:
+ return v
+ except KeyError:
+ logger.warn("Could not find vnfr for name : %s", name)
+
+ def find_vnfr_by_substring(vnfr_dict, name):
+ try:
+ for k, v in vnfr_dict.items():
+ if name in v['name']:
+ return v
+ except KeyError:
+ logger.warn("Could not find vnfr by name : %s", name)
+
+ def find_cp_ip(vnfr, cp_name):
+ for cp in vnfr['connection_point']:
+ logger.debug("Connection point: %s", format(cp))
+ if cp_name in cp['name']:
+ return cp['ip_address']
+
+ raise ValueError("Could not find vnfd %s connection point %s", cp_name)
+
+ def find_vnfr_mgmt_ip(vnfr):
+ return vnfr['mgmt_ip_address']
+
+ def get_vnfr_name(vnfr):
+ return vnfr['name']
+
+ def find_vdur_mgmt_ip(vnfr):
+ return vnfr['vdur'][0]['vm_management_ip']
+
+ def find_param_value(param_list, input_param):
+ for item in param_list:
+ logger.debug("Parameter: %s", format(item))
+ if item['name'] == input_param:
+ return item['value']
+
+ def set_ping_destination(mgmt_ip, port, pong_ip, pong_port):
+ curl_cmd = 'curl -D /dev/null -H "Accept: application/vnd.yang.data' \
+ '+xml" -H "Content-Type: application/vnd.yang.data+json" ' \
+ '-X POST -d "{{\\"ip\\":\\"{pong_ip}\\", \\"port\\":{pong_port}}}" ' \
+ 'http://{mgmt_ip}:{mgmt_port}/api/v1/ping/server'. \
+ format(
+ mgmt_ip=mgmt_ip,
+ mgmt_port=port,
+ pong_ip=pong_ip,
+ pong_port=pong_port)
+
+ logger.debug("Executing set-server cmd: %s", curl_cmd)
+ count = 0
+ delay = 20
+ max_tries = 12
+ rc = 0
+ while True:
+ count += 1
+ proc = subprocess.Popen(curl_cmd, shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+
+ proc.wait()
+ logger.debug("Process: {}".format(proc))
+
+ if proc.returncode == 0:
+ logger.info("Success response ")
+ rc = 0
+ break
+
+ elif proc.returncode == 7:
+ # Connection timeout
+ if count >= max_tries:
+ logger.error("Connect failed for {}. Failing".format(count))
+ rc = 7
+ break
+ # Try after delay
+ time.sleep(delay)
+
+ return rc
+
+ # Get the required and optional parameters
+ ping_vnfr = find_vnfr(yaml_cfg['vnfr'], yaml_cfg['vnfr_name'])
+ ping_vnf_mgmt_ip = find_vnfr_mgmt_ip(ping_vnfr)
+ pong_vnfr = yaml_cfg['vnfr'][2]
+ pong_svc_ip = find_cp_ip(pong_vnfr, 'pong_vnfd/cp0')
+
+ # Get the required and optional parameters
+ mgmt_ip = ping_vnf_mgmt_ip
+ mgmt_port = 18888
+ rate = 5
+
+ rc = set_ping_destination(mgmt_ip, mgmt_port, pong_svc_ip, 5555)
+ if rc != 0:
+ return rc
+
+ cmd = 'curl -D /dev/null -H "Accept: application/vnd.yang.data' \
+ '+xml" -H "Content-Type: application/vnd.yang.data+json" ' \
+ '-X POST -d "{{\\"rate\\":{rate}}}" ' \
+ 'http://{mgmt_ip}:{mgmt_port}/api/v1/ping/rate'. \
+ format(
+ mgmt_ip=mgmt_ip,
+ mgmt_port=mgmt_port,
+ rate=rate)
+
+ logger.debug("Executing set-rate cmd: %s", cmd)
+ count = 0
+ delay = 10
+ max_tries = 12
+ rc = 0
+
+ while True:
+ count += 1
+ proc = subprocess.Popen(cmd, shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ proc.wait()
+
+ logger.debug("Process: {}".format(proc))
+
+ if proc.returncode == 0:
+ rc = 0
+ break
+
+ elif proc.returncode == 7:
+ # Connection timeout
+ if count >= max_tries:
+ logger.error("Connect failed for {}. Failing".format(count))
+ rc = 7
+ break
+ # Try after delay
+ time.sleep(delay)
+
+ return rc
+
+def main(argv=sys.argv[1:]):
+ try:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
+ parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
+ args = parser.parse_args()
+
+ run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
+ if not os.path.exists(run_dir):
+ os.makedirs(run_dir)
+ log_file = "{}/ping_initial_config-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
+
+ # logging.basicConfig(filename=log_file, level=logging.DEBUG)
+ logger = logging.getLogger('ping-initial-config')
+ logger.setLevel(logging.DEBUG)
+
+ fh = logging.FileHandler(log_file)
+ fh.setLevel(logging.DEBUG)
+
+ ch = logging.StreamHandler()
+ if args.verbose:
+ ch.setLevel(logging.DEBUG)
+ else:
+ ch.setLevel(logging.INFO)
+
+ # create formatter and add it to the handlers
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ fh.setFormatter(formatter)
+ ch.setFormatter(formatter)
+ logger.addHandler(fh)
+ logger.addHandler(ch)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+ try:
+ logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
+ yaml_str = args.yaml_cfg_file.read()
+ yaml_cfg = yaml.load(yaml_str)
+ logger.debug("Input YAML: {}".format(yaml_cfg))
+
+ rc = ping_initial_config(yaml_cfg, logger)
+ logger.info("Return code: {}".format(rc))
+ sys.exit(rc)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/ping_pong_ns/rift/mano/examples/ping_pong_nsd.py b/examples/ping_pong_ns/rift/mano/examples/ping_pong_nsd.py
index ef2dd90..ba1c759 100755
--- a/examples/ping_pong_ns/rift/mano/examples/ping_pong_nsd.py
+++ b/examples/ping_pong_ns/rift/mano/examples/ping_pong_nsd.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
#
-# Copyright 2016 RIFT.IO Inc
+# Copyright 2016-2017 RIFT.IO Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -18,24 +18,27 @@
import argparse
+import simplejson
import os
+import yaml
import shutil
import sys
import uuid
+import random
+
+from xml.dom.minidom import parseString
import gi
gi.require_version('RwYang', '1.0')
gi.require_version('RwVnfdYang', '1.0')
gi.require_version('VnfdYang', '1.0')
gi.require_version('RwNsdYang', '1.0')
-gi.require_version('NsdYang', '1.0')
-
from gi.repository import (
- RwNsdYang,
- NsdYang,
- RwVnfdYang,
- VnfdYang,
+ RwNsdYang as RwNsdYang,
+ NsdYang as NsdYang,
+ RwVnfdYang as RwVnfdYang,
+ VnfdYang as VnfdYang,
RwYang,
)
@@ -91,7 +94,7 @@
self.descriptor = None
def write_to_file(self, module_list, outdir, output_format):
- model = RwYang.Model.create_libncx()
+ model = RwYang.Model.create_libyang()
for module in module_list:
model.load_module(module)
@@ -107,28 +110,532 @@
else:
raise Exception("Invalid output format for the descriptor")
- def get_json(self, module_list):
- model = RwYang.Model.create_libncx()
- for module in module_list:
- model.load_module(module)
- print(self.descriptor.to_json(model))
-
class VirtualNetworkFunction(ManoDescriptor):
def __init__(self, name, instance_count=1):
self.vnfd_catalog = None
self.vnfd = None
+ self.mano_ut = False
+ self.use_ns_init_conf = False
+ self.use_vca_conf = False
+ self.use_charm = False
self.instance_count = instance_count
self._placement_groups = []
+ self.config_files = []
self.use_vnf_init_conf = False
super(VirtualNetworkFunction, self).__init__(name)
def add_placement_group(self, group):
self._placement_groups.append(group)
- def compose(self, image_name, cloud_init="", cloud_init_file="", endpoint=None, mon_params=[],
- mon_port=8888, mgmt_port=8888, num_vlr_count=1, num_ivlr_count=1,
- num_vms=1, image_md5sum=None, mano_ut=False):
+ def add_vnf_conf_param_charm(self):
+ vnfd = self.descriptor.vnfd[0]
+ confparam = vnfd.config_parameter
+
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "mgmt_ip",
+ "description": "Management IP address",
+ "attribute": "../../../mgmt-interface, ip-address",
+ "parameter" : [{
+ "config_primitive_name_ref": "config",
+ "config_primitive_parameter_ref": "ssh-hostname"
+ }]
+ })
+ confparam.config_parameter_source.append(src)
+
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "username",
+ "description": "SSH username",
+ "value": "fedora",
+ "parameter" : [{
+ "config_primitive_name_ref": "config",
+ "config_primitive_parameter_ref": "ssh-username"
+ }]
+ })
+ confparam.config_parameter_source.append(src)
+
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "ssh_key",
+ "description": "SSH private key file",
+ "attribute": "../../../mgmt-interface/ssh-key, private-key-file",
+ "parameter" : [{
+ "config_primitive_name_ref": "config",
+ "config_primitive_parameter_ref": "ssh-private-key"
+ }]
+ })
+ confparam.config_parameter_source.append(src)
+
+ # Check if pong
+ if 'pong_' in self.name:
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "service_ip",
+ "description": "IP on which Pong service is listening",
+ "attribute": "../../../connection-point[name='pong_vnfd/cp0'], ip-address",
+ "parameter" : [
+ {
+ "config_primitive_name_ref": "set-server",
+ "config_primitive_parameter_ref": "server-ip"
+ },
+ ]
+ })
+ confparam.config_parameter_source.append(src)
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "service_port",
+ "description": "Port on which server listens for incoming data packets",
+ "value": "5555",
+ "parameter" : [
+ {
+ "config_primitive_name_ref": "set-server",
+ "config_primitive_parameter_ref": "server-port"
+ },
+ ]
+ })
+ confparam.config_parameter_source.append(src)
+
+ else:
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "rate",
+ "description": "Rate of packet generation",
+ "value": "5",
+ "parameter" : [
+ {
+ "config_primitive_name_ref": "set-rate",
+ "config_primitive_parameter_ref": "rate"
+ },
+ ]
+ })
+ confparam.config_parameter_source.append(src)
+
+ req = confparam.create_config_parameter_request()
+ req.from_dict({
+ "name": "pong_ip",
+ "description": "IP on which Pong service is listening",
+ "parameter" : [
+ {
+ "config_primitive_name_ref": "set-server",
+ "config_primitive_parameter_ref": "server-ip"
+ },
+ ]
+ })
+ confparam.config_parameter_request.append(req)
+ req = confparam.create_config_parameter_request()
+ req.from_dict({
+ "name": "pong_port",
+ "description": "Port on which Pong service is listening",
+ "parameter" : [
+ {
+ "config_primitive_name_ref": "set-server",
+ "config_primitive_parameter_ref": "server-port"
+ },
+ ]
+ })
+ confparam.config_parameter_request.append(req)
+
+ def add_vnf_conf_param(self):
+ vnfd = self.descriptor.vnfd[0]
+ confparam = vnfd.config_parameter
+
+ def get_params(param):
+ # Check if pong
+ if 'pong_' in self.name:
+ params = [
+ {
+ "config_primitive_name_ref": "config",
+ "config_primitive_parameter_ref": param
+ },
+ {
+ "config_primitive_name_ref": "start-stop",
+ "config_primitive_parameter_ref": param
+ },
+ ]
+ else:
+ params = [
+ {
+ "config_primitive_name_ref": "config",
+ "config_primitive_parameter_ref": param
+ },
+ {
+ "config_primitive_name_ref": "set-rate",
+ "config_primitive_parameter_ref": param
+ },
+ {
+ "config_primitive_name_ref": "start-stop",
+ "config_primitive_parameter_ref": param
+ },
+ ]
+ return params
+
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "mgmt_ip",
+ "description": "Management address",
+ "attribute": "../../../mgmt-interface, ip-address",
+ "parameter" : get_params("mgmt_ip")
+ })
+ confparam.config_parameter_source.append(src)
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "mgmt_port",
+ "description": "Management port",
+ "descriptor": "../../../mgmt-interface/port",
+ "parameter" : get_params("mgmt_port")
+ })
+ confparam.config_parameter_source.append(src)
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "username",
+ "description": "Management username",
+ "value": "admin",
+ "parameter" : get_params("username")
+ })
+ confparam.config_parameter_source.append(src)
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "password",
+ "description": "Management password",
+ "value": "admin",
+ "parameter" : get_params("password")
+ })
+ confparam.config_parameter_source.append(src)
+
+ # Check if pong
+ if 'pong_' in self.name:
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "service_ip",
+ "description": "IP on which Pong service is listening",
+ "attribute": "../../../connection-point[name='pong_vnfd/cp0'], ip-address",
+ "parameter" : [
+ {
+ "config_primitive_name_ref": "config",
+ "config_primitive_parameter_ref": "service_ip"
+ },
+ ]
+ })
+ confparam.config_parameter_source.append(src)
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "service_port",
+ "description": "Port on which server listens for incoming data packets",
+ "value": "5555",
+ "parameter" : [
+ {
+ "config_primitive_name_ref": "config",
+ "config_primitive_parameter_ref": "service_port"
+ },
+ ]
+ })
+ confparam.config_parameter_source.append(src)
+
+ else:
+ src = confparam.create_config_parameter_source()
+ src.from_dict({
+ "name": "rate",
+ "description": "Rate of packet generation",
+ "value": "5",
+ "parameter" : [
+ {
+ "config_primitive_name_ref": "set-rate",
+ "config_primitive_parameter_ref": "rate"
+ },
+ ]
+ })
+ confparam.config_parameter_source.append(src)
+
+ req = confparam.create_config_parameter_request()
+ req.from_dict({
+ "name": "pong_ip",
+ "description": "IP on which Pong service is listening",
+ "parameter" : [
+ {
+ "config_primitive_name_ref": "config",
+ "config_primitive_parameter_ref": "pong_ip"
+ },
+ ]
+ })
+ confparam.config_parameter_request.append(req)
+ req = confparam.create_config_parameter_request()
+ req.from_dict({
+ "name": "pong_port",
+ "description": "Port on which Pong service is listening",
+ "parameter" : [
+ {
+ "config_primitive_name_ref": "config",
+ "config_primitive_parameter_ref": "pong_port"
+ },
+ ]
+ })
+ confparam.config_parameter_request.append(req)
+
+ def add_ping_vca_config(self):
+ vnfd = self.descriptor.vnfd[0]
+ # Add vnf configuration
+ vnf_config = vnfd.vnf_configuration
+
+ # vnf_config.config_attributes.config_delay = 10
+
+ # Select "script" configuration
+ vnf_config.script.script_type = 'rift'
+
+ # Add config primitive
+ prim = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "config",
+ "parameter": [
+ {"name": "mgmt_ip", "data_type": "STRING", "read_only": "true"},
+ {"name": "mgmt_port", "data_type": "INTEGER", "read_only": "true"},
+ {"name": "username", "data_type": "STRING", "read_only": "true"},
+ {"name": "password", "data_type": "STRING", "read_only": "true"},
+ {"name": "pong_ip", "data_type": "STRING", "read_only": "true"},
+ {"name": "pong_port", "data_type": "INTEGER","read_only": "true",
+ "default_value": "5555"},
+ ],
+ "user_defined_script": "ping_setup.py",
+ })
+ vnf_config.config_primitive.append(prim)
+
+ prim = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "set-rate",
+ "parameter": [
+ {"name": "mgmt_ip", "data_type": "STRING", "read_only": "true"},
+ {"name": "mgmt_port", "data_type": "INTEGER", "read_only": "true"},
+ {"name": "username", "data_type": "STRING", "read_only": "true"},
+ {"name": "password", "data_type": "STRING", "read_only": "true"},
+ {"name": "rate", "data_type": "INTEGER",
+ "default_value": "5"},
+ ],
+ "user_defined_script": "ping_rate.py",
+ })
+ vnf_config.config_primitive.append(prim)
+
+ prim = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "start-stop",
+ "parameter": [
+ {"name": "mgmt_ip", "data_type": "STRING", "read_only": "true"},
+ {"name": "mgmt_port", "data_type": "INTEGER", "read_only": "true"},
+ {"name": "username", "data_type": "STRING", "read_only": "true"},
+ {"name": "password", "data_type": "STRING", "read_only": "true"},
+ {"name": "start", "data_type": "BOOLEAN",
+ "default_value": "true"}
+ ],
+ "user_defined_script": "ping_start_stop.py",
+ })
+ vnf_config.config_primitive.append(prim)
+
+ # Add initial config primitive
+ init_config = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 1,
+ "config_primitive_ref": "config",
+ }
+ )
+ vnf_config.initial_config_primitive.append(init_config)
+
+ init_config = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 2,
+ "config_primitive_ref": "set-rate",
+ },
+ )
+ vnf_config.initial_config_primitive.append(init_config)
+
+ if self.use_ns_init_conf is False:
+ init_config = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 3,
+ "config_primitive_ref": "start-stop",
+ },
+ )
+ vnf_config.initial_config_primitive.append(init_config)
+
+ def add_pong_vca_config(self):
+ vnfd = self.descriptor.vnfd[0]
+ # Add vnf configuration
+ vnf_config = vnfd.vnf_configuration
+
+ # Select "script" configuration
+ vnf_config.script.script_type = 'rift'
+
+ # Add config primitive
+ prim = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "config",
+ "parameter": [
+ {"name": "mgmt_ip", "data_type": "STRING", "read_only": "true"},
+ {"name": "mgmt_port", "data_type": "INTEGER", "read_only": "true"},
+ {"name": "username", "data_type": "STRING", "read_only": "true"},
+ {"name": "password", "data_type": "STRING", "read_only": "true"},
+ {"name": "service_ip", "data_type": "STRING", "read_only": "true"},
+ {"name": "service_port", "data_type": "INTEGER", "read_only": "true"},
+ ],
+ "user_defined_script": "pong_setup.py",
+ })
+ vnf_config.config_primitive.append(prim)
+
+ prim = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "start-stop",
+ "parameter": [
+ {"name": "mgmt_ip", "data_type": "STRING", "read_only": "true"},
+ {"name": "mgmt_port", "data_type": "INTEGER", "read_only": "true"},
+ {"name": "username", "data_type": "STRING", "read_only": "true"},
+ {"name": "password", "data_type": "STRING", "read_only": "true"},
+ {"name": "start", "data_type": "BOOLEAN",
+ "default_value": "true"}
+ ],
+ "user_defined_script": "pong_start_stop.py",
+ })
+ vnf_config.config_primitive.append(prim)
+
+ # Add initial config primitive
+ init_config = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 1,
+ "config_primitive_ref": "config",
+ }
+ )
+ vnf_config.initial_config_primitive.append(init_config)
+
+ if self.use_ns_init_conf is False:
+ init_config = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 2,
+ "config_primitive_ref": "start-stop",
+ },
+ )
+ vnf_config.initial_config_primitive.append(init_config)
+
+ def add_charm_config(self):
+ vnfd = self.descriptor.vnfd[0]
+ # Add vnf configuration
+ vnf_config = vnfd.vnf_configuration
+
+ if 'pong_' in self.name:
+ mode = "pong"
+ else:
+ mode = "ping"
+
+ # Select "script" configuration
+ vnf_config.juju.charm = 'pingpong'
+
+ # Add config primitive
+ vnf_config.create_config_primitive()
+ prim = VnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "start",
+ })
+ vnf_config.config_primitive.append(prim)
+
+ prim = VnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "stop",
+ })
+ vnf_config.config_primitive.append(prim)
+
+ prim = VnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "restart",
+ })
+ vnf_config.config_primitive.append(prim)
+
+ prim = VnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "config",
+ "parameter": [
+ {"name": "ssh-hostname", "data_type": "STRING"},
+ {"name": "ssh-username", "data_type": "STRING"},
+ {"name": "ssh-private-key", "data_type": "STRING"},
+ {"name": "mode", "data_type": "STRING",
+ "default_value": "{}".format(mode),
+ "read_only": "true"},
+ ],
+ })
+ vnf_config.config_primitive.append(prim)
+
+ prim = VnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "set-server",
+ "parameter": [
+ {"name": "server-ip", "data_type": "STRING"},
+ {"name": "server-port", "data_type": "INTEGER"},
+ ],
+ })
+ vnf_config.config_primitive.append(prim)
+
+ if mode == 'ping':
+ prim = VnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "set-rate",
+ "parameter": [
+ {"name": "rate", "data_type": "INTEGER",
+ "default_value": "5"},
+ ],
+ })
+ vnf_config.config_primitive.append(prim)
+
+ prim = VnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "start-traffic",
+ })
+ vnf_config.config_primitive.append(prim)
+
+ prim = VnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_ConfigPrimitive.from_dict({
+ "name": "stop-traffic",
+ })
+ vnf_config.config_primitive.append(prim)
+
+ # Add initial config primitive
+ vnf_config.create_initial_config_primitive()
+ init_config = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 1,
+ "config_primitive_ref": "config",
+ }
+ )
+ vnf_config.initial_config_primitive.append(init_config)
+
+ init_config = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 2,
+ "config_primitive_ref": "start",
+ }
+ )
+ vnf_config.initial_config_primitive.append(init_config)
+
+ init_config = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 3,
+ "config_primitive_ref": "set-server",
+ },
+ )
+ vnf_config.initial_config_primitive.append(init_config)
+
+ if mode == 'ping':
+ init_config = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 4,
+ "config_primitive_ref": "set-rate",
+ },
+ )
+ vnf_config.initial_config_primitive.append(init_config)
+
+ if self.use_ns_init_conf is False:
+ init_config = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 5,
+ "config_primitive_ref": "start-traffic",
+ },
+ )
+ vnf_config.initial_config_primitive.append(init_config)
+
+ def compose(self, image_name, vnf_descriptor_message, cloud_init="", cloud_init_file="",
+ endpoint=None, mon_params=[], mon_port=8888, mgmt_port=8888, num_vlr_count=1,
+ num_ivlr_count=1, num_vms=1, image_md5sum=None, mano_ut=False,
+ use_ns_init_conf=False, use_vca_conf=False, use_charm=False, use_static_ip=False,
+ multidisk=None, port_security=None, metadata_vdud=None, use_ipv6=False,
+ use_virtual_ip=False, vnfd_input_params=None, script_input_params=None, explicit_port_seq=False, mgmt_net=True):
+
+ self.mano_ut = mano_ut
+ self.use_ns_init_conf = use_ns_init_conf
+ self.use_vca_conf = use_vca_conf
+ self.use_charm = use_charm
+
self.descriptor = RwVnfdYang.YangData_Vnfd_VnfdCatalog()
self.id = str(uuid.uuid1())
vnfd = self.descriptor.vnfd.add()
@@ -137,12 +644,18 @@
vnfd.short_name = self.name
vnfd.vendor = 'RIFT.io'
vnfd.logo = 'rift_logo.png'
- vnfd.description = 'This is an example RIFT.ware VNF'
+ vnfd.description = vnf_descriptor_message
vnfd.version = '1.0'
self.vnfd = vnfd
- if mano_ut is True:
+ if explicit_port_seq:
+ # ping and pong vnfds will have 2 and 5 internal interfaces respectively
+ num_ivlr_count = 2
+ if 'pong' in vnfd.name:
+ num_ivlr_count = 5
+
+ if mano_ut or use_virtual_ip or explicit_port_seq:
internal_vlds = []
for i in range(num_ivlr_count):
internal_vld = vnfd.internal_vld.add()
@@ -154,12 +667,20 @@
internal_vlds.append(internal_vld)
for i in range(num_vlr_count):
+ index = i+1 if mgmt_net else i
cp = vnfd.connection_point.add()
cp.type_yang = 'VPORT'
- cp.name = '%s/cp%d' % (self.name, i)
-
+ cp.name = '%s/cp%d' % (self.name, index)
+ if port_security is not None:
+ cp.port_security_enabled = port_security
+
+ if mgmt_net:
+ cp = vnfd.connection_point.add()
+ cp.type_yang = 'VPORT'
+ cp.name = '%s/cp0' % (self.name)
+
if endpoint is not None:
- endp = VnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_HttpEndpoint(
+ endp = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_HttpEndpoint(
path=endpoint, port=mon_port, polling_interval_secs=2
)
vnfd.http_endpoint.append(endp)
@@ -170,7 +691,6 @@
monp.http_endpoint_ref = endpoint
vnfd.monitoring_param.append(monp)
-
for i in range(num_vms):
# VDU Specification
vdu = vnfd.vdu.add()
@@ -196,12 +716,16 @@
mgmt_intf.dashboard_params.path = endpoint
mgmt_intf.dashboard_params.port = mgmt_port
- if cloud_init_file and len(cloud_init_file):
- vdu.cloud_init_file = cloud_init_file
- else:
- vdu.cloud_init = cloud_init
- if aws:
- vdu.cloud_init += " - [ systemctl, restart, --no-block, elastic-network-interfaces.service ]\n"
+ if use_charm:
+ mgmt_intf.ssh_key = True
+
+ if not self.use_charm:
+ if cloud_init_file and len(cloud_init_file):
+ vdu.cloud_init_file = cloud_init_file
+ else:
+ vdu.cloud_init = cloud_init
+ if aws:
+ vdu.cloud_init += " - [ systemctl, restart, --no-block, elastic-network-interfaces.service ]\n"
# sepcify the guest EPA
if use_epa:
@@ -246,40 +770,167 @@
if aws:
vdu.image = 'rift-ping-pong'
+ elif multidisk:
+ ping_test_data, pong_test_data = multidisk
+ test_data = ping_test_data
+ if 'pong' in vnfd.name:
+ test_data = pong_test_data
+ for vol_name, vol_attrs in test_data.items():
+ vol = vdu.volumes.add()
+ vol.name = vol_name
+ vol.device_type = vol_attrs[0]
+ vol.device_bus = vol_attrs[1]
+ vol.size = vol_attrs[2]
+ if vol_attrs[3]:
+ vol.image = vol_attrs[3]
+ # Bug RIFT-15165. Will comment out later once the bug is fixed
+ #else:
+ # vol.ephemeral = True
+
+ if vol_attrs[4] is not None:
+ vol.boot_priority = vol_attrs[4]
else:
vdu.image = image_name
if image_md5sum is not None:
vdu.image_checksum = image_md5sum
- if mano_ut is True:
+ if explicit_port_seq:
+ # pong vnfd will have 3 ordered interfaces out of 7 and all interfaces of ping vnfd are ordered
+ ordered_interfaces_count = num_vlr_count + num_ivlr_count
+ if 'pong' in vnfd.name:
+ ordered_interfaces_count = 3
+ interface_positions_list = random.sample(range(1, 2**32-1), ordered_interfaces_count-1)
+ random.shuffle(interface_positions_list)
+
+ if mano_ut or use_virtual_ip or explicit_port_seq:
+ vip_internal_intf_pool_start = 51
for i in range(num_ivlr_count):
internal_cp = vdu.internal_connection_point.add()
if vnfd.name.find("ping") >= 0:
- cp_name = "ping"
+ cp_name = "ping_vnfd"
else:
- cp_name = "pong"
+ cp_name = "pong_vnfd"
internal_cp.name = cp_name + "/icp{}".format(i)
internal_cp.id = cp_name + "/icp{}".format(i)
internal_cp.type_yang = 'VPORT'
- ivld_cp = internal_vlds[i].internal_connection_point_ref.add()
+ ivld_cp = internal_vlds[i].internal_connection_point.add()
ivld_cp.id_ref = internal_cp.id
-
- internal_interface = vdu.internal_interface.add()
+ if use_virtual_ip:
+ vcp = internal_vlds[i].virtual_connection_points.add()
+ if 'ping' in vnfd.name:
+ vcp.name = 'ivcp-0'
+ else:
+ vcp.name = 'ivcp-1'
+ vcp.type_yang = 'VPORT'
+ vcp.associated_cps.append(internal_cp.id)
+ int_interface_positon_set = False
+ internal_interface = vdu.interface.add()
internal_interface.name = 'fab%d' % i
- internal_interface.vdu_internal_connection_point_ref = internal_cp.id
+ internal_interface.type_yang = 'INTERNAL'
+ internal_interface.internal_connection_point_ref = internal_cp.id
internal_interface.virtual_interface.type_yang = 'VIRTIO'
-
+ if explicit_port_seq and interface_positions_list:
+ internal_interface.position = interface_positions_list.pop()
+ int_interface_positon_set = True
# internal_interface.virtual_interface.vpci = '0000:00:1%d.0'%i
+ if use_virtual_ip and int_interface_positon_set is False:
+ internal_interface.position = vip_internal_intf_pool_start
+ vip_internal_intf_pool_start += 1
+ if mgmt_net:
+ #adding a vlr for management network
+ num_vlr_count = num_vlr_count + 1
+
+ vip_external_intf_pool_start = 1
for i in range(num_vlr_count):
- external_interface = vdu.external_interface.add()
- external_interface.name = 'eth%d' % i
- external_interface.vnfd_connection_point_ref = '%s/cp%d' % (self.name, i)
- if use_epa:
- external_interface.virtual_interface.type_yang = 'VIRTIO'
- else:
- external_interface.virtual_interface.type_yang = 'VIRTIO'
+ ext_interface_positon_set = False
+ external_interface = vdu.interface.add()
+ external_interface.name = 'eth%d' % (i)
+ external_interface.type_yang = 'EXTERNAL'
+ external_interface.external_connection_point_ref = '%s/cp%d' % (self.name, i)
+ # The first external interface need to be set as the packets use this
+ # and we bring up only the eth0 (mgmt interface) and eth1 in the ping and
+ # pong VMs
+ if explicit_port_seq and (i == 0):
+ external_interface.position = 1
+ elif explicit_port_seq and interface_positions_list:
+ external_interface.position = interface_positions_list.pop()
+ ext_interface_positon_set = True
+
+ external_interface.virtual_interface.type_yang = 'VIRTIO'
# external_interface.virtual_interface.vpci = '0000:00:2%d.0'%i
+ if use_virtual_ip and ext_interface_positon_set is False:
+ external_interface.position = vip_external_intf_pool_start
+ vip_external_intf_pool_start += 1
+
+ if use_static_ip and not(mgmt_net and i == 0):
+ if 'pong_' in self.name:
+ external_interface.static_ip_address = '31.31.31.31'
+ if use_ipv6:
+ external_interface.static_ip_address = '3fee:1111:1111::1234'
+ else:
+ external_interface.static_ip_address = '31.31.31.32'
+ if use_ipv6:
+ external_interface.static_ip_address = '3fee:1111:1111::1235'
+
+
+ if metadata_vdud:
+ # Metadata for VDU
+ # Add config files, custom-meta-data for both ping, pong VNFs. Enable 'boot data drive' only for ping VNF
+ meta_data = {'EMS_IP':'10.1.2.3', 'Licenseserver_IP':'192.168.1.1'}
+ for i in range(2):
+ self.config_files.append('test_cfg_file_{}.txt'.format(random.randint(1,1000)))
+
+ supplemental_boot_data = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_Vdu_SupplementalBootData()
+
+ # Add config files
+ for cfg_file in self.config_files:
+ config_file = supplemental_boot_data.config_file.add()
+ config_file.source = cfg_file
+ config_file.dest = os.path.join('/tmp',cfg_file)
+
+ # enable 'boot data drive' only for ping VNF
+ if 'ping_' in vnfd.name:
+ supplemental_boot_data.boot_data_drive = True
+ # Add custom metadata
+ for name, value in meta_data.items():
+ custom_meta_data = supplemental_boot_data.custom_meta_data.add()
+ custom_meta_data.name = name
+ custom_meta_data.value = value
+
+ vdu.supplemental_boot_data = supplemental_boot_data
+
+ if vnfd_input_params:
+ # Input parameters for vnfd
+ supplemental_boot_data = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_Vdu_SupplementalBootData()
+
+ if 'ping_' in vnfd.name or 'pong_' in vnfd.name:
+ cloud_init_data = supplemental_boot_data.custom_meta_data.add()
+ cloud_init_data.destination = 'CLOUD_INIT'
+ cloud_init_data.name = 'custom_cloud_init_data'
+ cloud_init_data.value = 'cc_init_data'
+ cloud_init_data.data_type = 'STRING'
+
+ cloud_meta_data = supplemental_boot_data.custom_meta_data.add()
+ cloud_meta_data.destination = 'CLOUD_METADATA'
+ cloud_meta_data.name = 'custom_cloud_meta_data'
+ cloud_meta_data.value = 'cc_meta_data'
+ cloud_meta_data.data_type = 'STRING'
+
+ vdu.supplemental_boot_data = supplemental_boot_data
+
+ if script_input_params:
+ # Input parameters for vnfd
+ supplemental_boot_data = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_Vdu_SupplementalBootData()
+
+ if 'ping_' in vnfd.name or 'pong_' in vnfd.name:
+ cloud_init_data = supplemental_boot_data.custom_meta_data.add()
+ cloud_init_data.destination = 'CLOUD_METADATA'
+ cloud_init_data.name = 'CI-script-init-data'
+ cloud_init_data.value = 'default_script_init_data'
+ cloud_init_data.data_type = 'STRING'
+
+ vdu.supplemental_boot_data = supplemental_boot_data
for group in self._placement_groups:
placement_group = vnfd.placement_groups.add()
@@ -297,6 +948,54 @@
member_vdu = placement_group.member_vdus.add()
member_vdu.member_vdu_ref = vdu.id
+ # Add VNF access point
+ if use_vca_conf:
+ if use_charm:
+ self.add_vnf_conf_param_charm()
+ self.add_charm_config()
+ else:
+ self.add_vnf_conf_param()
+ if 'pong_' in self.name:
+ self.add_pong_vca_config()
+ else:
+ self.add_ping_vca_config()
+ else:
+ if 'pong_' in self.name:
+ self.add_pong_config()
+ else:
+ self.add_ping_config()
+
+ def add_ping_config(self):
+ vnfd = self.descriptor.vnfd[0]
+ # Add vnf configuration
+ vnf_config = vnfd.vnf_configuration
+ vnf_config.script.script_type = 'rift'
+
+ # Add initial config primitive
+ init_config = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 1,
+ "name": "Ping config",
+ "user_defined_script": "ping_initial_config.py",
+ }
+ )
+ vnf_config.initial_config_primitive.append(init_config)
+
+ def add_pong_config(self):
+ vnfd = self.descriptor.vnfd[0]
+ # Add vnf configuration
+ vnf_config = vnfd.vnf_configuration
+ vnf_config.script.script_type = 'rift'
+
+ # Add initial config primitive
+ init_config =RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd_VnfConfiguration_InitialConfigPrimitive.from_dict(
+ {
+ "seq": 1,
+ "name": "Pong config",
+ "user_defined_script": "pong_initial_config.py",
+ }
+ )
+ vnf_config.initial_config_primitive.append(init_config)
def write_to_file(self, outdir, output_format):
dirpath = "%s/%s" % (outdir, self.name)
@@ -307,7 +1006,7 @@
output_format)
self.add_scripts(outdir)
- def add_scripts(self, outdir):
+ def add_cloud_init(self, outdir):
script_dir = os.path.join(outdir, self.name, 'cloud_init')
try:
os.makedirs(script_dir)
@@ -315,7 +1014,7 @@
if not os.path.isdir(script_dir):
raise
- if 'ping' in self.name:
+ if 'ping_' in self.name:
script_file = os.path.join(script_dir, 'ping_cloud_init.cfg')
cfg = PING_USERDATA_FILE
else:
@@ -325,19 +1024,68 @@
with open(script_file, "w") as f:
f.write("{}".format(cfg))
- # Copy the vnf_init_config script
- if self.use_vnf_init_conf and ('ping' in self.name):
- script_name = 'ping_set_rate.py'
+ # Create the config files in script_dir
+ for cfg_file in self.config_files:
+ with open(os.path.join(script_dir, cfg_file), 'w') as f:
+ f.write('metadata-vdud test')
- src_path = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
+ def add_scripts(self, outdir):
+ if not self.use_charm:
+ self.add_cloud_init(outdir)
+
+ if not self.use_charm:
+ if self.use_vca_conf:
+ self.add_vca_scripts(outdir)
+ else:
+ self.add_config_scripts(outdir)
+
+ def add_config_scripts(self, outdir):
+ dest_path = os.path.join(outdir, self.name, 'scripts')
+ try:
+ os.makedirs(dest_path)
+ except OSError:
+ if not os.path.isdir(dest_path):
+ raise
+
+ if 'pong_' in self.name:
+ scripts = ['pong_initial_config.py']
+ else:
+ scripts = ['ping_initial_config.py']
+
+ for script_name in scripts:
+ src_path = os.path.dirname(os.path.abspath(
+ os.path.realpath(__file__)))
script_src = os.path.join(src_path, script_name)
if not os.path.exists(script_src):
src_path = os.path.join(os.environ['RIFT_ROOT'],
- 'modules/core/mano/examples/ping_pong_ns/rift/mano/examples')
+ 'modules/core/mano/examples/'
+ 'ping_pong_ns/rift/mano/examples')
script_src = os.path.join(src_path, script_name)
- dest_path = os.path.join(outdir, self.name, 'scripts')
- os.makedirs(dest_path, exist_ok=True)
+ shutil.copy2(script_src, dest_path)
+
+ def add_vca_scripts(self, outdir):
+ dest_path = os.path.join(outdir, self.name, 'scripts')
+ try:
+ os.makedirs(dest_path)
+ except OSError:
+ if not os.path.isdir(dest_path):
+ raise
+
+ if 'pong_' in self.name:
+ scripts = ['pong_setup.py', 'pong_start_stop.py']
+ else:
+ scripts = ['ping_setup.py', 'ping_rate.py', 'ping_start_stop.py']
+
+ for script_name in scripts:
+ src_path = os.path.dirname(os.path.abspath(
+ os.path.realpath(__file__)))
+ script_src = os.path.join(src_path, script_name)
+ if not os.path.exists(script_src):
+ src_path = os.path.join(os.environ['RIFT_ROOT'],
+ 'modules/core/mano/examples/'
+ 'ping_pong_ns/rift/mano/examples')
+ script_src = os.path.join(src_path, script_name)
shutil.copy2(script_src, dest_path)
@@ -349,255 +1097,16 @@
self.vnfd_config = {}
self._placement_groups = []
- def ping_config(self, mano_ut, use_ns_init_conf, use_vnf_init_conf):
- suffix = ''
- if mano_ut:
- ping_cfg = r'''
-#!/bin/bash
+ def default_config(self, constituent_vnfd, vnfd, mano_ut, use_ns_init_conf, use_vnf_init_conf):
+ vnf_config = vnfd.vnfd.vnf_configuration
-echo "!!!!!!!! Executed ping Configuration !!!!!!!!!"
- '''
- else:
- ping_cfg = r'''
-#!/bin/bash
-
-# Rest API config
-ping_mgmt_ip='<rw_mgmt_ip>'
-ping_mgmt_port=18888
-
-# VNF specific configuration
-pong_server_ip='<rw_connection_point_name pong_vnfd%s/cp0>'
-ping_rate=5
-server_port=5555
-
-# Make rest API calls to configure VNF
-curl -D /dev/stdout \
- -H "Accept: application/vnd.yang.data+xml" \
- -H "Content-Type: application/vnd.yang.data+json" \
- -X POST \
- -d "{\"ip\":\"$pong_server_ip\", \"port\":$server_port}" \
- http://${ping_mgmt_ip}:${ping_mgmt_port}/api/v1/ping/server
-rc=$?
-if [ $rc -ne 0 ]
-then
- echo "Failed to set server info for ping!"
- exit $rc
-fi
-''' % suffix
-
- if use_vnf_init_conf is False:
- ping_cfg +='''
-curl -D /dev/stdout \
- -H "Accept: application/vnd.yang.data+xml" \
- -H "Content-Type: application/vnd.yang.data+json" \
- -X POST \
- -d "{\"rate\":$ping_rate}" \
- http://${ping_mgmt_ip}:${ping_mgmt_port}/api/v1/ping/rate
-rc=$?
-if [ $rc -ne 0 ]
-then
- echo "Failed to set ping rate!"
- exit $rc
-fi
-
-'''
- if use_ns_init_conf:
- ping_cfg += "exit 0\n"
- else:
- ping_cfg +='''
-output=$(curl -D /dev/stdout \
- -H "Accept: application/vnd.yang.data+xml" \
- -H "Content-Type: application/vnd.yang.data+json" \
- -X POST \
- -d "{\"enable\":true}" \
- http://${ping_mgmt_ip}:${ping_mgmt_port}/api/v1/ping/adminstatus/state)
-if [[ $output == *"Internal Server Error"* ]]
-then
- echo $output
- exit 3
-else
- echo $output
-fi
-
-exit 0
-'''
- return ping_cfg
-
- def pong_config(self, mano_ut, use_ns_init_conf):
- suffix = ''
- if mano_ut:
- pong_cfg = r'''
-#!/bin/bash
-
-echo "!!!!!!!! Executed pong Configuration !!!!!!!!!"
- '''
- else:
- pong_cfg = r'''
-#!/bin/bash
-
-# Rest API configuration
-pong_mgmt_ip='<rw_mgmt_ip>'
-pong_mgmt_port=18889
-# username=<rw_username>
-# password=<rw_password>
-
-# VNF specific configuration
-pong_server_ip='<rw_connection_point_name pong_vnfd%s/cp0>'
-server_port=5555
-
-# Make Rest API calls to configure VNF
-curl -D /dev/stdout \
- -H "Accept: application/vnd.yang.data+xml" \
- -H "Content-Type: application/vnd.yang.data+json" \
- -X POST \
- -d "{\"ip\":\"$pong_server_ip\", \"port\":$server_port}" \
- http://${pong_mgmt_ip}:${pong_mgmt_port}/api/v1/pong/server
-rc=$?
-if [ $rc -ne 0 ]
-then
- echo "Failed to set server(own) info for pong!"
- exit $rc
-fi
-
-''' % suffix
-
- if use_ns_init_conf:
- pong_cfg += "exit 0\n"
- else:
- pong_cfg +='''
-curl -D /dev/stdout \
- -H "Accept: application/vnd.yang.data+xml" \
- -H "Content-Type: application/vnd.yang.data+json" \
- -X POST \
- -d "{\"enable\":true}" \
- http://${pong_mgmt_ip}:${pong_mgmt_port}/api/v1/pong/adminstatus/state
-rc=$?
-if [ $rc -ne 0 ]
-then
- echo "Failed to enable pong service!"
- exit $rc
-fi
-
-exit 0
-'''
- return pong_cfg
-
- def pong_fake_juju_config(self, vnf_config):
-
- if vnf_config:
- # Select "script" configuration
- vnf_config.juju.charm = 'clearwater-aio-proxy'
-
- # Set the initital-config
- vnf_config.create_initial_config_primitive()
- init_config = VnfdYang.InitialConfigPrimitive.from_dict({
- "seq": 1,
- "name": "config",
- "parameter": [
- {"name": "proxied_ip", "value": "<rw_mgmt_ip>"},
- ]
- })
- vnf_config.initial_config_primitive.append(init_config)
-
- init_config_action = VnfdYang.InitialConfigPrimitive.from_dict({
- "seq": 2,
- "name": "action1",
- "parameter": [
- {"name": "Pong Connection Point", "value": "pong_vnfd/cp0"},
- ]
- })
- vnf_config.initial_config_primitive.append(init_config_action)
- init_config_action = VnfdYang.InitialConfigPrimitive.from_dict({
- "seq": 3,
- "name": "action2",
- "parameter": [
- {"name": "Ping Connection Point", "value": "ping_vnfd/cp0"},
- ]
- })
- vnf_config.initial_config_primitive.append(init_config_action)
-
- # Config parameters can be taken from config.yaml and
- # actions from actions.yaml in the charm
- # Config to set the home domain
- vnf_config.create_service_primitive()
- config = VnfdYang.ServicePrimitive.from_dict({
- "name": "config",
- "parameter": [
- {"name": "home_domain", "data_type": "STRING"},
- {"name": "base_number", "data_type": "STRING"},
- {"name": "number_count", "data_type": "INTEGER"},
- {"name": "password", "data_type": "STRING"},
- ]
- })
- vnf_config.service_primitive.append(config)
-
- config = VnfdYang.ServicePrimitive.from_dict({
- "name": "create-update-user",
- # "user-defined-script":"/tmp/test.py",
- "parameter": [
- {"name": "number", "data_type": "STRING", "mandatory": True},
- {"name": "password", "data_type": "STRING", "mandatory": True},
- ]
- })
- vnf_config.service_primitive.append(config)
-
- config = VnfdYang.ServicePrimitive.from_dict({
- "name": "delete-user",
- "parameter": [
- {"name": "number", "data_type": "STRING", "mandatory": True},
- ]
- })
- vnf_config.service_primitive.append(config)
-
- def default_config(self, const_vnfd, vnfd, mano_ut,
- use_ns_init_conf,
- use_vnf_init_conf):
- vnf_config = vnfd.vnfd.vnf_configuration
-
- vnf_config.config_attributes.config_priority = 0
- vnf_config.config_attributes.config_delay = 0
-
- # Select "script" configuration
- vnf_config.script.script_type = 'bash'
-
- if vnfd.name == 'pong_vnfd' or vnfd.name == 'pong_vnfd_with_epa' or vnfd.name == 'pong_vnfd_aws':
- vnf_config.config_attributes.config_priority = 1
- vnf_config.config_template = self.pong_config(mano_ut, use_ns_init_conf)
- # First priority config delay will delay the entire NS config delay
- if mano_ut is False:
- vnf_config.config_attributes.config_delay = 60
- else:
- # This is PONG and inside mano_ut
- # This is test only
- vnf_config.config_attributes.config_delay = 10
- # vnf_config.config_template = self.pong_config(vnf_config, use_ns_init_conf)
-
- if vnfd.name == 'ping_vnfd' or vnfd.name == 'ping_vnfd_with_epa' or vnfd.name == 'ping_vnfd_aws':
- vnf_config.config_attributes.config_priority = 2
- vnf_config.config_template = self.ping_config(mano_ut,
- use_ns_init_conf,
- use_vnf_init_conf)
- if use_vnf_init_conf:
- vnf_config.initial_config_primitive.add().from_dict(
- {
- "seq": 1,
- "name": "set ping rate",
- "user_defined_script": "ping_set_rate.py",
- "parameter": [
- {
- 'name': 'rate',
- 'value': '5',
- },
- ],
- }
- )
def ns_config(self, nsd, vnfd_list, mano_ut):
# Used by scale group
if mano_ut:
nsd.service_primitive.add().from_dict(
{
- "name": "ping config",
+ "name": "ping scale",
"user_defined_script": "{}".format(os.path.join(
os.environ['RIFT_ROOT'],
'modules/core/mano',
@@ -607,12 +1116,21 @@
else:
nsd.service_primitive.add().from_dict(
{
- "name": "ping config",
- "user_defined_script": "ping_config.py"
+ "name": "ping scale",
+ "user_defined_script": "ping_scale.py"
})
+ def ns_xconfig(self, nsd):
+ """Used for a testcase."""
+ nsd.service_primitive.add().from_dict(
+ {
+ "name": "primitive_test",
+ "user_defined_script": "primitive_test.py"
+ }
+ )
+
def ns_initial_config(self, nsd):
- nsd.initial_config_primitive.add().from_dict(
+ nsd.initial_service_primitive.add().from_dict(
{
"seq": 1,
"name": "start traffic",
@@ -625,6 +1143,19 @@
],
}
)
+ nsd.terminate_service_primitive.add().from_dict(
+ {
+ "seq": 1,
+ "name": "stop traffic",
+ "user_defined_script": "stop_traffic.py",
+ "parameter": [
+ {
+ 'name': 'userid',
+ 'value': 'rift',
+ },
+ ],
+ }
+ )
def add_scale_group(self, scale_group):
self._scale_groups.append(scale_group)
@@ -644,18 +1175,56 @@
'value_type': mon_param.value_type,
'vnfd_monitoring_param': [
{'vnfd_id_ref': vnfd_obj.vnfd.id,
- 'vnfd_monitoring_param_ref': mon_param.id}]
+ 'vnfd_monitoring_param_ref': mon_param.id,
+ 'member_vnf_index_ref': self.get_member_vnf_index(vnfd_obj.vnfd.id)}],
})
self.nsd.monitoring_param.append(nsd_monp)
param_id += 1
+ def get_vnfd_id(self, index):
+ for cv in self.nsd.constituent_vnfd:
+ if cv.member_vnf_index == index:
+ return cv.vnfd_id_ref
+ def get_member_vnf_index(self, vnfd_id):
+ for cv in self.nsd.constituent_vnfd:
+ if cv.vnfd_id_ref == vnfd_id:
+ return cv.member_vnf_index
+ def add_conf_param_map(self):
+ nsd = self.nsd
+
+ confparam_map = nsd.config_parameter_map.add()
+ confparam_map.id = '1'
+ confparam_map.config_parameter_source.member_vnf_index_ref = 2
+ confparam_map.config_parameter_source.vnfd_id_ref = self.get_vnfd_id(2)
+ confparam_map.config_parameter_source.config_parameter_source_ref = 'service_ip'
+ confparam_map.config_parameter_request.member_vnf_index_ref = 1
+ confparam_map.config_parameter_request.vnfd_id_ref = self.get_vnfd_id(1)
+ confparam_map.config_parameter_request.config_parameter_request_ref = 'pong_ip'
+
+ confparam_map = nsd.config_parameter_map.add()
+ confparam_map.id = '2'
+ confparam_map.config_parameter_source.member_vnf_index_ref = 2
+ confparam_map.config_parameter_source.vnfd_id_ref = self.get_vnfd_id(2)
+ confparam_map.config_parameter_source.config_parameter_source_ref = 'service_port'
+ confparam_map.config_parameter_request.member_vnf_index_ref = 1
+ confparam_map.config_parameter_request.vnfd_id_ref = self.get_vnfd_id(1)
+ confparam_map.config_parameter_request.config_parameter_request_ref = 'pong_port'
def compose(self, vnfd_list, cpgroup_list, mano_ut,
+ ns_descriptor_message,
use_ns_init_conf=True,
- use_vnf_init_conf=True,):
+ use_vnf_init_conf=True,
+ use_vca_conf=False,
+ use_ipv6=False,
+ port_security = None,
+ use_virtual_ip=False,
+ primitive_test=False,
+ vnfd_input_params=False,
+ script_input_params=False,
+ mgmt_net=True):
if mano_ut:
# Disable NS initial config primitive
@@ -671,20 +1240,31 @@
nsd.short_name = self.name
nsd.vendor = 'RIFT.io'
nsd.logo = 'rift_logo.png'
- nsd.description = 'Toy NS'
+ nsd.description = ns_descriptor_message
nsd.version = '1.0'
nsd.input_parameter_xpath.append(
NsdYang.YangData_Nsd_NsdCatalog_Nsd_InputParameterXpath(
- xpath="/nsd:nsd-catalog/nsd:nsd/nsd:vendor",
+ xpath="/nsd-catalog/nsd/vendor",
)
)
+ if vnfd_input_params:
+ nsd.input_parameter_xpath.append(
+ NsdYang.YangData_Nsd_NsdCatalog_Nsd_InputParameterXpath(
+ xpath="/vnfd:vnfd-catalog/vnfd:vnfd/vnfd:vendor",
+ )
+ )
+
ip_profile = nsd.ip_profiles.add()
ip_profile.name = "InterVNFLink"
ip_profile.description = "Inter VNF Link"
ip_profile.ip_profile_params.ip_version = "ipv4"
ip_profile.ip_profile_params.subnet_address = "31.31.31.0/24"
ip_profile.ip_profile_params.gateway_address = "31.31.31.210"
+ if use_ipv6:
+ ip_profile.ip_profile_params.ip_version = "ipv6"
+ ip_profile.ip_profile_params.subnet_address = "3fee:1111:1111::/64"
+ ip_profile.ip_profile_params.gateway_address = "3fee:1111:1111::1"
vld_id = 1
for cpgroup in cpgroup_list:
@@ -698,12 +1278,19 @@
vld.version = '1.0'
vld.type_yang = 'ELAN'
vld.ip_profile_ref = 'InterVNFLink'
- for cp in cpgroup:
+ for i, cp in enumerate(cpgroup):
cpref = vld.vnfd_connection_point_ref.add()
cpref.member_vnf_index_ref = cp[0]
cpref.vnfd_id_ref = cp[1]
cpref.vnfd_connection_point_ref = cp[2]
-
+ if use_virtual_ip:
+ vcp = vld.virtual_connection_points.add()
+ vcp.name = 'vcp-{}'.format(i)
+ vcp.type_yang = 'VPORT'
+ if port_security is not None:
+ vcp.port_security_enabled = port_security
+ vcp.associated_cps.append(cpref.vnfd_connection_point_ref)
+
vnfd_index_map = {}
member_vnf_index = 1
for vnfd in vnfd_list:
@@ -719,10 +1306,78 @@
constituent_vnfd.start_by_default = False
constituent_vnfd.vnfd_id_ref = vnfd.descriptor.vnfd[0].id
- self.default_config(constituent_vnfd, vnfd, mano_ut,
- use_ns_init_conf, use_vnf_init_conf)
+ if use_vca_conf is False:
+ self.default_config(constituent_vnfd, vnfd, mano_ut,
+ use_ns_init_conf, use_vnf_init_conf)
member_vnf_index += 1
+ if vnfd_input_params:
+ nsd.input_parameter_xpath.append(
+ NsdYang.YangData_Nsd_NsdCatalog_Nsd_InputParameterXpath(
+ xpath="/vnfd:vnfd-catalog/vnfd:vnfd[vnfd:id='%s']/vnfd:vendor" % (constituent_vnfd.vnfd_id_ref),
+ )
+ )
+ nsd.input_parameter_xpath.append(
+ NsdYang.YangData_Nsd_NsdCatalog_Nsd_InputParameterXpath(
+ xpath=(
+ "/vnfd:vnfd-catalog/vnfd:vnfd/vnfd:vdu"
+ "/vnfd:supplemental-boot-data/vnfd:custom-meta-data[vnfd:name='custom_cloud_init_data']/vnfd:value"
+ )
+ )
+ )
+ nsd.input_parameter_xpath.append(
+ NsdYang.YangData_Nsd_NsdCatalog_Nsd_InputParameterXpath(
+ xpath=(
+ "/vnfd:vnfd-catalog/vnfd:vnfd[vnfd:id='%s']/vnfd:vdu[vnfd:id='%s']"
+ "/vnfd:supplemental-boot-data/vnfd:custom-meta-data[vnfd:name='custom_cloud_init_data']/vnfd:value"
+ ) % (constituent_vnfd.vnfd_id_ref, vnfd.descriptor.vnfd[0].vdu[0].id)
+ )
+ )
+ nsd.input_parameter_xpath.append(
+ NsdYang.YangData_Nsd_NsdCatalog_Nsd_InputParameterXpath(
+ xpath=(
+ "/vnfd:vnfd-catalog/vnfd:vnfd/vnfd:vdu"
+ "/vnfd:supplemental-boot-data/vnfd:custom-meta-data[vnfd:name='custom_cloud_meta_data']/vnfd:value"
+ )
+ )
+ )
+ nsd.input_parameter_xpath.append(
+ NsdYang.YangData_Nsd_NsdCatalog_Nsd_InputParameterXpath(
+ xpath=(
+ "/vnfd:vnfd-catalog/vnfd:vnfd[vnfd:id='%s']/vnfd:vdu[vnfd:id='%s']"
+ "/vnfd:supplemental-boot-data/vnfd:custom-meta-data[vnfd:name='custom_cloud_meta_data']/vnfd:value"
+ ) % (constituent_vnfd.vnfd_id_ref, vnfd.descriptor.vnfd[0].vdu[0].id)
+ )
+ )
+
+ if script_input_params:
+ nsd.input_parameter_xpath.append(
+ NsdYang.YangData_Nsd_NsdCatalog_Nsd_InputParameterXpath(
+ xpath=(
+ "/vnfd:vnfd-catalog/vnfd:vnfd[vnfd:id='%s']/vnfd:vdu[vnfd:id='%s']"
+ "/vnfd:supplemental-boot-data/vnfd:custom-meta-data[vnfd:name='CI-script-init-data']/vnfd:value"
+ ) % (constituent_vnfd.vnfd_id_ref, vnfd.descriptor.vnfd[0].vdu[0].id)
+ )
+ )
+
+ if mgmt_net:
+ vld = nsd.vld.add()
+ vld.id = 'mgmt_vld'
+ vld.name = 'mgmt_vld'
+ vld.type_yang = 'ELAN'
+ vld.mgmt_network = "true"
+ vld.vim_network_name = "private"
+
+ ping_cpref = vld.vnfd_connection_point_ref.add()
+ ping_cpref.member_vnf_index_ref = 1
+ ping_cpref.vnfd_id_ref = nsd.constituent_vnfd[0].vnfd_id_ref
+ ping_cpref.vnfd_connection_point_ref = 'ping_vnfd/cp0'
+
+ pong_cpref = vld.vnfd_connection_point_ref.add()
+ pong_cpref.member_vnf_index_ref = 2
+ pong_cpref.vnfd_id_ref = nsd.constituent_vnfd[1].vnfd_id_ref
+ pong_cpref.vnfd_connection_point_ref = 'pong_vnfd/cp0'
+
# Enable config primitives if either mano_ut or
# scale groups are enabled
if mano_ut or len(self._scale_groups):
@@ -732,6 +1387,9 @@
if use_ns_init_conf:
self.ns_initial_config(nsd)
+ if primitive_test:
+ self.ns_xconfig(nsd)
+
for scale_group in self._scale_groups:
group_desc = nsd.scaling_group_descriptor.add()
group_desc.name = scale_group.name
@@ -746,7 +1404,7 @@
config_action = group_desc.scaling_config_action.add()
config_action.trigger = trigger
config = scale_group.config_action[trigger]
- config_action.ns_config_primitive_name_ref = config['ns-config-primitive-name-ref']
+ config_action.ns_service_primitive_name_ref = config['ns-service-primitive-name-ref']
for placement_group in self._placement_groups:
group = nsd.placement_groups.add()
@@ -758,7 +1416,9 @@
member.vnfd_id_ref = member_vnfd.descriptor.vnfd[0].id
member.member_vnf_index_ref = vnfd_index_map[member_vnfd]
- # self.create_mon_params(vnfd_list)
+ self.create_mon_params(vnfd_list)
+ if use_vca_conf:
+ self.add_conf_param_map()
def write_config(self, outdir, vnfds):
@@ -781,9 +1441,7 @@
with open('%s/%s__%s.yaml' % (vnf_config_dir, vnfd.id, i), "w") as fh:
fh.write(yaml_data)
- def write_initial_config_script(self, outdir):
- script_name = 'start_traffic.py'
-
+ def write_config_scripts(self, outdir, script_name):
src_path = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
script_src = os.path.join(src_path, script_name)
if not os.path.exists(script_src):
@@ -805,8 +1463,13 @@
dirpath,
output_format)
- # Write the initial config script
- self.write_initial_config_script(dirpath)
+ # Write the config scripts
+ self.write_config_scripts(dirpath, 'start_traffic.py')
+ self.write_config_scripts(dirpath, 'stop_traffic.py')
+ self.write_config_scripts(dirpath, 'primitive_test.py')
+
+ if len(self._scale_groups):
+ self.write_config_scripts(dirpath, 'ping_scale.py')
def get_ping_mon_params(path):
@@ -877,8 +1540,8 @@
self.vnfd_count_map[vnfd] = vnfd_count
def add_config(self):
- self.config_action['post_scale_out']= {'ns-config-primitive-name-ref':
- 'ping config'}
+ self.config_action['post_scale_out']= {'ns-service-primitive-name-ref':
+ 'ping scale'}
class PlacementGroup(object):
def __init__(self, name):
@@ -909,8 +1572,31 @@
def add_member(self, vdu):
self.vdu_list.append(vdu)
-
-
+def generate_vnf_and_ns_description_message(descriptor_type,
+ aws=False,
+ epa=False,
+ charm=False,
+ vca=False,
+ vip=False):
+ # Helper Function to generate a description message for
+ # VNFD/NSD based on type
+
+ suffix_list = []
+ if aws:
+ suffix_list.append(" for AWS ")
+ else:
+ suffix_list.append(' ')
+
+ if epa:
+ suffix_list.append("EPA")
+ if charm:
+ suffix_list.append("Charm")
+ if vca:
+ suffix_list.append("VCA Conf")
+ if vip:
+ suffix_list.append("VIP")
+ message = "Toy Rift.ware " + descriptor_type + 'with '.join(filter(None, [suffix_list[0], ', '.join(suffix_list[1:])]))
+ return message
def generate_ping_pong_descriptors(fmt="json",
write_to_file=False,
@@ -934,14 +1620,38 @@
use_placement_group=True,
use_ns_init_conf=True,
use_vnf_init_conf=True,
- ):
+ use_vca_conf=False,
+ use_charm=False,
+ use_static_ip=False,
+ port_security=None,
+ metadata_vdud=None,
+ vnfd_input_params=None,
+ script_input_params=None,
+ multidisk=None,
+ explicit_port_seq=False,
+ use_ipv6=False,
+ primitive_test=False,
+ use_virtual_ip=False,
+ mgmt_net=True,
+ nsd_name=None):
+
# List of connection point groups
# Each connection point group refers to a virtual link
# the CP group consists of tuples of connection points
+ if explicit_port_seq:
+ # ping and pong each will have two external interfaces.
+ external_vlr_count = 2
cpgroup_list = []
for i in range(external_vlr_count):
cpgroup_list.append([])
+ if use_charm:
+ use_vca_conf = True
+
+ if use_vca_conf:
+ use_ns_init_conf = True
+ use_vnf_init_conf = False
+
suffix = ''
ping = VirtualNetworkFunction("ping_vnfd%s" % (suffix), pingcount)
ping.use_vnf_init_conf = use_vnf_init_conf
@@ -965,9 +1675,16 @@
ping_userdata=ping_userdata,
ex_ping_userdata=ex_ping_userdata
)
+ ns_descriptor_message = generate_vnf_and_ns_description_message("NS", aws, use_epa,
+ use_charm, use_vca_conf,
+ use_virtual_ip)
+ vnf_descriptor_message = generate_vnf_and_ns_description_message("VNF", aws, use_epa,
+ use_charm, use_vca_conf,
+ use_virtual_ip)
ping.compose(
"Fedora-x86_64-20-20131211.1-sda-ping.qcow2",
+ vnf_descriptor_message,
ping_userdata,
use_ping_cloud_init_file,
"api/v1/ping/stats",
@@ -979,7 +1696,19 @@
num_vms=num_vnf_vms,
image_md5sum=ping_md5sum,
mano_ut=mano_ut,
- )
+ use_ns_init_conf=use_ns_init_conf,
+ use_vca_conf=use_vca_conf,
+ use_charm=use_charm,
+ use_static_ip=use_static_ip,
+ port_security=port_security,
+ metadata_vdud=metadata_vdud,
+ vnfd_input_params=vnfd_input_params,
+ script_input_params=script_input_params,
+ multidisk=multidisk,
+ explicit_port_seq=explicit_port_seq,
+ use_ipv6=use_ipv6,
+ use_virtual_ip=use_virtual_ip,
+ mgmt_net=mgmt_net)
pong = VirtualNetworkFunction("pong_vnfd%s" % (suffix))
@@ -1008,6 +1737,7 @@
pong.compose(
"Fedora-x86_64-20-20131211.1-sda-pong.qcow2",
+ vnf_descriptor_message,
pong_userdata,
use_pong_cloud_init_file,
"api/v1/pong/stats",
@@ -1019,15 +1749,29 @@
num_vms=num_vnf_vms,
image_md5sum=pong_md5sum,
mano_ut=mano_ut,
- )
+ use_ns_init_conf=use_ns_init_conf,
+ use_vca_conf=use_vca_conf,
+ use_charm=use_charm,
+ use_static_ip=use_static_ip,
+ port_security=False if port_security else port_security,
+ metadata_vdud=metadata_vdud,
+ vnfd_input_params=vnfd_input_params,
+ script_input_params=script_input_params,
+ multidisk=multidisk,
+ explicit_port_seq=explicit_port_seq,
+ use_ipv6=use_ipv6,
+ use_virtual_ip=use_virtual_ip,
+ mgmt_net=mgmt_net)
# Initialize the member VNF index
member_vnf_index = 1
# define the connection point groups
for index, cp_group in enumerate(cpgroup_list):
+ if explicit_port_seq:
+ member_vnf_index = 1
desc_id = ping.descriptor.vnfd[0].id
- filename = 'ping_vnfd{}/cp{}'.format(suffix, index)
+ filename = 'ping_vnfd{}/cp{}'.format(suffix, index+1)
for idx in range(pingcount):
cp_group.append((
@@ -1039,7 +1783,7 @@
member_vnf_index += 1
desc_id = pong.descriptor.vnfd[0].id
- filename = 'pong_vnfd{}/cp{}'.format(suffix, index)
+ filename = 'pong_vnfd{}/cp{}'.format(suffix, index+1)
cp_group.append((
member_vnf_index,
@@ -1051,7 +1795,10 @@
vnfd_list = [ping, pong]
- nsd_catalog = NetworkService("ping_pong_nsd%s" % (suffix))
+ if nsd_name is None:
+ nsd_name = "ping_pong_nsd%s" % (suffix)
+
+ nsd_catalog = NetworkService(nsd_name)
if use_scale_group:
group = ScaleGroup("ping_group", max_count=10)
@@ -1084,15 +1831,22 @@
nsd_catalog.compose(vnfd_list,
cpgroup_list,
mano_ut,
+ ns_descriptor_message,
use_ns_init_conf=use_ns_init_conf,
- use_vnf_init_conf=use_vnf_init_conf,)
+ use_vnf_init_conf=use_vnf_init_conf,
+ use_vca_conf=use_vca_conf,
+ use_ipv6=use_ipv6,
+ port_security=port_security,
+ use_virtual_ip=use_virtual_ip,
+ primitive_test=primitive_test,
+ vnfd_input_params=vnfd_input_params,
+ script_input_params=script_input_params)
if write_to_file:
ping.write_to_file(out_dir, ping_fmt if ping_fmt is not None else fmt)
pong.write_to_file(out_dir, pong_fmt if ping_fmt is not None else fmt)
nsd_catalog.write_config(out_dir, vnfd_list)
nsd_catalog.write_to_file(out_dir, ping_fmt if nsd_fmt is not None else fmt)
-
return (ping, pong, nsd_catalog)
@@ -1103,24 +1857,41 @@
parser.add_argument('-f', '--format', default='json')
parser.add_argument('-e', '--epa', action="store_true", default=False)
parser.add_argument('-a', '--aws', action="store_true", default=False)
+ parser.add_argument('--vnf-input-parameter', action="store_true", default=False)
parser.add_argument('-n', '--pingcount', default=NUM_PING_INSTANCES)
parser.add_argument('--ping-image-md5')
parser.add_argument('--pong-image-md5')
parser.add_argument('--ping-cloud-init', default=None)
parser.add_argument('--pong-cloud-init', default=None)
+ parser.add_argument('--charm', action="store_true", default=False)
+ parser.add_argument('-v', '--vca_conf', action="store_true", default=False)
+ parser.add_argument('--virtual-ip', action="store_true", default=False)
+ parser.add_argument('--static-ip', action="store_true", default=False)
+ parser.add_argument('--scale', action="store_true", default=False)
+ parser.add_argument('--primitive-test', action="store_true", default=False)
+
args = parser.parse_args()
outdir = args.outdir
output_format = args.format
use_epa = args.epa
+ use_vnf_input_params = args.vnf_input_parameter
aws = args.aws
- pingcount = args.pingcount
+ pingcount = int(args.pingcount)
use_ping_cloud_init_file = args.ping_cloud_init
use_pong_cloud_init_file = args.pong_cloud_init
generate_ping_pong_descriptors(args.format, True, args.outdir, pingcount,
- ping_md5sum=args.ping_image_md5, pong_md5sum=args.pong_image_md5,
+ ping_md5sum=args.ping_image_md5,
+ pong_md5sum=args.pong_image_md5,
mano_ut=False,
- use_scale_group=False,)
+ use_scale_group=args.scale,
+ use_charm=args.charm,
+ use_vca_conf=args.vca_conf,
+ use_virtual_ip=args.virtual_ip,
+ use_static_ip=args.static_ip,
+ primitive_test=args.primitive_test,
+ vnfd_input_params=use_vnf_input_params
+ )
if __name__ == "__main__":
main()
diff --git a/examples/ping_pong_ns/rift/mano/examples/ping_rate.py b/examples/ping_pong_ns/rift/mano/examples/ping_rate.py
new file mode 100755
index 0000000..d9275f9
--- /dev/null
+++ b/examples/ping_pong_ns/rift/mano/examples/ping_rate.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python3
+
+############################################################################
+# Copyright 2016 RIFT.IO Inc #
+# #
+# 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 argparse
+import logging
+import os
+import subprocess
+import sys
+import time
+
+import yaml
+
+
+def ping_rate(yaml_cfg, logger):
+ '''Use curl to configure ping and set the ping rate'''
+
+ # Get the required and optional parameters
+ params = yaml_cfg['parameters']
+ mgmt_ip = params['mgmt_ip']
+ mgmt_port = 18888
+ if 'mgmt_port' in params:
+ mgmt_port = params['mgmt_port']
+ rate = 1
+ if 'rate' in params:
+ rate = params['rate']
+
+ cmd = 'curl -D /dev/stdout -H "Accept: application/json" ' \
+ '-H "Content-Type: application/json" ' \
+ '-X POST -d "{{\\"rate\\":{rate}}}" ' \
+ 'http://{mgmt_ip}:{mgmt_port}/api/v1/ping/rate'. \
+ format(
+ mgmt_ip=mgmt_ip,
+ mgmt_port=mgmt_port,
+ rate=rate)
+
+ logger.debug("Executing cmd: %s", cmd)
+ proc = subprocess.Popen(cmd, shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+
+ proc.wait()
+
+ logger.debug("Process: {}".format(proc))
+
+ return proc.returncode
+
+
+def main(argv=sys.argv[1:]):
+ try:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
+ parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
+ args = parser.parse_args()
+
+ run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
+ if not os.path.exists(run_dir):
+ os.makedirs(run_dir)
+ log_file = "{}/ping_rate-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
+
+ # logging.basicConfig(filename=log_file, level=logging.DEBUG)
+ logger = logging.getLogger('ping-rate')
+ logger.setLevel(logging.DEBUG)
+
+ fh = logging.FileHandler(log_file)
+ fh.setLevel(logging.DEBUG)
+
+ ch = logging.StreamHandler()
+ if args.verbose:
+ ch.setLevel(logging.DEBUG)
+ else:
+ ch.setLevel(logging.INFO)
+
+ # create formatter and add it to the handlers
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ fh.setFormatter(formatter)
+ ch.setFormatter(formatter)
+ logger.addHandler(fh)
+ logger.addHandler(ch)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+ try:
+ logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
+ yaml_str = args.yaml_cfg_file.read()
+ yaml_cfg = yaml.load(yaml_str)
+ logger.debug("Input YAML: {}".format(yaml_cfg))
+
+ rc = ping_rate(yaml_cfg, logger)
+ logger.info("Return code: {}".format(rc))
+ sys.exit(rc)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/ping_pong_ns/rift/mano/examples/ping_config.py b/examples/ping_pong_ns/rift/mano/examples/ping_scale.py
similarity index 91%
rename from examples/ping_pong_ns/rift/mano/examples/ping_config.py
rename to examples/ping_pong_ns/rift/mano/examples/ping_scale.py
index 4e5fd35..27ffd84 100755
--- a/examples/ping_pong_ns/rift/mano/examples/ping_config.py
+++ b/examples/ping_pong_ns/rift/mano/examples/ping_scale.py
@@ -64,9 +64,9 @@
done
# Make rest API calls to configure VNF
-curl -D /dev/stdout \
- -H "Accept: application/vnd.yang.data+xml" \
- -H "Content-Type: application/vnd.yang.data+json" \
+curl -D /dev/null \
+ -H "Accept: application/json" \
+ -H "Content-Type: application/json" \
-X POST \
-d "{\"ip\":\"$pong_server_ip\", \"port\":$server_port}" \
http://${ping_mgmt_ip}:${ping_mgmt_port}/api/v1/ping/server
@@ -77,9 +77,9 @@
exit $rc
fi
-curl -D /dev/stdout \
- -H "Accept: application/vnd.yang.data+xml" \
- -H "Content-Type: application/vnd.yang.data+json" \
+curl -D /dev/null \
+ -H "Accept: application/json" \
+ -H "Content-Type: application/json" \
-X POST \
-d "{\"rate\":$ping_rate}" \
http://${ping_mgmt_ip}:${ping_mgmt_port}/api/v1/ping/rate
@@ -90,9 +90,9 @@
exit $rc
fi
-output=$(curl -D /dev/stdout \
- -H "Accept: application/vnd.yang.data+xml" \
- -H "Content-Type: application/vnd.yang.data+json" \
+output=$(curl -D /dev/null \
+ -H "Accept: application/json" \
+ -H "Content-Type: application/json" \
-X POST \
-d "{\"enable\":true}" \
http://${ping_mgmt_ip}:${ping_mgmt_port}/api/v1/ping/adminstatus/state)
@@ -128,7 +128,7 @@
run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
if not os.path.exists(run_dir):
os.makedirs(run_dir)
- log_file = "{}/rift_ping_config-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
+ log_file = "{}/rift_ping_scale_config-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
logging.basicConfig(filename=log_file, level=logging.DEBUG)
logger = logging.getLogger()
diff --git a/examples/ping_pong_ns/rift/mano/examples/ping_set_rate.py b/examples/ping_pong_ns/rift/mano/examples/ping_set_rate.py
index 54629e8..6aab121 100644
--- a/examples/ping_pong_ns/rift/mano/examples/ping_set_rate.py
+++ b/examples/ping_pong_ns/rift/mano/examples/ping_set_rate.py
@@ -32,8 +32,8 @@
def set_rate(mgmt_ip, port, rate):
curl_cmd = '''curl -D /dev/stdout \
- -H "Accept: application/vnd.yang.data+xml" \
- -H "Content-Type: application/vnd.yang.data+json" \
+ -H "Accept: application/json" \
+ -H "Content-Type: application/json" \
-X POST \
-d "{{ \\"rate\\":{ping_rate} }}" \
http://{ping_mgmt_ip}:{ping_mgmt_port}/api/v1/ping/rate
@@ -53,7 +53,6 @@
# Check if it is pong vnf
if 'ping_vnfd' in vnfr['name']:
- vnf_type = 'ping'
port = 18888
set_rate(vnfr['mgmt_ip_address'], port, rate)
break
diff --git a/examples/ping_pong_ns/rift/mano/examples/ping_setup.py b/examples/ping_pong_ns/rift/mano/examples/ping_setup.py
new file mode 100755
index 0000000..8d1d317
--- /dev/null
+++ b/examples/ping_pong_ns/rift/mano/examples/ping_setup.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python3
+
+############################################################################
+# Copyright 2016 RIFT.IO Inc #
+# #
+# 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 argparse
+import logging
+import os
+import subprocess
+import sys
+import time
+
+import yaml
+
+
+def ping_setup(yaml_cfg, logger):
+ '''Use curl to configure ping and set the ping rate'''
+
+ # Get the required and optional parameters
+ params = yaml_cfg['parameters']
+ mgmt_ip = params['mgmt_ip']
+ mgmt_port = 18888
+ if 'mgmt_port' in params:
+ mgmt_port = params['mgmt_port']
+ pong_ip = params['pong_ip']
+ pong_port = 5555
+ if 'pong_port' in params:
+ pong_port = params['pong_port']
+ rate = 1
+ if 'rate' in params:
+ rate = params['rate']
+
+ cmd = 'curl -D /dev/stdout -H "Accept: application/json" ' \
+ '-H "Content-Type: application/json" ' \
+ '-X POST -d "{{\\"ip\\":\\"{pong_ip}\\", \\"port\\":{pong_port}}}" ' \
+ 'http://{mgmt_ip}:{mgmt_port}/api/v1/ping/server'. \
+ format(
+ mgmt_ip=mgmt_ip,
+ mgmt_port=mgmt_port,
+ pong_ip=pong_ip,
+ pong_port=pong_port)
+
+ logger.debug("Executing cmd: %s", cmd)
+ count = 0
+ delay = 5
+ max_tries = 12
+ rc = 0
+
+ while True:
+ count += 1
+ proc = subprocess.Popen(cmd, shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ proc.wait()
+
+ logger.debug("Process rc: {}".format(proc.returncode))
+
+ if proc.returncode == 0:
+ # Check if response is 200 OK
+ resp = proc.stdout.read().decode()
+ if 'HTTP/1.1 200 OK' in resp:
+ rc = 0
+ break
+ logger.error("Got error response: {}".format(resp))
+ rc = 1
+ break
+
+ elif proc.returncode == 7:
+ # Connection timeout
+ if count >= max_tries:
+ logger.error("Connect failed for {}. Failing".format(count))
+ rc = 7
+ break
+ # Try after delay
+ time.sleep(delay)
+ else:
+ #Exit the loop incase of errors other than connection timeout and response ok
+ err_resp = proc.stderr.read().decode()
+ logger.error("Got error response: {}".format(err_resp))
+ return proc.returncode
+
+ return rc
+
+def main(argv=sys.argv[1:]):
+ try:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
+ parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
+ args = parser.parse_args()
+
+ run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
+ if not os.path.exists(run_dir):
+ os.makedirs(run_dir)
+ log_file = "{}/ping_setup-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
+
+ # logging.basicConfig(filename=log_file, level=logging.DEBUG)
+ logger = logging.getLogger('ping-setup')
+ logger.setLevel(logging.DEBUG)
+
+ fh = logging.FileHandler(log_file)
+ fh.setLevel(logging.DEBUG)
+
+ ch = logging.StreamHandler()
+ if args.verbose:
+ ch.setLevel(logging.DEBUG)
+ else:
+ ch.setLevel(logging.INFO)
+
+ # create formatter and add it to the handlers
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ fh.setFormatter(formatter)
+ ch.setFormatter(formatter)
+ logger.addHandler(fh)
+ logger.addHandler(ch)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+ try:
+ logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
+ yaml_str = args.yaml_cfg_file.read()
+ yaml_cfg = yaml.load(yaml_str)
+ logger.debug("Input YAML: {}".format(yaml_cfg))
+
+ rc = ping_setup(yaml_cfg, logger)
+ logger.info("Return code: {}".format(rc))
+ sys.exit(rc)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/ping_pong_ns/rift/mano/examples/ping_start_stop.py b/examples/ping_pong_ns/rift/mano/examples/ping_start_stop.py
new file mode 100755
index 0000000..004c058
--- /dev/null
+++ b/examples/ping_pong_ns/rift/mano/examples/ping_start_stop.py
@@ -0,0 +1,124 @@
+#!/usr/bin/env python3
+
+############################################################################
+# Copyright 2016 RIFT.IO Inc #
+# #
+# 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 argparse
+import logging
+import os
+import subprocess
+import sys
+import time
+
+import yaml
+
+
+def ping_start_stop(yaml_cfg, logger):
+ '''Use curl to configure ping and set the ping rate'''
+
+ # Get the required and optional parameters
+ params = yaml_cfg['parameters']
+ mgmt_ip = params['mgmt_ip']
+ mgmt_port = 18888
+ if 'mgmt_port' in params:
+ mgmt_port = params['mgmt_port']
+ start = 'true'
+ if 'start' in params:
+ if not params['start']:
+ start = 'false'
+
+ cmd = 'curl -D /dev/stdout -H "Accept: application/json" ' \
+ '-H "Content-Type: application/json" ' \
+ '-X POST -d "{{\\"enable\\":{start}}}" ' \
+ 'http://{mgmt_ip}:{mgmt_port}/api/v1/ping/adminstatus/state'. \
+ format(
+ mgmt_ip=mgmt_ip,
+ mgmt_port=mgmt_port,
+ start=start)
+
+ logger.debug("Executing cmd: %s", cmd)
+ proc = subprocess.Popen(cmd, shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+
+ proc.wait()
+ logger.debug("Process: {}".format(proc))
+
+ rc = proc.returncode
+
+ if rc == 0:
+ # Check if we got 200 OK
+ resp = proc.stdout.read().decode()
+ if 'HTTP/1.1 200 OK' not in resp:
+ logger.error("Got error response: {}".format(resp))
+ rc = 1
+
+ return rc
+
+
+def main(argv=sys.argv[1:]):
+ try:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
+ parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
+ args = parser.parse_args()
+
+ run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
+ if not os.path.exists(run_dir):
+ os.makedirs(run_dir)
+ log_file = "{}/ping_start_stop-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
+
+ # logging.basicConfig(filename=log_file, level=logging.DEBUG)
+ logger = logging.getLogger('ping-start-stop')
+ logger.setLevel(logging.DEBUG)
+
+ fh = logging.FileHandler(log_file)
+ fh.setLevel(logging.DEBUG)
+
+ ch = logging.StreamHandler()
+ if args.verbose:
+ ch.setLevel(logging.DEBUG)
+ else:
+ ch.setLevel(logging.INFO)
+
+ # create formatter and add it to the handlers
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ fh.setFormatter(formatter)
+ ch.setFormatter(formatter)
+ logger.addHandler(fh)
+ logger.addHandler(ch)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+ try:
+ logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
+ yaml_str = args.yaml_cfg_file.read()
+ yaml_cfg = yaml.load(yaml_str)
+ logger.debug("Input YAML: {}".format(yaml_cfg))
+
+ rc = ping_start_stop(yaml_cfg, logger)
+ logger.info("Return code: {}".format(rc))
+ sys.exit(rc)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/ping_pong_ns/rift/mano/examples/pong_initial_config.py b/examples/ping_pong_ns/rift/mano/examples/pong_initial_config.py
new file mode 100755
index 0000000..a5f9def
--- /dev/null
+++ b/examples/ping_pong_ns/rift/mano/examples/pong_initial_config.py
@@ -0,0 +1,168 @@
+#!/usr/bin/env python3
+
+############################################################################
+# Copyright 2016 RIFT.IO Inc #
+# #
+# 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 argparse
+import logging
+import os
+import subprocess
+import sys
+import time
+
+import yaml
+
+
+def pong_initial_config(yaml_cfg, logger):
+ '''Use curl to configure ping and set the ping rate'''
+ def find_vnfr(vnfr_dict, name):
+ try:
+ for k, v in vnfr_dict.items():
+ if v['name'] == name:
+ return v
+ except KeyError:
+ logger.warn("Could not find vnfr for name : %s", name)
+
+ def find_cp_ip(vnfr, cp_name):
+ for cp in vnfr['connection_point']:
+ logger.debug("Connection point: %s", format(cp))
+ if cp_name in cp['name']:
+ return cp['ip_address']
+
+ raise ValueError("Could not find vnfd %s connection point %s", cp_name)
+
+ def find_vnfr_mgmt_ip(vnfr):
+ return vnfr['mgmt_ip_address']
+
+ def get_vnfr_name(vnfr):
+ return vnfr['name']
+
+ def find_vdur_mgmt_ip(vnfr):
+ return vnfr['vdur'][0]['vm_management_ip']
+
+ def find_param_value(param_list, input_param):
+ for item in param_list:
+ logger.debug("Parameter: %s", format(item))
+ if item['name'] == input_param:
+ return item['value']
+
+ # Get the required and optional parameters
+ pong_vnfr = find_vnfr(yaml_cfg['vnfr'], yaml_cfg['vnfr_name'])
+ pong_vnf_mgmt_ip = find_vnfr_mgmt_ip(pong_vnfr)
+ pong_vnf_svc_ip = find_cp_ip(pong_vnfr, "pong_vnfd/cp0")
+
+
+ # Get the required and optional parameters
+ mgmt_ip = pong_vnf_mgmt_ip
+ mgmt_port = 18889
+ service_ip = pong_vnf_svc_ip
+ service_port = 5555
+
+ config_cmd = 'curl -D /dev/null -H "Accept: application/vnd.yang.data' \
+ '+xml" -H "Content-Type: application/vnd.yang.data+json" ' \
+ '-X POST -d "{{\\"ip\\":\\"{service_ip}\\", \\"port\\":{service_port}}}" ' \
+ 'http://{mgmt_ip}:{mgmt_port}/api/v1/pong/server'. \
+ format(
+ mgmt_ip=mgmt_ip,
+ mgmt_port=mgmt_port,
+ service_ip=service_ip,
+ service_port=service_port)
+
+ logger.debug("Executing cmd: %s", config_cmd)
+ count = 0
+ delay = 20
+ max_tries = 12
+ rc = 0
+
+ while True:
+ count += 1
+ proc = subprocess.Popen(config_cmd, shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+
+ proc.wait()
+ logger.debug("Process: {}".format(proc))
+
+ if proc.returncode == 0:
+ # Check if response is 200 OK
+ logger.info("Success response ")
+ rc = 0
+ break
+ elif proc.returncode == 7:
+ # Connection timeout
+ if count >= max_tries:
+ logger.error("Connect failed for {}. Failing".format(count))
+ rc = 7
+ break
+ # Try after delay
+ time.sleep(delay)
+
+ return rc
+
+
+def main(argv=sys.argv[1:]):
+ try:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
+ parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
+ args = parser.parse_args()
+
+ run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
+ if not os.path.exists(run_dir):
+ os.makedirs(run_dir)
+ log_file = "{}/pong_initial_config-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
+
+ # logging.basicConfig(filename=log_file, level=logging.DEBUG)
+ logger = logging.getLogger('pong-initial-config')
+ logger.setLevel(logging.DEBUG)
+
+ fh = logging.FileHandler(log_file)
+ fh.setLevel(logging.DEBUG)
+
+ ch = logging.StreamHandler()
+ if args.verbose:
+ ch.setLevel(logging.DEBUG)
+ else:
+ ch.setLevel(logging.INFO)
+
+ # create formatter and add it to the handlers
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ fh.setFormatter(formatter)
+ ch.setFormatter(formatter)
+ logger.addHandler(fh)
+ logger.addHandler(ch)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+ try:
+ logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
+ yaml_str = args.yaml_cfg_file.read()
+ yaml_cfg = yaml.load(yaml_str)
+ logger.debug("Input YAML: {}".format(yaml_cfg))
+
+ rc = pong_initial_config(yaml_cfg, logger)
+ logger.info("Return code: {}".format(rc))
+ sys.exit(rc)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/ping_pong_ns/rift/mano/examples/pong_setup.py b/examples/ping_pong_ns/rift/mano/examples/pong_setup.py
new file mode 100755
index 0000000..4da8f2a
--- /dev/null
+++ b/examples/ping_pong_ns/rift/mano/examples/pong_setup.py
@@ -0,0 +1,150 @@
+#!/usr/bin/env python3
+
+############################################################################
+# Copyright 2016 RIFT.IO Inc #
+# #
+# 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 argparse
+import logging
+import os
+import subprocess
+import sys
+import time
+
+import yaml
+
+
+def pong_setup(yaml_cfg, logger):
+ '''Use curl to configure ping and set the ping rate'''
+
+ # Get the required and optional parameters
+ params = yaml_cfg['parameters']
+ mgmt_ip = params['mgmt_ip']
+ mgmt_port = 18889
+ if 'mgmt_port' in params:
+ mgmt_port = params['mgmt_port']
+ service_ip = params['service_ip']
+ service_port = 5555
+ if 'service_port' in params:
+ service_port = params['service_port']
+ rate = 1
+ if 'rate' in params:
+ rate = params['rate']
+
+ config_cmd = 'curl -D /dev/stdout -H "Accept: application/json" ' \
+ '-H "Content-Type: application/json" ' \
+ '-X POST -d "{{\\"ip\\":\\"{service_ip}\\", \\"port\\":{service_port}}}" ' \
+ 'http://{mgmt_ip}:{mgmt_port}/api/v1/pong/server'. \
+ format(
+ mgmt_ip=mgmt_ip,
+ mgmt_port=mgmt_port,
+ service_ip=service_ip,
+ service_port=service_port)
+
+ logger.debug("Executing cmd: %s", config_cmd)
+ count = 0
+ delay = 5
+ max_tries = 12
+ rc = 0
+
+ while True:
+ count += 1
+ proc = subprocess.Popen(config_cmd, shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+
+ proc.wait()
+ logger.debug("Process rc: {}".format(proc.returncode))
+
+ if proc.returncode == 0:
+ # Check if response is 200 OK
+ resp = proc.stdout.read().decode()
+ if 'HTTP/1.1 200 OK' in resp:
+ rc = 0
+ break
+ logger.error("Got error response: {}".format(resp))
+ rc = 1
+ break
+
+ elif proc.returncode == 7:
+ # Connection timeout
+ if count >= max_tries:
+ logger.error("Connect failed for {}. Failing".format(count))
+ rc = 7
+ break
+ # Try after delay
+ time.sleep(delay)
+ else:
+ #Exit the loop incase of errors other than connection timeout and response ok
+ err_resp = proc.stderr.read().decode()
+ logger.error("Got error response: {}".format(err_resp))
+ return proc.returncode
+
+ return rc
+
+
+def main(argv=sys.argv[1:]):
+ try:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
+ parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
+ args = parser.parse_args()
+
+ run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
+ if not os.path.exists(run_dir):
+ os.makedirs(run_dir)
+ log_file = "{}/pong_setup-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
+
+ # logging.basicConfig(filename=log_file, level=logging.DEBUG)
+ logger = logging.getLogger('pong-setup')
+ logger.setLevel(logging.DEBUG)
+
+ fh = logging.FileHandler(log_file)
+ fh.setLevel(logging.DEBUG)
+
+ ch = logging.StreamHandler()
+ if args.verbose:
+ ch.setLevel(logging.DEBUG)
+ else:
+ ch.setLevel(logging.INFO)
+
+ # create formatter and add it to the handlers
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ fh.setFormatter(formatter)
+ ch.setFormatter(formatter)
+ logger.addHandler(fh)
+ logger.addHandler(ch)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+ try:
+ logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
+ yaml_str = args.yaml_cfg_file.read()
+ yaml_cfg = yaml.load(yaml_str)
+ logger.debug("Input YAML: {}".format(yaml_cfg))
+
+ rc = pong_setup(yaml_cfg, logger)
+ logger.info("Return code: {}".format(rc))
+ sys.exit(rc)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/ping_pong_ns/rift/mano/examples/pong_start_stop.py b/examples/ping_pong_ns/rift/mano/examples/pong_start_stop.py
new file mode 100755
index 0000000..953ff3b
--- /dev/null
+++ b/examples/ping_pong_ns/rift/mano/examples/pong_start_stop.py
@@ -0,0 +1,124 @@
+#!/usr/bin/env python3
+
+############################################################################
+# Copyright 2016 RIFT.IO Inc #
+# #
+# 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 argparse
+import logging
+import os
+import subprocess
+import sys
+import time
+
+import yaml
+
+
+def pong_start_stop(yaml_cfg, logger):
+ '''Use curl to configure ping and set the ping rate'''
+
+ # Get the required and optional parameters
+ params = yaml_cfg['parameters']
+ mgmt_ip = params['mgmt_ip']
+ mgmt_port = 18889
+ if 'mgmt_port' in params:
+ mgmt_port = params['mgmt_port']
+ start = 'true'
+ if 'start' in params:
+ if not params['start']:
+ start = 'false'
+
+ cmd = 'curl -D /dev/stdout -H "Accept: application/json" ' \
+ '-H "Content-Type: application/json" ' \
+ '-X POST -d "{{\\"enable\\":{start}}}" ' \
+ 'http://{mgmt_ip}:{mgmt_port}/api/v1/pong/adminstatus/state'. \
+ format(
+ mgmt_ip=mgmt_ip,
+ mgmt_port=mgmt_port,
+ start=start)
+
+ logger.debug("Executing cmd: %s", cmd)
+ proc = subprocess.Popen(cmd, shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+
+ proc.wait()
+ logger.debug("Process: {}".format(proc))
+
+ rc = proc.returncode
+
+ if rc == 0:
+ # Check if we got 200 OK
+ resp = proc.stdout.read().decode()
+ if 'HTTP/1.1 200 OK' not in resp:
+ logger._log.error("Got error response: {}".format(resp))
+ rc = 1
+
+ return rc
+
+
+def main(argv=sys.argv[1:]):
+ try:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
+ parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
+ args = parser.parse_args()
+
+ run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
+ if not os.path.exists(run_dir):
+ os.makedirs(run_dir)
+ log_file = "{}/pong_start_stop-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
+
+ # logging.basicConfig(filename=log_file, level=logging.DEBUG)
+ logger = logging.getLogger('pong-start-stop')
+ logger.setLevel(logging.DEBUG)
+
+ fh = logging.FileHandler(log_file)
+ fh.setLevel(logging.DEBUG)
+
+ ch = logging.StreamHandler()
+ if args.verbose:
+ ch.setLevel(logging.DEBUG)
+ else:
+ ch.setLevel(logging.INFO)
+
+ # create formatter and add it to the handlers
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ fh.setFormatter(formatter)
+ ch.setFormatter(formatter)
+ logger.addHandler(fh)
+ logger.addHandler(ch)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+ try:
+ logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
+ yaml_str = args.yaml_cfg_file.read()
+ yaml_cfg = yaml.load(yaml_str)
+ logger.debug("Input YAML: {}".format(yaml_cfg))
+
+ rc = pong_start_stop(yaml_cfg, logger)
+ logger.info("Return code: {}".format(rc))
+ sys.exit(rc)
+
+ except Exception as e:
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/ping_pong_ns/rift/mano/examples/primitive_test.py b/examples/ping_pong_ns/rift/mano/examples/primitive_test.py
new file mode 100755
index 0000000..6c75543
--- /dev/null
+++ b/examples/ping_pong_ns/rift/mano/examples/primitive_test.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+
+############################################################################
+# Copyright 2017 RIFT.IO Inc #
+# #
+# 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 argparse
+import os
+import sys
+import random
+import paramiko
+import yaml
+from glob import glob
+
+
+def copy_file_ssh_sftp(server, remote_dir, remote_file, local_file):
+ """Copy file to VM."""
+ sshclient = paramiko.SSHClient()
+ sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+ sshclient.load_system_host_keys(filename="/dev/null")
+ sshclient.connect(server, username="fedora", password="fedora")
+ sftpclient = sshclient.open_sftp()
+ sftpclient.put(local_file, remote_dir + '/' + remote_file)
+ sshclient.close()
+
+
+def get_full_path(file_name, production_launchpad=True):
+ """Return the full path for the init cfg file."""
+ mpath = os.path.join(
+ os.getenv('RIFT_INSTALL'), 'var', 'rift')
+ if not production_launchpad:
+ launchpad_folder = glob('{}/*mgmt-vm-lp-2'.format(mpath))[0]
+ else:
+ launchpad_folder = ''
+ mpath = os.path.join(
+ os.getenv('RIFT_INSTALL'), 'var', 'rift', launchpad_folder,
+ 'launchpad', 'packages', 'vnfd', 'default')
+ vnfd_folder = random.choice(
+ [x for x in os.listdir(mpath) if os.path.isdir(
+ os.path.join(mpath, x))])
+ full_path = glob(
+ '{}/{}/cloud_init/{}'.format(mpath, vnfd_folder, file_name))[0]
+ file_name = os.path.basename(os.path.normpath(full_path))
+ return full_path, file_name
+
+
+def exists_remote(host, path):
+ """Test if a file exists at path on a host accessible with SSH."""
+ ssh = paramiko.SSHClient()
+ ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+ try:
+ ssh.connect(host, username="fedora", password="fedora")
+ sftp = ssh.open_sftp()
+ try:
+ sftp.stat(path)
+ except Exception:
+ raise Exception('Transfered file not found on the remote host')
+ ssh.close()
+ except paramiko.SSHException:
+ print("Connection Error")
+
+
+def primitive_test(yaml_cfg):
+ """Transfer a cloud init file from the vnfd descriptor package.
+
+ Verify that the file is transfered.
+ """
+ for index, vnfr in yaml_cfg['vnfr_data_map'].items():
+ vnfd_ip = vnfr['mgmt_interface']['ip_address']
+ file_name = '*_cloud_init.cfg'
+ local_file, file_name = get_full_path(file_name)
+ copy_file_ssh_sftp(vnfd_ip, '/tmp/', file_name, local_file)
+ remote_file_path = os.path.join(
+ '/'
+ 'tmp',
+ file_name)
+ exists_remote(vnfd_ip, remote_file_path)
+
+
+def main(argv=sys.argv[1:]):
+ """Main."""
+ try:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
+ parser.add_argument(
+ "-q", "--quiet", dest="verbose",
+ action="store_false")
+ args = parser.parse_args()
+
+ except Exception as e:
+ print("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+ try:
+ yaml_str = args.yaml_cfg_file.read()
+ yaml_cfg = yaml.load(yaml_str)
+
+ primitive_test(yaml_cfg)
+
+ except Exception as e:
+ print("Exception: {}".format(e))
+ raise e
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/ping_pong_ns/rift/mano/examples/start_traffic.py b/examples/ping_pong_ns/rift/mano/examples/start_traffic.py
index af6f62f..a65321f 100755
--- a/examples/ping_pong_ns/rift/mano/examples/start_traffic.py
+++ b/examples/ping_pong_ns/rift/mano/examples/start_traffic.py
@@ -31,8 +31,8 @@
'''Use curl and set admin status to enable on pong and ping vnfs'''
def enable_service(mgmt_ip, port, vnf_type):
- curl_cmd = 'curl -D /dev/stdout -H "Accept: application/vnd.yang.data' \
- '+xml" -H "Content-Type: application/vnd.yang.data+json" ' \
+ curl_cmd = 'curl -D /dev/null -H "Accept: application/json" ' \
+ '-H "Content-Type: application/json" ' \
'-X POST -d "{{\\"enable\\":true}}" http://{mgmt_ip}:' \
'{mgmt_port}/api/v1/{vnf_type}/adminstatus/state'. \
format(
@@ -40,8 +40,39 @@
mgmt_port=port,
vnf_type=vnf_type)
- logger.debug("Executing cmd: %s", curl_cmd)
- subprocess.check_call(curl_cmd, shell=True)
+ count = 0
+ delay = 10
+ max_tries = 10
+ while True:
+ count += 1
+
+ logger.debug("Executing cmd: %s", curl_cmd)
+ proc = subprocess.Popen(curl_cmd, shell=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+
+ proc.wait()
+ logger.debug("Process: {}".format(proc))
+
+ if proc.returncode == 0:
+ # Check if response is 200 OK
+ logger.info("Got success response")
+ break
+
+ elif proc.returncode == 7:
+ # Connection timeout
+ if count >= max_tries:
+ logger.error("Connect failed for {}. Failing".format(count))
+ break
+ # Try after delay
+ time.sleep(delay)
+ else:
+ #Exit the loop incase of errors other than connection timeout and response ok
+ err_resp = proc.stderr.read().decode()
+ logger.error("Got error response: {}".format(err_resp))
+ return proc.returncode
+
+ return proc.returncode
# Enable pong service first
for index, vnfr in yaml_cfg['vnfr'].items():
@@ -51,11 +82,16 @@
if 'pong_vnfd' in vnfr['name']:
vnf_type = 'pong'
port = 18889
- enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
+ rc = enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
+ if rc != 0:
+ logger.error("Enable service for pong failed: {}".
+ format(rc))
+ return rc
break
+
# Add a delay to provide pong port to come up
- time.sleep(0.1)
+ time.sleep(1)
# Enable ping service next
for index, vnfr in yaml_cfg['vnfr'].items():
@@ -65,9 +101,12 @@
if 'ping_vnfd' in vnfr['name']:
vnf_type = 'ping'
port = 18888
- enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
+ rc = enable_service(vnfr['mgmt_ip_address'], port, vnf_type)
break
+ return rc
+
+
def main(argv=sys.argv[1:]):
try:
parser = argparse.ArgumentParser()
@@ -79,14 +118,14 @@
if not os.path.exists(run_dir):
os.makedirs(run_dir)
log_file = "{}/ping_pong_start_traffic-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
- logging.basicConfig(filename=log_file, level=logging.DEBUG)
- logger = logging.getLogger()
- except Exception as e:
- print("Exception in {}: {}".format(__file__, e))
- sys.exit(1)
+ # logging.basicConfig(filename=log_file, level=logging.DEBUG)
+ logger = logging.getLogger('ping-pong-start-traffic')
+ logger.setLevel(logging.DEBUG)
- try:
+ fh = logging.FileHandler(log_file)
+ fh.setLevel(logging.DEBUG)
+
ch = logging.StreamHandler()
if args.verbose:
ch.setLevel(logging.DEBUG)
@@ -95,24 +134,28 @@
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ fh.setFormatter(formatter)
ch.setFormatter(formatter)
+ logger.addHandler(fh)
logger.addHandler(ch)
except Exception as e:
- logger.exception(e)
- raise e
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
try:
+ logger.debug("Input file: {}".format(args.yaml_cfg_file.name))
yaml_str = args.yaml_cfg_file.read()
- # logger.debug("Input YAML file:\n{}".format(yaml_str))
yaml_cfg = yaml.load(yaml_str)
logger.debug("Input YAML: {}".format(yaml_cfg))
- start_traffic(yaml_cfg, logger)
+ rc = start_traffic(yaml_cfg, logger)
+ logger.info("Return code: {}".format(rc))
+ sys.exit(rc)
except Exception as e:
- logger.exception(e)
- raise e
+ logger.exception("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
if __name__ == "__main__":
main()
diff --git a/examples/ping_pong_ns/rift/mano/examples/stop_traffic.py b/examples/ping_pong_ns/rift/mano/examples/stop_traffic.py
new file mode 100755
index 0000000..8161f9d
--- /dev/null
+++ b/examples/ping_pong_ns/rift/mano/examples/stop_traffic.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+
+############################################################################
+# Copyright 2016 RIFT.IO Inc #
+# #
+# 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 argparse
+import logging
+import os
+import subprocess
+import sys
+import time
+
+import yaml
+
+
+def stop_traffic(yaml_cfg, logger):
+ '''Use curl and set admin status to enable on pong and ping vnfs'''
+
+ def disable_service(mgmt_ip, port, vnf_type):
+ curl_cmd = 'curl -D /dev/null -H "Accept: application/json" ' \
+ '-H "Content-Type: application/json" ' \
+ '-X POST -d "{{\\"enable\\":false}}" http://{mgmt_ip}:' \
+ '{mgmt_port}/api/v1/{vnf_type}/adminstatus/state'. \
+ format(
+ mgmt_ip=mgmt_ip,
+ mgmt_port=port,
+ vnf_type=vnf_type)
+
+ logger.debug("Executing cmd: %s", curl_cmd)
+ subprocess.check_call(curl_cmd, shell=True)
+
+ # Disable ping service first
+ for index, vnfr in yaml_cfg['vnfr'].items():
+ logger.debug("VNFR {}: {}".format(index, vnfr))
+
+ # Check if it is pong vnf
+ if 'ping_vnfd' in vnfr['name']:
+ vnf_type = 'ping'
+ port = 18888
+ disable_service(vnfr['mgmt_ip_address'], port, vnf_type)
+ break
+
+ # Add a delay
+ time.sleep(0.1)
+
+ # Disable pong service next
+ for index, vnfr in yaml_cfg['vnfr'].items():
+ logger.debug("VNFR {}: {}".format(index, vnfr))
+
+ # Check if it is pong vnf
+ if 'pong_vnfd' in vnfr['name']:
+ vnf_type = 'pong'
+ port = 18889
+ disable_service(vnfr['mgmt_ip_address'], port, vnf_type)
+ break
+
+def main(argv=sys.argv[1:]):
+ try:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("yaml_cfg_file", type=argparse.FileType('r'))
+ parser.add_argument("-q", "--quiet", dest="verbose", action="store_false")
+ args = parser.parse_args()
+
+ run_dir = os.path.join(os.environ['RIFT_INSTALL'], "var/run/rift")
+ if not os.path.exists(run_dir):
+ os.makedirs(run_dir)
+ log_file = "{}/ping_pong_stop_traffic-{}.log".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
+ logging.basicConfig(filename=log_file, level=logging.DEBUG)
+ logger = logging.getLogger()
+
+ except Exception as e:
+ print("Exception in {}: {}".format(__file__, e))
+ sys.exit(1)
+
+ try:
+ ch = logging.StreamHandler()
+ if args.verbose:
+ ch.setLevel(logging.DEBUG)
+ else:
+ ch.setLevel(logging.INFO)
+
+ # create formatter and add it to the handlers
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ ch.setFormatter(formatter)
+ logger.addHandler(ch)
+
+ except Exception as e:
+ logger.exception(e)
+ raise e
+
+ try:
+ yaml_str = args.yaml_cfg_file.read()
+ # logger.debug("Input YAML file:\n{}".format(yaml_str))
+ yaml_cfg = yaml.load(yaml_str)
+ logger.debug("Input YAML: {}".format(yaml_cfg))
+
+ stop_traffic(yaml_cfg, logger)
+
+ except Exception as e:
+ logger.exception(e)
+ raise e
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/ping_pong_ns/stand_up_ping_pong b/examples/ping_pong_ns/stand_up_ping_pong
index a8e5e55..f6b8f85 100644
--- a/examples/ping_pong_ns/stand_up_ping_pong
+++ b/examples/ping_pong_ns/stand_up_ping_pong
@@ -42,12 +42,12 @@
fi
}
-echo -n "wait for system"
-while ! system_is_up
-do
- echo -n "."
- sleep 5s
-done
+#echo -n "wait for system"
+#while ! system_is_up
+#do
+# echo -n "."
+# sleep 5s
+#done
echo "system is up"
@@ -121,8 +121,9 @@
echo "must supply transaction id to wait for"
exit -1
fi
-
- response=$(curl --silent --insecure https://${lp_ip}:4567/api/upload/${transaction_id}/state)
+
+ project="default"
+ response=$(curl --silent --insecure https://${lp_ip}:8008/api/operational/project/${project}/create-jobs/job/${transaction_id})
transaction_state=$(echo ${response} | awk -F "status" '{print $2}' | awk '{print $2}')
transaction_state=${transaction_state:1:-2}