Remove config template from use in ping-pong 71/1671/1
authorChamarty <ravi.chamarty@riftio.com>
Mon, 24 Apr 2017 20:32:31 +0000 (16:32 -0400)
committerChamarty <ravi.chamarty@riftio.com>
Mon, 24 Apr 2017 20:32:31 +0000 (16:32 -0400)
Change-Id: If569a63b75fb131a13f595f88d7300989583f346
Signed-off-by: Chamarty <ravi.chamarty@riftio.com>
examples/ping_pong_ns/CMakeLists.txt
examples/ping_pong_ns/rift/mano/examples/ping_initial_config.py [new file with mode: 0755]
examples/ping_pong_ns/rift/mano/examples/ping_pong_nsd.py
examples/ping_pong_ns/rift/mano/examples/pong_initial_config.py [new file with mode: 0755]
rwcm/plugins/rwconman/rift/tasklets/rwconmantasklet/rwconman_config.py

index 34f7a03..65ace57 100644 (file)
@@ -15,7 +15,7 @@
 #
 # Author(s): Anil Gunturu
 # Creation Date: 03/26/2014
-# 
+
 
 cmake_minimum_required(VERSION 2.8)
 
@@ -34,12 +34,21 @@ set(PACKAGE_OUTPUT
   ${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}/pong_vnfd_with_epa.tar.gz
+  ${CMAKE_CURRENT_BINARY_DIR}/ping_vnfd_with_image.tar.gz
+  ${CMAKE_CURRENT_BINARY_DIR}/pong_vnfd_with_image.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_initial_config.py
+       ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/pong_initial_config.py
+       ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/ping_set_rate.py
+       ${CMAKE_CURRENT_SOURCE_DIR}/rift/mano/examples/start_traffic.py
   )
 
 add_custom_target(ping_pong_pkg_gen ALL
@@ -67,13 +76,14 @@ rift_python_install_tree(
   COMPONENT ${PKG_LONG_NAME}
   FILES
     rift/mano/examples/ping_pong_nsd.py
-    rift/mano/examples/start_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/start_traffic.py
   )
 
 install(
   PROGRAMS
-    rift/mano/examples/ping_config.py
     stand_up_ping_pong
   DESTINATION usr/bin
   COMPONENT ${PKG_LONG_NAME}
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 (executable)
index 0000000..35ae308
--- /dev/null
@@ -0,0 +1,204 @@
+#!/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 cmd: %s", curl_cmd)
+        proc = subprocess.Popen(curl_cmd, shell=True,
+                                stdout=subprocess.PIPE,
+                                stderr=subprocess.PIPE)
+
+        proc.wait()
+        logger.debug("Process: {}".format(proc))
+
+        return proc.returncode 
+
+    # 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/stdout -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 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: {}".format(proc))
+
+        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)
+
+    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()
index ef2dd90..e0a6848 100755 (executable)
@@ -170,6 +170,10 @@ class VirtualNetworkFunction(ManoDescriptor):
             monp.http_endpoint_ref = endpoint
             vnfd.monitoring_param.append(monp)
 
+        if 'pong_' in self.name:
+            self.add_pong_config()
+        else:
+            self.add_ping_config() 
 
         for i in range(num_vms):
             # VDU Specification
@@ -298,6 +302,46 @@ class VirtualNetworkFunction(ManoDescriptor):
                     member_vdu.member_vdu_ref = vdu.id
 
 
+    def add_ping_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 = 'bash'
+
+        # Add initial config primitive
+        vnf_config.create_initial_config_primitive()
+        init_config = VnfdYang.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
+
+        # Select "script" configuration
+        vnf_config.script.script_type = 'bash'
+
+        # Add initial config primitive
+        vnf_config.create_initial_config_primitive()
+        init_config = VnfdYang.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)
         if not os.path.exists(dirpath):
@@ -325,6 +369,8 @@ class VirtualNetworkFunction(ManoDescriptor):
         with open(script_file, "w") as f:
             f.write("{}".format(cfg))
 
+        self.add_config_scripts(outdir)
+
         # Copy the vnf_init_config script
         if self.use_vnf_init_conf and ('ping' in self.name):
             script_name = 'ping_set_rate.py'
@@ -340,6 +386,31 @@ class VirtualNetworkFunction(ManoDescriptor):
             os.makedirs(dest_path, exist_ok=True)
 
             shutil.copy2(script_src, dest_path)
+   
+    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')
+                script_src = os.path.join(src_path, script_name)
+
+            shutil.copy2(script_src, dest_path) 
 
 
 class NetworkService(ManoDescriptor):
@@ -349,209 +420,7 @@ class NetworkService(ManoDescriptor):
         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
-
-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):
+    def default_config(self, vnfd):
         vnf_config = vnfd.vnfd.vnf_configuration
 
         vnf_config.config_attributes.config_priority = 0
@@ -559,38 +428,8 @@ exit 0
 
         # Select "script" configuration
         vnf_config.script.script_type = 'bash'
+        vnf_config.config_template = "#!/bin/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
@@ -719,8 +558,7 @@ exit 0
                     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)
+                self.default_config(vnfd)
                 member_vnf_index += 1
 
         # Enable config primitives if either mano_ut or
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 (executable)
index 0000000..e0d2836
--- /dev/null
@@ -0,0 +1,173 @@
+#!/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/stdout -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 = 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: {}".format(proc))
+
+        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)
+
+    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()
index 4b010b6..9e8b944 100644 (file)
@@ -30,11 +30,14 @@ from gi.repository import (
 )
 
 import rift.tasklets
+import rift.package.script
+import rift.package.store
 
 from . import rwconman_conagent as conagent
 from . import RiftCM_rpc
 from . import riftcm_config_plugin
 
+
 if sys.version_info < (3, 4, 4):
     asyncio.ensure_future = asyncio.async
 
@@ -792,37 +795,32 @@ class ConfigManagerConfig(object):
                             format(inp_file, e))
 
     def get_script_file(self, script_name, d_name, d_id, d_type):
-          # Get the full path to the script
-          script = ''
-          # If script name starts with /, assume it is full path
-          if script_name[0] == '/':
-              # The script has full path, use as is
-              script = script_name
-          else:
-              script = os.path.join(os.environ['RIFT_ARTIFACTS'],
-                                    'launchpad/packages',
-                                    d_type,
-                                    d_id,
-                                    d_name,
-                                    'scripts',
-                                    script_name)
-              self._log.debug("Checking for script at %s", script)
-              if not os.path.exists(script):
-                  self._log.warning("Did not find script %s", script)
-                  script = os.path.join(os.environ['RIFT_INSTALL'],
-                                        'usr/bin',
-                                        script_name)
-
-              # Seen cases in jenkins, where the script execution fails
-              # with permission denied. Setting the permission on script
-              # to make sure it has execute permission
-              perm = os.stat(script).st_mode
-              if not (perm  &  stat.S_IXUSR):
-                  self._log.warning("NSR/VNFR {} initial config script {} " \
+        if d_type == "vnfd":
+            package_store = rift.package.store.VnfdPackageFilesystemStore(self._log)
+            package_store.refresh()
+        elif d_type == "nsd":
+            package_store = rift.package.store.NsdPackageFilesystemStore(self._log)
+            package_store.refresh()
+        else:
+            raise
+        script_extractor = rift.package.script.PackageScriptExtractor(self._log)
+        script = script_extractor.get_extracted_script_path(d_id, script_name)
+
+        self._log.debug("Checking for script at %s", script)
+        if not os.path.exists(script):
+            self._log.warning("Did not find script %s", script)
+            return
+
+        # Seen cases in jenkins, where the script execution fails
+        # with permission denied. Setting the permission on script
+        # to make sure it has execute permission
+        perm = os.stat(script).st_mode
+        if not (perm  &  stat.S_IXUSR):
+            self._log.warning("NSR/VNFR {} script {} " \
                                     "without execute permission: {}".
                                     format(d_name, script, perm))
-                  os.chmod(script, perm | stat.S_IXUSR)
-              return script
+            os.chmod(script, perm | stat.S_IXUSR)
+        return script
 
     @asyncio.coroutine
     def process_ns_initial_config(self, nsr_obj):
@@ -854,11 +852,11 @@ class ConfigManagerConfig(object):
         vnf_cfg = vnfd.vnf_configuration
 
         for conf in vnf_cfg.initial_config_primitive:
-                self._log.debug("VNFR {} initial config: {}".
-                                format(vnfr_name, conf))
+                self._log.debug("VNFR {} initial config: {} for vnfd id {}".
+                                format(vnfr_name, conf, vnfd.id))
 
                 if not conf.user_defined_script:
-                    self._log.debug("VNFR {} did not fine user defined script: {}".
+                    self._log.debug("VNFR {} did not find user defined script: {}".
                                     format(vnfr_name, conf))
                     continue