RIFT OSM R1 Initial Submission
Signed-off-by: Jeremy Mordkoff <jeremy.mordkoff@riftio.com>
diff --git a/models/openmano/CMakeLists.txt b/models/openmano/CMakeLists.txt
new file mode 100644
index 0000000..ad0cdc8
--- /dev/null
+++ b/models/openmano/CMakeLists.txt
@@ -0,0 +1,27 @@
+#
+# 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.
+#
+# Author(s): Anil Gunturu
+# Creation Date: 2014/12/11
+#
+
+cmake_minimum_required(VERSION 2.8)
+
+set(subdirs
+ bin
+ src
+ python
+ )
+rift_add_subdirs(SUBDIR_LIST ${subdirs})
diff --git a/models/openmano/bin/CMakeLists.txt b/models/openmano/bin/CMakeLists.txt
new file mode 100644
index 0000000..895823c
--- /dev/null
+++ b/models/openmano/bin/CMakeLists.txt
@@ -0,0 +1,12 @@
+# RIFT_IO_STANDARD_CMAKE_COPYRIGHT_HEADER(BEGIN)
+# Author(s): Austin Cormier
+# Creation Date: 1/11/2015
+# RIFT_IO_STANDARD_CMAKE_COPYRIGHT_HEADER(END)
+
+install(
+ PROGRAMS
+ openmano
+ openmano_cleanup.sh
+ DESTINATION usr/bin
+ COMPONENT ${PKG_LONG_NAME}
+)
diff --git a/models/openmano/bin/openmano b/models/openmano/bin/openmano
new file mode 100755
index 0000000..3ea0654
--- /dev/null
+++ b/models/openmano/bin/openmano
@@ -0,0 +1,1401 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# PYTHON_ARGCOMPLETE_OK
+
+##
+# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
+# This file is part of openmano
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+#
+# For those usages not covered by the Apache License, Version 2.0 please
+# contact with: nfvlabs@tid.es
+##
+
+'''
+openmano client used to interact with openmano-server (openmanod)
+'''
+__author__="Alfonso Tierno, Gerardo Garcia"
+__date__ ="$09-oct-2014 09:09:48$"
+__version__="0.4.3-r467"
+version_date="Mar 2016"
+
+from argcomplete.completers import FilesCompleter
+import os
+import argparse
+import argcomplete
+import requests
+import json
+import yaml
+import logging
+#from jsonschema import validate as js_v, exceptions as js_e
+
+class ArgumentParserError(Exception): pass
+
+class OpenmanoCLIError(Exception): pass
+
+class ThrowingArgumentParser(argparse.ArgumentParser):
+ def error(self, message):
+ print "Error: %s" %message
+ print
+ self.print_usage()
+ #self.print_help()
+ print
+ print "Type 'openmano -h' for help"
+ raise ArgumentParserError
+
+
+def config(args):
+ print "OPENMANO_HOST: %s" %mano_host
+ print "OPENMANO_PORT: %s" %mano_port
+ if args.n:
+ logger.debug("resolving tenant and datacenter names")
+ mano_tenant_id = "None"
+ mano_tenant_name = "None"
+ mano_datacenter_id = "None"
+ mano_datacenter_name = "None"
+ try:
+ mano_tenant_id = _get_item_uuid("tenants", mano_tenant)
+ URLrequest = "http://%s:%s/openmano/tenants/%s" %(mano_host, mano_port, mano_tenant_id)
+ mano_response = requests.get(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ content = mano_response.json()
+ mano_tenant_name = content["tenant"]["name"]
+ URLrequest = "http://%s:%s/openmano/%s/datacenters/%s" %(mano_host, mano_port, mano_tenant_id, mano_datacenter)
+ mano_response = requests.get(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ content = mano_response.json()
+ if "error" not in content:
+ mano_datacenter_id = content["datacenter"]["uuid"]
+ mano_datacenter_name = content["datacenter"]["name"]
+ except OpenmanoCLIError:
+ pass
+ print "OPENMANO_TENANT: %s" %mano_tenant
+ print " Id: %s" %mano_tenant_id
+ print " Name: %s" %mano_tenant_name
+ print "OPENMANO_DATACENTER: %s" %str (mano_datacenter)
+ print " Id: %s" %mano_datacenter_id
+ print " Name: %s" %mano_datacenter_name
+ else:
+ print "OPENMANO_TENANT: %s" %mano_tenant
+ print "OPENMANO_DATACENTER: %s" %str (mano_datacenter)
+
+def _print_verbose(mano_response, verbose_level=0):
+ content = mano_response.json()
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ if type(content)!=dict or len(content)!=1:
+ #print "Non expected format output"
+ print str(content)
+ return result
+
+ val=content.values()[0]
+ if type(val)==str:
+ print val
+ return result
+ elif type(val) == list:
+ content_list = val
+ elif type(val)==dict:
+ content_list = [val]
+ else:
+ #print "Non expected dict/list format output"
+ print str(content)
+ return result
+
+ #print content_list
+ if verbose_level==None:
+ verbose_level=0
+ if verbose_level >= 3:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+
+ if mano_response.status_code == 200:
+ for content in content_list:
+ if "uuid" in content:
+ uuid = content['uuid']
+ elif "id" in content:
+ uuid = content['id']
+ elif "vim_id" in content:
+ uuid = content['vim_id']
+ myoutput = "%s %s" %(uuid.ljust(38),content['name'].ljust(20))
+ if "status" in content:
+ myoutput += " " + content['status'].ljust(20)
+ elif "enabled" in content and not content["enabled"]:
+ myoutput += " enabled=False".ljust(20)
+ if verbose_level >=1:
+ if 'created_at' in content:
+ myoutput += " " + content['created_at'].ljust(20)
+ if verbose_level >=2:
+ new_line='\n'
+ if 'type' in content and content['type']!=None:
+ myoutput += new_line + " Type: " + content['type'].ljust(29)
+ new_line=''
+ if 'description' in content and content['description']!=None:
+ myoutput += new_line + " Description: " + content['description'].ljust(20)
+ print myoutput
+ else:
+ print content['error']['description']
+ return result
+
+def parser_json_yaml(file_name):
+ try:
+ f = file(file_name, "r")
+ text = f.read()
+ f.close()
+ except Exception as e:
+ return (False, str(e))
+
+ #Read and parse file
+ if file_name[-5:]=='.yaml' or file_name[-4:]=='.yml' or (file_name[-5:]!='.json' and '\t' not in text):
+ try:
+ config = yaml.load(text)
+ except yaml.YAMLError as exc:
+ error_pos = ""
+ if hasattr(exc, 'problem_mark'):
+ mark = exc.problem_mark
+ error_pos = " at line:%s column:%s" % (mark.line+1, mark.column+1)
+ return (False, "Error loading file '"+file_name+"' yaml format error" + error_pos)
+ else: #json
+ try:
+ config = json.loads(text)
+ except Exception as e:
+ return (False, "Error loading file '"+file_name+"' json format error " + str(e) )
+
+ return True, config
+
+def _load_file_or_yaml(content):
+ '''
+ 'content' can be or a yaml/json file or a text containing a yaml/json text format
+ This function autodetect, trying to load and parse the file,
+ if fails trying to parse the 'content' text
+ Returns the dictionary once parsed, or print an error and finish the program
+ '''
+ #Check config file exists
+ if os.path.isfile(content):
+ r,payload = parser_json_yaml(content)
+ if not r:
+ print payload
+ exit(-1)
+ elif "{" in content or ":" in content:
+ try:
+ payload = yaml.load(content)
+ except yaml.YAMLError as exc:
+ error_pos = ""
+ if hasattr(exc, 'problem_mark'):
+ mark = exc.problem_mark
+ error_pos = " at position: (%s:%s)" % (mark.line+1, mark.column+1)
+ print "Error loading yaml/json text"+error_pos
+ exit (-1)
+ else:
+ print "'%s' is neither a valid file nor a yaml/json content" % content
+ exit(-1)
+ return payload
+
+def _get_item_uuid(item, item_name_id, tenant=None):
+ if tenant:
+ URLrequest = "http://%s:%s/openmano/%s/%s" %(mano_host, mano_port, tenant, item)
+ else:
+ URLrequest = "http://%s:%s/openmano/%s" %(mano_host, mano_port, item)
+ mano_response = requests.get(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ content = mano_response.json()
+ #print content
+ found = 0
+ for i in content[item]:
+ if i["uuid"] == item_name_id:
+ return item_name_id
+ if i["name"] == item_name_id:
+ uuid = i["uuid"]
+ found += 1
+ if found == 0:
+ raise OpenmanoCLIError("No %s found with name/uuid '%s'" %(item[:-1], item_name_id))
+ elif found > 1:
+ raise OpenmanoCLIError("%d %s found with name '%s'. uuid must be used" %(found, item, item_name_id))
+ return uuid
+#
+# def check_valid_uuid(uuid):
+# id_schema = {"type" : "string", "pattern": "^[a-fA-F0-9]{8}(-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}$"}
+# try:
+# js_v(uuid, id_schema)
+# return True
+# except js_e.ValidationError:
+# return False
+
+def _get_tenant(tenant_name_id = None):
+ if not tenant_name_id:
+ tenant_name_id = mano_tenant
+ if not mano_tenant:
+ raise OpenmanoCLIError("'OPENMANO_TENANT' environment variable is not set")
+ return _get_item_uuid("tenants", tenant_name_id)
+
+def _get_datacenter(datacenter_name_id = None, tenant = "any"):
+ if not datacenter_name_id:
+ datacenter_name_id = mano_datacenter
+ if not datacenter_name_id:
+ raise OpenmanoCLIError("neither 'OPENMANO_DATACENTER' environment variable is set nor --datacenter option is used")
+ return _get_item_uuid("datacenters", datacenter_name_id, tenant)
+
+def vnf_create(args):
+ #print "vnf-create",args
+ headers_req = {'Accept': 'application/json', 'content-type': 'application/json'}
+ tenant = _get_tenant()
+ myvnf = _load_file_or_yaml(args.file)
+
+ if args.name or args.description or args.image_path:
+ #print args.name
+ try:
+ if args.name:
+ myvnf['vnf']['name'] = args.name
+ if args.description:
+ myvnf['vnf']['description'] = args.description
+ if args.image_path:
+ index=0
+ for image_path_ in args.image_path.split(","):
+ #print "image-path", image_path_
+ myvnf['vnf']['VNFC'][index]['VNFC image']=image_path_
+ index=index+1
+ except (KeyError, TypeError), e:
+ if str(e)=='vnf': error_pos= "missing field 'vnf'"
+ elif str(e)=='name': error_pos= "missing field 'vnf':'name'"
+ elif str(e)=='description': error_pos= "missing field 'vnf':'description'"
+ elif str(e)=='VNFC': error_pos= "missing field 'vnf':'VNFC'"
+ elif str(e)==str(index): error_pos= "field 'vnf':'VNFC' must be an array"
+ elif str(e)=='VNFC image': error_pos= "missing field 'vnf':'VNFC'['VNFC image']"
+ else: error_pos="wrong format"
+ print "Wrong VNF descriptor: " + error_pos
+ return -1
+ payload_req = json.dumps(myvnf)
+
+ #print payload_req
+
+ URLrequest = "http://%s:%s/openmano/%s/vnfs" %(mano_host, mano_port, tenant)
+ logger.debug("openmano request: %s", payload_req)
+ mano_response = requests.post(URLrequest, headers = headers_req, data=payload_req)
+ logger.debug("openmano response: %s", mano_response.text )
+
+ return _print_verbose(mano_response, args.verbose)
+
+def vnf_list(args):
+ #print "vnf-list",args
+ if args.all:
+ tenant = "any"
+ else:
+ tenant = _get_tenant()
+ if args.name:
+ toshow = _get_item_uuid("vnfs", args.name, tenant)
+ URLrequest = "http://%s:%s/openmano/%s/vnfs/%s" %(mano_host, mano_port, tenant, toshow)
+ else:
+ URLrequest = "http://%s:%s/openmano/%s/vnfs" %(mano_host, mano_port, tenant)
+ mano_response = requests.get(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if args.verbose==None:
+ args.verbose=0
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ if mano_response.status_code == 200:
+ if not args.name:
+ if args.verbose >= 3:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+ if len(content['vnfs']) == 0:
+ print "No VNFs were found."
+ return 404 #HTTP_Not_Found
+ for vnf in content['vnfs']:
+ myoutput = "%s %s" %(vnf['uuid'].ljust(38),vnf['name'].ljust(20))
+ if args.verbose >=1:
+ myoutput = "%s %s" %(myoutput, vnf['created_at'].ljust(20))
+ print myoutput
+ if args.verbose >=2:
+ print " Description: %s" %vnf['description']
+ print " VNF descriptor file: %s" %vnf['path']
+ else:
+ if args.verbose:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+ vnf = content['vnf']
+ print "%s %s %s" %(vnf['uuid'].ljust(38),vnf['name'].ljust(20), vnf['created_at'].ljust(20))
+ print " Description: %s" %vnf['description']
+ #print " VNF descriptor file: %s" %vnf['path']
+ print " VMs:"
+ for vm in vnf['VNFC']:
+ #print " %s %s %s" %(vm['name'].ljust(20), vm['uuid'].ljust(38), vm['description'].ljust(30))
+ print " %s %s" %(vm['name'].ljust(20), vm['description'])
+ if len(vnf['nets'])>0:
+ print " Internal nets:"
+ for net in vnf['nets']:
+ print " %s %s" %(net['name'].ljust(20), net['description'])
+ if len(vnf['external-connections'])>0:
+ print " External interfaces:"
+ for interface in vnf['external-connections']:
+ print " %s %s %s %s" %(interface['external_name'].ljust(20), interface['vm_name'].ljust(20), interface['internal_name'].ljust(20), \
+ interface['vpci'].ljust(14))
+ else:
+ print content['error']['description']
+ if args.verbose:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+
+def vnf_delete(args):
+ #print "vnf-delete",args
+ if args.all:
+ tenant = "any"
+ else:
+ tenant = _get_tenant()
+ todelete = _get_item_uuid("vnfs", args.name, tenant=tenant)
+ if not args.force:
+ r = raw_input("Delete VNF %s (y/N)? " %(todelete))
+ if not (len(r)>0 and r[0].lower()=="y"):
+ return 0
+ URLrequest = "http://%s:%s/openmano/%s/vnfs/%s" %(mano_host, mano_port, tenant, todelete)
+ mano_response = requests.delete(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if mano_response.status_code == 200:
+ print content['result']
+ else:
+ print content['error']['description']
+ return result
+
+def scenario_create(args):
+ #print "scenario-create",args
+ tenant = _get_tenant()
+ headers_req = {'content-type': 'application/yaml'}
+ myscenario = _load_file_or_yaml(args.file)
+
+ if args.name:
+ myscenario['name'] = args.name
+ if args.description:
+ myscenario['description'] = args.description
+ payload_req = yaml.safe_dump(myscenario, explicit_start=True, indent=4, default_flow_style=False, tags=False, encoding='utf-8', allow_unicode=True)
+
+ #print payload_req
+
+ URLrequest = "http://%s:%s/openmano/%s/scenarios" %(mano_host, mano_port, tenant)
+ logger.debug("openmano request: %s", payload_req)
+ mano_response = requests.post(URLrequest, headers = headers_req, data=payload_req)
+ logger.debug("openmano response: %s", mano_response.text )
+ return _print_verbose(mano_response, args.verbose)
+
+def scenario_list(args):
+ #print "scenario-list",args
+ if args.all:
+ tenant = "any"
+ else:
+ tenant = _get_tenant()
+ if args.name:
+ toshow = _get_item_uuid("scenarios", args.name, tenant)
+ URLrequest = "http://%s:%s/openmano/%s/scenarios/%s" %(mano_host, mano_port, tenant, toshow)
+ else:
+ URLrequest = "http://%s:%s/openmano/%s/scenarios" %(mano_host, mano_port, tenant)
+ mano_response = requests.get(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if args.verbose==None:
+ args.verbose=0
+
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ if mano_response.status_code == 200:
+ if not args.name:
+ if args.verbose >= 3:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+ if len(content['scenarios']) == 0:
+ print "No scenarios were found."
+ return 404 #HTTP_Not_Found
+ for scenario in content['scenarios']:
+ myoutput = "%s %s" %(scenario['uuid'].ljust(38),scenario['name'].ljust(20))
+ if args.verbose >=1:
+ myoutput = "%s %s" %(myoutput, scenario['created_at'].ljust(20))
+ print myoutput
+ if args.verbose >=2:
+ print " Description: %s" %scenario['description']
+ else:
+ if args.verbose:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+ scenario = content['scenario']
+ myoutput = "%s %s %s" %(scenario['uuid'].ljust(38),scenario['name'].ljust(20), scenario['created_at'].ljust(20))
+ print myoutput
+ print " Description: %s" %scenario['description']
+ print " VNFs:"
+ for vnf in scenario['vnfs']:
+ print " %s %s %s" %(vnf['name'].ljust(20), vnf['vnf_id'].ljust(38), vnf['description'])
+ if len(scenario['nets'])>0:
+ print " Internal nets:"
+ for net in scenario['nets']:
+ if net['description'] is None: #if description does not exist, description is "-". Valid for external and internal nets.
+ net['description'] = '-'
+ if not net['external']:
+ print " %s %s %s" %(net['name'].ljust(20), net['uuid'].ljust(38), net['description'].ljust(30))
+ print " External nets:"
+ for net in scenario['nets']:
+ if net['external']:
+ print " %s %s %s vim-id:%s" %(net['name'].ljust(20), net['uuid'].ljust(38), net['description'].ljust(30), net['vim_id'])
+ else:
+ print content['error']['description']
+ if args.verbose:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+
+def scenario_delete(args):
+ #print "scenario-delete",args
+ if args.all:
+ tenant = "any"
+ else:
+ tenant = _get_tenant()
+ todelete = _get_item_uuid("scenarios", args.name, tenant=tenant)
+ if not args.force:
+ r = raw_input("Delete scenario %s (y/N)? " %(args.name))
+ if not (len(r)>0 and r[0].lower()=="y"):
+ return 0
+ URLrequest = "http://%s:%s/openmano/%s/scenarios/%s" %(mano_host, mano_port, tenant, todelete)
+ mano_response = requests.delete(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if mano_response.status_code == 200:
+ print content['result']
+ else:
+ print content['error']['description']
+ return result
+
+def scenario_deploy(args):
+ print "This command is deprecated, use 'openmano instance-scenario-create --scenario %s --name %s' instead!!!" % (args.scenario, args.name)
+ print
+ args.file = None
+ args.netmap_use = None
+ args.netmap_create = None
+ return instance_create(args)
+
+# #print "scenario-deploy",args
+# headers_req = {'content-type': 'application/json'}
+# action = {}
+# actionCmd="start"
+# if args.nostart:
+# actionCmd="reserve"
+# action[actionCmd] = {}
+# action[actionCmd]["instance_name"] = args.name
+# if args.datacenter != None:
+# action[actionCmd]["datacenter"] = args.datacenter
+# elif mano_datacenter != None:
+# action[actionCmd]["datacenter"] = mano_datacenter
+#
+# if args.description:
+# action[actionCmd]["description"] = args.description
+# payload_req = json.dumps(action, indent=4)
+# #print payload_req
+#
+# URLrequest = "http://%s:%s/openmano/%s/scenarios/%s/action" %(mano_host, mano_port, mano_tenant, args.scenario)
+# logger.debug("openmano request: %s", payload_req)
+# mano_response = requests.post(URLrequest, headers = headers_req, data=payload_req)
+# logger.debug("openmano response: %s", mano_response.text )
+# if args.verbose==None:
+# args.verbose=0
+#
+# result = 0 if mano_response.status_code==200 else mano_response.status_code
+# content = mano_response.json()
+# #print json.dumps(content, indent=4)
+# if args.verbose >= 3:
+# print yaml.safe_dump(content, indent=4, default_flow_style=False)
+# return result
+#
+# if mano_response.status_code == 200:
+# myoutput = "%s %s" %(content['uuid'].ljust(38),content['name'].ljust(20))
+# if args.verbose >=1:
+# myoutput = "%s %s" %(myoutput, content['created_at'].ljust(20))
+# if args.verbose >=2:
+# myoutput = "%s %s %s" %(myoutput, content['description'].ljust(30))
+# print myoutput
+# print ""
+# print "To check the status, run the following command:"
+# print "openmano instance-scenario-list <instance_id>"
+# else:
+# print content['error']['description']
+# return result
+
+def scenario_verify(args):
+ #print "scenario-verify",args
+ headers_req = {'content-type': 'application/json'}
+ action = {}
+ action["verify"] = {}
+ action["verify"]["instance_name"] = "scen-verify-return5"
+ payload_req = json.dumps(action, indent=4)
+ #print payload_req
+
+ URLrequest = "http://%s:%s/openmano/%s/scenarios/%s/action" %(mano_host, mano_port, mano_tenant, args.scenario)
+ logger.debug("openmano request: %s", payload_req)
+ mano_response = requests.post(URLrequest, headers = headers_req, data=payload_req)
+ logger.debug("openmano response: %s", mano_response.text )
+
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if mano_response.status_code == 200:
+ print content['result']
+ else:
+ print content['error']['description']
+ return result
+
+def instance_create(args):
+ tenant = _get_tenant()
+ headers_req = {'content-type': 'application/yaml'}
+ myInstance={"instance": {}, "schema_version": "0.1"}
+ if args.file:
+ instance_dict = _load_file_or_yaml(args.file)
+ if "instance" not in instance_dict:
+ myInstance = {"instance": instance_dict, "schema_version": "0.1"}
+ else:
+ myInstance = instance_dict
+ if args.name:
+ myInstance["instance"]['name'] = args.name
+ if args.description:
+ myInstance["instance"]['description'] = args.description
+ if args.nostart:
+ myInstance["instance"]['action'] = "reserve"
+ #datacenter
+ datacenter = myInstance["instance"].get("datacenter")
+ if args.datacenter != None:
+ datacenter = args.datacenter
+ myInstance["instance"]["datacenter"] = _get_datacenter(datacenter, tenant)
+ #scenario
+ scenario = myInstance["instance"].get("scenario")
+ if args.scenario != None:
+ scenario = args.scenario
+ if not scenario:
+ print "you must provide an scenario in the file descriptor or with --scenario"
+ return -1
+ myInstance["instance"]["scenario"] = _get_item_uuid("scenarios", scenario, tenant)
+ if args.netmap_use:
+ if "networks" not in myInstance["instance"]:
+ myInstance["instance"]["networks"] = {}
+ for net in args.netmap_use:
+ net_comma_list = net.split(",")
+ for net_comma in net_comma_list:
+ net_tuple = net_comma.split("=")
+ if len(net_tuple) != 2:
+ print "error at netmap-use. Expected net-scenario=net-datacenter. (%s)?" % net_comma
+ return
+ net_scenario = net_tuple[0].strip()
+ net_datacenter = net_tuple[1].strip()
+ if net_scenario not in myInstance["instance"]["networks"]:
+ myInstance["instance"]["networks"][net_scenario] = {}
+ myInstance["instance"]["networks"][net_scenario]["netmap-use"] = net_datacenter
+ if args.netmap_create:
+ if "networks" not in myInstance["instance"]:
+ myInstance["instance"]["networks"] = {}
+ for net in args.netmap_create:
+ net_comma_list = net.split(",")
+ for net_comma in net_comma_list:
+ net_tuple = net_comma.split("=")
+ if len(net_tuple) == 1:
+ net_scenario = net_tuple[0].strip()
+ net_datacenter = None
+ elif len(net_tuple) == 2:
+ net_scenario = net_tuple[0].strip()
+ net_datacenter = net_tuple[1].strip()
+ else:
+ print "error at netmap-create. Expected net-scenario=net-datacenter or net-scenario. (%s)?" % net_comma
+ return
+ if net_scenario not in myInstance["instance"]["networks"]:
+ myInstance["instance"]["networks"][net_scenario] = {}
+ myInstance["instance"]["networks"][net_scenario]["netmap-create"] = net_datacenter
+
+ payload_req = yaml.safe_dump(myInstance, explicit_start=True, indent=4, default_flow_style=False, tags=False, encoding='utf-8', allow_unicode=True)
+ logger.debug("openmano request: %s", payload_req)
+ URLrequest = "http://%s:%s/openmano/%s/instances" %(mano_host, mano_port, tenant)
+ mano_response = requests.post(URLrequest, headers = headers_req, data=payload_req)
+ logger.debug("openmano response: %s", mano_response.text )
+ if args.verbose==None:
+ args.verbose=0
+
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if args.verbose >= 3:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+
+ if mano_response.status_code == 200:
+ myoutput = "%s %s" %(content['uuid'].ljust(38),content['name'].ljust(20))
+ if args.verbose >=1:
+ myoutput = "%s %s" %(myoutput, content['created_at'].ljust(20))
+ if args.verbose >=2:
+ myoutput = "%s %s %s" %(myoutput, content['description'].ljust(30))
+ print myoutput
+ else:
+ print content['error']['description']
+ return result
+
+def instance_scenario_list(args):
+ #print "instance-scenario-list",args
+ if args.all:
+ tenant = "any"
+ else:
+ tenant = _get_tenant()
+ if args.name:
+ toshow = _get_item_uuid("instances", args.name, tenant)
+ URLrequest = "http://%s:%s/openmano/%s/instances/%s" %(mano_host, mano_port, tenant, toshow)
+ else:
+ URLrequest = "http://%s:%s/openmano/%s/instances" %(mano_host, mano_port, tenant)
+ mano_response = requests.get(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if args.verbose==None:
+ args.verbose=0
+
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ if mano_response.status_code == 200:
+ if not args.name:
+ if args.verbose >= 3:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+ if len(content['instances']) == 0:
+ print "No scenario instances were found."
+ return result
+ for instance in content['instances']:
+ myoutput = "%s %s" %(instance['uuid'].ljust(38),instance['name'].ljust(20))
+ if args.verbose >=1:
+ myoutput = "%s %s" %(myoutput, instance['created_at'].ljust(20))
+ print myoutput
+ if args.verbose >=2:
+ print "Description: %s" %instance['description']
+ else:
+ if args.verbose:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+ instance = content
+ print "%s %s %s" %(instance['uuid'].ljust(38),instance['name'].ljust(20),instance['created_at'].ljust(20))
+ print "Description: %s" %instance['description']
+ print "Template scenario id: %s" %instance['scenario_id']
+ print "Template scenario name: %s" %instance['scenario_name']
+ print "---------------------------------------"
+ print "VNF instances: %d" %len(instance['vnfs'])
+ for vnf in instance['vnfs']:
+ #print " %s %s Template vnf name: %s Template vnf id: %s" %(vnf['uuid'].ljust(38), vnf['name'].ljust(20), vnf['vnf_name'].ljust(20), vnf['vnf_id'].ljust(38))
+ print " %s %s Template vnf id: %s" %(vnf['uuid'].ljust(38), vnf['vnf_name'].ljust(20), vnf['vnf_id'].ljust(38))
+ if len(instance['nets'])>0:
+ print "---------------------------------------"
+ print "Internal nets:"
+ for net in instance['nets']:
+ if not net['external']:
+ print " %s %s VIM ID: %s" %(net['uuid'].ljust(38), net['status'].ljust(12), net['vim_net_id'])
+ print "---------------------------------------"
+ print "External nets:"
+ for net in instance['nets']:
+ if net['external']:
+ print " %s %s VIM ID: %s" %(net['uuid'].ljust(38), net['status'].ljust(12), net['vim_net_id'])
+ print "---------------------------------------"
+ print "VM instances:"
+ for vnf in instance['vnfs']:
+ for vm in vnf['vms']:
+ print " %s %s %s %s VIM ID: %s" %(vm['uuid'].ljust(38), vnf['vnf_name'].ljust(20), vm['name'].ljust(20), vm['status'].ljust(12), vm['vim_vm_id'])
+ else:
+ print content['error']['description']
+ if args.verbose:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+
+def instance_scenario_status(args):
+ print "instance-scenario-status"
+ return 0
+
+def instance_scenario_delete(args):
+ if args.all:
+ tenant = "any"
+ else:
+ tenant = _get_tenant()
+ todelete = _get_item_uuid("instances", args.name, tenant=tenant)
+ #print "instance-scenario-delete",args
+ if not args.force:
+ r = raw_input("Delete scenario instance %s (y/N)? " %(args.name))
+ if not (len(r)>0 and r[0].lower()=="y"):
+ return
+ URLrequest = "http://%s:%s/openmano/%s/instances/%s" %(mano_host, mano_port, tenant, todelete)
+ mano_response = requests.delete(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if mano_response.status_code == 200:
+ print content['result']
+ else:
+ print content['error']['description']
+ return result
+
+def instance_scenario_action(args):
+ #print "instance-scenario-action", args
+ tenant = _get_tenant()
+ toact = _get_item_uuid("instances", args.name, tenant=tenant)
+ action={}
+ action[ args.action ] = args.param
+ if args.vnf:
+ action["vnfs"] = args.vnf
+ if args.vm:
+ action["vms"] = args.vm
+
+ headers_req = {'content-type': 'application/json'}
+ payload_req = json.dumps(action, indent=4)
+ URLrequest = "http://%s:%s/openmano/%s/instances/%s/action" %(mano_host, mano_port, tenant, toact)
+ logger.debug("openmano request: %s", payload_req)
+ mano_response = requests.post(URLrequest, headers = headers_req, data=payload_req)
+ logger.debug("openmano response: %s", mano_response.text )
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if mano_response.status_code == 200:
+ if args.verbose:
+ print yaml.safe_dump(content, indent=4, default_flow_style=False)
+ return result
+ for uuid,c in content.iteritems():
+ print "%s %s %s" %(uuid.ljust(38), c['name'].ljust(20),c['description'].ljust(20))
+ else:
+ print content['error']['description']
+ return result
+
+
+def instance_vnf_list(args):
+ print "instance-vnf-list"
+ return 0
+
+def instance_vnf_status(args):
+ print "instance-vnf-status"
+ return 0
+
+def tenant_create(args):
+ headers_req = {'Accept': 'application/json', 'content-type': 'application/json'}
+ tenant_dict={"name": args.name}
+ if args.description!=None:
+ tenant_dict["description"] = args.description
+ payload_req = json.dumps( {"tenant": tenant_dict })
+
+ #print payload_req
+
+ URLrequest = "http://%s:%s/openmano/tenants" %(mano_host, mano_port)
+ logger.debug("openmano request: %s", payload_req)
+ mano_response = requests.post(URLrequest, headers=headers_req, data=payload_req)
+ logger.debug("openmano response: %s", mano_response.text )
+ return _print_verbose(mano_response, args.verbose)
+
+def tenant_list(args):
+ #print "tenant-list",args
+ if args.name:
+ toshow = _get_item_uuid("tenants", args.name)
+ URLrequest = "http://%s:%s/openmano/tenants/%s" %(mano_host, mano_port, toshow)
+ else:
+ URLrequest = "http://%s:%s/openmano/tenants" %(mano_host, mano_port)
+ mano_response = requests.get(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ if args.verbose==None:
+ args.verbose=0
+ if args.name!=None:
+ args.verbose += 1
+ return _print_verbose(mano_response, args.verbose)
+
+def tenant_delete(args):
+ #print "tenant-delete",args
+ todelete = _get_item_uuid("tenants", args.name)
+ if not args.force:
+ r = raw_input("Delete tenant %s (y/N)? " %(args.name))
+ if not (len(r)>0 and r[0].lower()=="y"):
+ return 0
+ URLrequest = "http://%s:%s/openmano/tenants/%s" %(mano_host, mano_port, todelete)
+ mano_response = requests.delete(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if mano_response.status_code == 200:
+ print content['result']
+ else:
+ print content['error']['description']
+ return result
+
+def datacenter_attach(args):
+ tenant = _get_tenant()
+ datacenter = _get_datacenter(args.name)
+ headers_req = {'Accept': 'application/json', 'content-type': 'application/json'}
+
+ datacenter_dict={}
+ if args.vim_tenant_id != None:
+ datacenter_dict['vim_tenant'] = args.vim_tenant_id
+ if args.vim_tenant_name != None:
+ datacenter_dict['vim_tenant_name'] = args.vim_tenant_name
+ if args.user != None:
+ datacenter_dict['vim_username'] = args.user
+ if args.password != None:
+ datacenter_dict['vim_password'] = args.password
+ payload_req = json.dumps( {"datacenter": datacenter_dict })
+
+ #print payload_req
+
+ URLrequest = "http://%s:%s/openmano/%s/datacenters/%s" %(mano_host, mano_port, tenant, datacenter)
+ logger.debug("openmano request: %s", payload_req)
+ mano_response = requests.post(URLrequest, headers=headers_req, data=payload_req)
+ logger.debug("openmano response: %s", mano_response.text )
+ result = _print_verbose(mano_response, args.verbose)
+ #provide addional information if error
+ if mano_response.status_code != 200:
+ content = mano_response.json()
+ if "already in use for 'name'" in content['error']['description'] and \
+ "to database vim_tenants table" in content['error']['description']:
+ print "Try to specify a different name with --vim-tenant-name"
+ return result
+
+def datacenter_detach(args):
+ if args.all:
+ tenant = "any"
+ else:
+ tenant = _get_tenant()
+ datacenter = _get_datacenter(args.name, tenant)
+ headers_req = {'Accept': 'application/json', 'content-type': 'application/json'}
+ URLrequest = "http://%s:%s/openmano/%s/datacenters/%s" %(mano_host, mano_port, tenant, datacenter)
+ mano_response = requests.delete(URLrequest, headers=headers_req)
+ logger.debug("openmano response: %s", mano_response.text )
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ if mano_response.status_code == 200:
+ print content['result']
+ else:
+ print content['error']['description']
+ return result
+
+def datacenter_create(args):
+ headers_req = {'Accept': 'application/json', 'content-type': 'application/json'}
+ datacenter_dict={"name": args.name, "vim_url": args.url}
+ if args.description!=None:
+ datacenter_dict["description"] = args.description
+ if args.type!=None:
+ datacenter_dict["type"] = args.type
+ if args.url!=None:
+ datacenter_dict["vim_url_admin"] = args.url_admin
+ if args.config!=None:
+ datacenter_dict["config"] = _load_file_or_yaml(args.config)
+ payload_req = json.dumps( {"datacenter": datacenter_dict })
+
+ #print payload_req
+
+ URLrequest = "http://%s:%s/openmano/datacenters" %(mano_host, mano_port)
+ logger.debug("openmano request: %s", payload_req)
+ mano_response = requests.post(URLrequest, headers=headers_req, data=payload_req)
+ logger.debug("openmano response: %s", mano_response.text )
+ return _print_verbose(mano_response, args.verbose)
+
+def datacenter_delete(args):
+ #print "datacenter-delete",args
+ todelete = _get_item_uuid("datacenters", args.name, "any")
+ if not args.force:
+ r = raw_input("Delete datacenter %s (y/N)? " %(args.name))
+ if not (len(r)>0 and r[0].lower()=="y"):
+ return 0
+ URLrequest = "http://%s:%s/openmano/datacenters/%s" %(mano_host, mano_port, todelete)
+ mano_response = requests.delete(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if mano_response.status_code == 200:
+ print content['result']
+ else:
+ print content['error']['description']
+ return result
+
+def datacenter_list(args):
+ #print "datacenter-list",args
+ tenant='any' if args.all else _get_tenant()
+
+ if args.name:
+ toshow = _get_item_uuid("datacenters", args.name, tenant)
+ URLrequest = "http://%s:%s/openmano/%s/datacenters/%s" %(mano_host, mano_port, tenant, toshow)
+ else:
+ URLrequest = "http://%s:%s/openmano/%s/datacenters" %(mano_host, mano_port, tenant)
+ mano_response = requests.get(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ if args.verbose==None:
+ args.verbose=0
+ if args.name!=None:
+ args.verbose += 1
+ return _print_verbose(mano_response, args.verbose)
+
+def vim_action(args):
+ #print "datacenter-net-action",args
+ tenant = _get_tenant()
+ datacenter = _get_datacenter(args.datacenter, tenant)
+ if args.verbose==None:
+ args.verbose=0
+ if args.action=="list":
+ URLrequest = "http://%s:%s/openmano/%s/vim/%s/%ss" %(mano_host, mano_port, tenant, datacenter, args.item)
+ if args.name!=None:
+ args.verbose += 1
+ URLrequest += "/" + args.name
+ mano_response = requests.get(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ return _print_verbose(mano_response, args.verbose)
+ elif args.action=="delete":
+ URLrequest = "http://%s:%s/openmano/%s/vim/%s/%ss/%s" %(mano_host, mano_port, tenant, datacenter, args.item, args.name)
+ mano_response = requests.delete(URLrequest)
+ logger.debug("openmano response: %s", mano_response.text )
+ result = 0 if mano_response.status_code==200 else mano_response.status_code
+ content = mano_response.json()
+ #print json.dumps(content, indent=4)
+ if mano_response.status_code == 200:
+ print content['result']
+ else:
+ print content['error']['description']
+ return result
+ elif args.action=="create":
+ headers_req = {'content-type': 'application/yaml'}
+ if args.file:
+ create_dict = _load_file_or_yaml(args.file)
+ if args.item not in create_dict:
+ create_dict = {args.item: create_dict}
+ else:
+ create_dict = {args.item:{}}
+ if args.name:
+ create_dict[args.item]['name'] = args.name
+ #if args.description:
+ # create_dict[args.item]['description'] = args.description
+ if args.item=="vim-net":
+ if args.bind_net:
+ create_dict[args.item]['bind_net'] = args.bind_net
+ if args.bind_type:
+ create_dict[args.item]['bind_type'] = args.bind_type
+ if args.shared:
+ create_dict[args.item]['shared'] = args.shared
+ if "name" not in create_dict[args.item]:
+ print "You must provide a name in the descriptor file or with the --name option"
+ return
+ payload_req = yaml.safe_dump(create_dict, explicit_start=True, indent=4, default_flow_style=False, tags=False, encoding='utf-8', allow_unicode=True)
+ logger.debug("openmano request: %s", payload_req)
+ URLrequest = "http://%s:%s/openmano/%s/vim/%s/%ss" %(mano_host, mano_port, mano_tenant, datacenter, args.item)
+ mano_response = requests.post(URLrequest, headers = headers_req, data=payload_req)
+ logger.debug("openmano response: %s", mano_response.text )
+ if args.verbose==None:
+ args.verbose=0
+ return _print_verbose(mano_response, args.verbose)
+
+
+def datacenter_net_action(args):
+ if args.action == "net-update":
+ print "This command is deprecated, use 'openmano datacenter-netmap-delete --all' and 'openmano datacenter-netmap-upload' instead!!!"
+ print
+ args.action = "netmap-delete"
+ args.netmap = None
+ args.all = True
+ r = datacenter_netmap_action(args)
+ if r == 0:
+ args.force = True
+ args.action = "netmap-upload"
+ r = datacenter_netmap_action(args)
+ return r
+
+ if args.action == "net-edit":
+ args.netmap = args.net
+ args.name = None
+ elif args.action == "net-list":
+ args.netmap = None
+ elif args.action == "net-delete":
+ args.netmap = args.net
+ args.all = False
+
+ args.action = "netmap" + args.action[3:]
+ args.vim_name=None
+ args.vim_id=None
+ print "This command is deprecated, use 'openmano datacenter-%s' instead!!!" % args.action
+ print
+ return datacenter_netmap_action(args)
+
+def datacenter_netmap_action(args):
+ tenant = _get_tenant()
+ datacenter = _get_datacenter(args.datacenter, tenant)
+ #print "datacenter_netmap_action",args
+ payload_req = None
+ if args.verbose==None:
+ args.verbose=0
+ headers_req = {'Accept': 'application/json', 'content-type': 'application/json'}
+ URLrequest = "http://%s:%s/openmano/%s/datacenters/%s/netmaps" %(mano_host, mano_port, tenant, datacenter)
+
+ if args.action=="netmap-list":
+ if args.netmap:
+ URLrequest += "/" + args.netmap
+ args.verbose += 1
+ mano_response = requests.get(URLrequest)
+
+ elif args.action=="netmap-delete":
+ if args.netmap and args.all:
+ print "you can not use a netmap name and the option --all at the same time"
+ return 1
+ if args.netmap:
+ force_text= "Delete default netmap '%s' from datacenter '%s' (y/N)? " % (args.netmap, datacenter)
+ URLrequest += "/" + args.netmap
+ elif args.all:
+ force_text="Delete all default netmaps from datacenter '%s' (y/N)? " % (datacenter)
+ else:
+ print "you must specify a netmap name or the option --all"
+ return 1
+ if not args.force:
+ r = raw_input(force_text)
+ if len(r)>0 and r[0].lower()=="y":
+ pass
+ else:
+ return 0
+ mano_response = requests.delete(URLrequest, headers=headers_req)
+ elif args.action=="netmap-upload":
+ if not args.force:
+ r = raw_input("Create all the available networks from datacenter '%s' as default netmaps (y/N)? " % (datacenter))
+ if len(r)>0 and r[0].lower()=="y":
+ pass
+ else:
+ return 0
+ URLrequest += "/upload"
+ mano_response = requests.post(URLrequest, headers=headers_req)
+ elif args.action=="netmap-edit" or args.action=="netmap-create":
+ if args.file:
+ payload = _load_file_or_yaml(args.file)
+ else:
+ payload = {}
+ if "netmap" not in payload:
+ payload = {"netmap": payload}
+ if args.name:
+ payload["netmap"]["name"] = args.name
+ if args.vim_id:
+ payload["netmap"]["vim_id"] = args.vim_id
+ if args.action=="netmap-create" and args.vim_name:
+ payload["netmap"]["vim_name"] = args.vim_name
+ payload_req = json.dumps(payload)
+ logger.debug("openmano request: %s", payload_req)
+
+ if args.action=="netmap-edit" and not args.force:
+ if len(payload["netmap"]) == 0:
+ print "You must supply some parameter to edit"
+ return 1
+ r = raw_input("Edit default netmap '%s' from datacenter '%s' (y/N)? " % (args.netmap, datacenter))
+ if len(r)>0 and r[0].lower()=="y":
+ pass
+ else:
+ return 0
+ URLrequest += "/" + args.netmap
+ mano_response = requests.put(URLrequest, headers=headers_req, data=payload_req)
+ else: #netmap-create
+ if "vim_name" not in payload["netmap"] and "vim_id" not in payload["netmap"]:
+ print "You must supply either --vim-id or --vim-name option; or include one of them in the file descriptor"
+ return 1
+ mano_response = requests.post(URLrequest, headers=headers_req, data=payload_req)
+
+ logger.debug("openmano response: %s", mano_response.text )
+ return _print_verbose(mano_response, args.verbose)
+
+def element_edit(args):
+ element = _get_item_uuid(args.element, args.name)
+ headers_req = {'Accept': 'application/json', 'content-type': 'application/json'}
+ URLrequest = "http://%s:%s/openmano/%s/%s" %(mano_host, mano_port, args.element, element)
+ payload=_load_file_or_yaml(args.file)
+ if args.element[:-1] not in payload:
+ payload = {args.element[:-1]: payload }
+ payload_req = json.dumps(payload)
+
+ #print payload_req
+ if not args.force or (args.name==None and args.filer==None):
+ r = raw_input(" Edit " + args.element[:-1] + " " + args.name + " (y/N)? ")
+ if len(r)>0 and r[0].lower()=="y":
+ pass
+ else:
+ return 0
+ logger.debug("openmano request: %s", payload_req)
+ mano_response = requests.put(URLrequest, headers=headers_req, data=payload_req)
+ logger.debug("openmano response: %s", mano_response.text )
+ if args.verbose==None:
+ args.verbose=0
+ if args.name!=None:
+ args.verbose += 1
+ return _print_verbose(mano_response, args.verbose)
+
+
+global mano_host
+global mano_port
+global mano_tenant
+
+if __name__=="__main__":
+
+ mano_tenant = os.getenv('OPENMANO_TENANT', None)
+ mano_host = os.getenv('OPENMANO_HOST',"localhost")
+ mano_port = os.getenv('OPENMANO_PORT',"9090")
+ mano_datacenter = os.getenv('OPENMANO_DATACENTER',None)
+
+ main_parser = ThrowingArgumentParser(description='User program to interact with OPENMANO-SERVER (openmanod)')
+ main_parser.add_argument('--version', action='version', version='%(prog)s ' + __version__ )
+
+ subparsers = main_parser.add_subparsers(help='commands')
+
+ parent_parser = argparse.ArgumentParser(add_help=False)
+ parent_parser.add_argument('--verbose', '-v', action='count', help="increase verbosity level. Use several times")
+ parent_parser.add_argument('--debug', '-d', action='store_true', help="show debug information")
+
+ config_parser = subparsers.add_parser('config', parents=[parent_parser], help="prints configuration values")
+ config_parser.add_argument("-n", action="store_true", help="resolves tenant and datacenter names")
+ config_parser.set_defaults(func=config)
+
+ vnf_create_parser = subparsers.add_parser('vnf-create', parents=[parent_parser], help="adds a vnf into the catalogue")
+ vnf_create_parser.add_argument("file", action="store", help="location of the JSON file describing the VNF").completer = FilesCompleter
+ vnf_create_parser.add_argument("--name", action="store", help="name of the VNF (if it exists in the VNF descriptor, it is overwritten)")
+ vnf_create_parser.add_argument("--description", action="store", help="description of the VNF (if it exists in the VNF descriptor, it is overwritten)")
+ vnf_create_parser.add_argument("--image-path", action="store", help="change image path locations (overwritten)")
+ vnf_create_parser.set_defaults(func=vnf_create)
+
+ vnf_list_parser = subparsers.add_parser('vnf-list', parents=[parent_parser], help="lists information about a vnf")
+ vnf_list_parser.add_argument("name", nargs='?', help="name of the VNF")
+ vnf_list_parser.add_argument("-a", "--all", action="store_true", help="shows all vnfs, not only the owned or public ones")
+ #vnf_list_parser.add_argument('--descriptor', help="prints the VNF descriptor", action="store_true")
+ vnf_list_parser.set_defaults(func=vnf_list)
+
+ vnf_delete_parser = subparsers.add_parser('vnf-delete', parents=[parent_parser], help="deletes a vnf from the catalogue")
+ vnf_delete_parser.add_argument("name", action="store", help="name or uuid of the VNF to be deleted")
+ vnf_delete_parser.add_argument("-f", "--force", action="store_true", help="forces deletion without asking")
+ vnf_delete_parser.add_argument("-a", "--all", action="store_true", help="allow delete not owned or privated one")
+ vnf_delete_parser.set_defaults(func=vnf_delete)
+
+ scenario_create_parser = subparsers.add_parser('scenario-create', parents=[parent_parser], help="adds a scenario into the OPENMANO DB")
+ scenario_create_parser.add_argument("file", action="store", help="location of the YAML file describing the scenario").completer = FilesCompleter
+ scenario_create_parser.add_argument("--name", action="store", help="name of the scenario (if it exists in the YAML scenario, it is overwritten)")
+ scenario_create_parser.add_argument("--description", action="store", help="description of the scenario (if it exists in the YAML scenario, it is overwritten)")
+ scenario_create_parser.set_defaults(func=scenario_create)
+
+ scenario_list_parser = subparsers.add_parser('scenario-list', parents=[parent_parser], help="lists information about a scenario")
+ scenario_list_parser.add_argument("name", nargs='?', help="name of the scenario")
+ #scenario_list_parser.add_argument('--descriptor', help="prints the scenario descriptor", action="store_true")
+ scenario_list_parser.add_argument("-a", "--all", action="store_true", help="shows all scenarios, not only the owned or public ones")
+ scenario_list_parser.set_defaults(func=scenario_list)
+
+ scenario_delete_parser = subparsers.add_parser('scenario-delete', parents=[parent_parser], help="deletes a scenario from the OPENMANO DB")
+ scenario_delete_parser.add_argument("name", action="store", help="name or uuid of the scenario to be deleted")
+ scenario_delete_parser.add_argument("-f", "--force", action="store_true", help="forces deletion without asking")
+ scenario_delete_parser.add_argument("-a", "--all", action="store_true", help="allow delete not owned or privated one")
+ scenario_delete_parser.set_defaults(func=scenario_delete)
+
+ scenario_deploy_parser = subparsers.add_parser('scenario-deploy', parents=[parent_parser], help="deploys a scenario")
+ scenario_deploy_parser.add_argument("scenario", action="store", help="name or uuid of the scenario to be deployed")
+ scenario_deploy_parser.add_argument("name", action="store", help="name of the instance")
+ scenario_deploy_parser.add_argument("--nostart", action="store_true", help="does not start the vms, just reserve resources")
+ scenario_deploy_parser.add_argument("--datacenter", action="store", help="specifies the datacenter. Needed if several datacenters are available")
+ scenario_deploy_parser.add_argument("--description", action="store", help="description of the instance")
+ scenario_deploy_parser.set_defaults(func=scenario_deploy)
+
+ scenario_deploy_parser = subparsers.add_parser('scenario-verify', help="verifies if a scenario can be deployed (deploys it and deletes it)")
+ scenario_deploy_parser.add_argument("scenario", action="store", help="name or uuid of the scenario to be verified")
+ scenario_deploy_parser.add_argument('--debug', '-d', action='store_true', help="show debug information")
+ scenario_deploy_parser.set_defaults(func=scenario_verify)
+
+ instance_scenario_create_parser = subparsers.add_parser('instance-scenario-create', parents=[parent_parser], help="deploys a scenario")
+ instance_scenario_create_parser.add_argument("file", nargs='?', help="descriptor of the instance. Must be a file or yaml/json text")
+ instance_scenario_create_parser.add_argument("--scenario", action="store", help="name or uuid of the scenario to be deployed")
+ instance_scenario_create_parser.add_argument("--name", action="store", help="name of the instance")
+ instance_scenario_create_parser.add_argument("--nostart", action="store_true", help="does not start the vms, just reserve resources")
+ instance_scenario_create_parser.add_argument("--datacenter", action="store", help="specifies the datacenter. Needed if several datacenters are available")
+ instance_scenario_create_parser.add_argument("--netmap-use", action="append", type=str, dest="netmap_use", help="indicates a datacenter network to map a scenario network 'scenario-network=datacenter-network'. Can be used several times")
+ instance_scenario_create_parser.add_argument("--netmap-create", action="append", type=str, dest="netmap_create", help="the scenario network must be created at datacenter 'scenario-network[=datacenter-network-name]' . Can be used several times")
+ instance_scenario_create_parser.add_argument("--description", action="store", help="description of the instance")
+ instance_scenario_create_parser.set_defaults(func=instance_create)
+
+ instance_scenario_list_parser = subparsers.add_parser('instance-scenario-list', parents=[parent_parser], help="lists information about a scenario instance")
+ instance_scenario_list_parser.add_argument("name", nargs='?', help="name of the scenario instance")
+ instance_scenario_list_parser.add_argument("-a", "--all", action="store_true", help="shows all instance-scenarios, not only the owned")
+ instance_scenario_list_parser.set_defaults(func=instance_scenario_list)
+
+ instance_scenario_delete_parser = subparsers.add_parser('instance-scenario-delete', parents=[parent_parser], help="deletes a scenario instance (and deletes all VM and net instances in VIM)")
+ instance_scenario_delete_parser.add_argument("name", action="store", help="name or uuid of the scenario instance to be deleted")
+ instance_scenario_delete_parser.add_argument("-f", "--force", action="store_true", help="forces deletion without asking")
+ instance_scenario_delete_parser.add_argument("-a", "--all", action="store_true", help="allow delete not owned or privated one")
+ instance_scenario_delete_parser.set_defaults(func=instance_scenario_delete)
+
+ instance_scenario_action_parser = subparsers.add_parser('instance-scenario-action', parents=[parent_parser], help="invoke an action over part or the whole scenario instance")
+ instance_scenario_action_parser.add_argument("name", action="store", help="name or uuid of the scenario instance")
+ instance_scenario_action_parser.add_argument("action", action="store", type=str, \
+ choices=["start","pause","resume","shutoff","shutdown","forceOff","rebuild","reboot", "console"],\
+ help="action to send")
+ instance_scenario_action_parser.add_argument("param", nargs='?', help="addional param of the action. e.g. console type (novnc, ...), reboot type (TODO)")
+ instance_scenario_action_parser.add_argument("--vnf", action="append", help="VNF to act on (can use several entries)")
+ instance_scenario_action_parser.add_argument("--vm", action="append", help="VM to act on (can use several entries)")
+ instance_scenario_action_parser.set_defaults(func=instance_scenario_action)
+
+ #instance_scenario_status_parser = subparsers.add_parser('instance-scenario-status', help="show the status of a scenario instance")
+ #instance_scenario_status_parser.add_argument("name", action="store", help="name or uuid of the scenario instance")
+ #instance_scenario_status_parser.set_defaults(func=instance_scenario_status)
+
+ tenant_create_parser = subparsers.add_parser('tenant-create', parents=[parent_parser], help="creates a new tenant")
+ tenant_create_parser.add_argument("name", action="store", help="name for the tenant")
+ tenant_create_parser.add_argument("--description", action="store", help="description of the tenant")
+ tenant_create_parser.set_defaults(func=tenant_create)
+
+ tenant_delete_parser = subparsers.add_parser('tenant-delete', parents=[parent_parser], help="deletes a tenant from the catalogue")
+ tenant_delete_parser.add_argument("name", action="store", help="name or uuid of the tenant to be deleted")
+ tenant_delete_parser.add_argument("-f", "--force", action="store_true", help="forces deletion without asking")
+ tenant_delete_parser.set_defaults(func=tenant_delete)
+
+ tenant_list_parser = subparsers.add_parser('tenant-list', parents=[parent_parser], help="lists information about a tenant")
+ tenant_list_parser.add_argument("name", nargs='?', help="name or uuid of the tenant")
+ tenant_list_parser.set_defaults(func=tenant_list)
+
+ item_list=('tenant','datacenter') #put tenant before so that help appear in order
+ for item in item_list:
+ element_edit_parser = subparsers.add_parser(item+'-edit', parents=[parent_parser], help="edits one "+item)
+ element_edit_parser.add_argument("name", help="name or uuid of the "+item)
+ element_edit_parser.add_argument("file", help="json/yaml text or file with the changes").completer = FilesCompleter
+ element_edit_parser.add_argument("-f","--force", action="store_true", help="do not prompt for confirmation")
+ element_edit_parser.set_defaults(func=element_edit, element=item + 's')
+
+ datacenter_create_parser = subparsers.add_parser('datacenter-create', parents=[parent_parser], help="creates a new datacenter")
+ datacenter_create_parser.add_argument("name", action="store", help="name for the datacenter")
+ datacenter_create_parser.add_argument("url", action="store", help="url for the datacenter")
+ datacenter_create_parser.add_argument("--url_admin", action="store", help="url for administration for the datacenter")
+ datacenter_create_parser.add_argument("--type", action="store", help="datacenter type: openstack or openvim (default)")
+ datacenter_create_parser.add_argument("--config", action="store", help="aditional configuration in json/yaml format")
+ datacenter_create_parser.add_argument("--description", action="store", help="description of the datacenter")
+ datacenter_create_parser.set_defaults(func=datacenter_create)
+
+ datacenter_delete_parser = subparsers.add_parser('datacenter-delete', parents=[parent_parser], help="deletes a datacenter from the catalogue")
+ datacenter_delete_parser.add_argument("name", action="store", help="name or uuid of the datacenter to be deleted")
+ datacenter_delete_parser.add_argument("-f", "--force", action="store_true", help="forces deletion without asking")
+ datacenter_delete_parser.set_defaults(func=datacenter_delete)
+
+ datacenter_list_parser = subparsers.add_parser('datacenter-list', parents=[parent_parser], help="lists information about a datacenter")
+ datacenter_list_parser.add_argument("name", nargs='?', help="name or uuid of the datacenter")
+ datacenter_list_parser.add_argument("-a", "--all", action="store_true", help="shows all datacenters, not only datacenters attached to tenant")
+ datacenter_list_parser.set_defaults(func=datacenter_list)
+
+ datacenter_attach_parser = subparsers.add_parser('datacenter-attach', parents=[parent_parser], help="associates a datacenter to the operating tenant")
+ datacenter_attach_parser.add_argument("name", help="name or uuid of the datacenter")
+ datacenter_attach_parser.add_argument('--vim-tenant-id', action='store', help="specify a datacenter tenant to use. A new one is created by default")
+ datacenter_attach_parser.add_argument('--vim-tenant-name', action='store', help="specify a datacenter tenant name.")
+ datacenter_attach_parser.add_argument("--user", action="store", help="user credentials for the datacenter")
+ datacenter_attach_parser.add_argument("--password", action="store", help="password credentials for the datacenter")
+ datacenter_attach_parser.set_defaults(func=datacenter_attach)
+
+ datacenter_detach_parser = subparsers.add_parser('datacenter-detach', parents=[parent_parser], help="removes the association between a datacenter and the operating tenant")
+ datacenter_detach_parser.add_argument("name", help="name or uuid of the datacenter")
+ datacenter_detach_parser.add_argument("-a", "--all", action="store_true", help="removes all associations from this datacenter")
+ datacenter_detach_parser.set_defaults(func=datacenter_detach)
+
+
+ action_dict={'net-update': 'retrieves external networks from datacenter',
+ 'net-edit': 'edits an external network',
+ 'net-delete': 'deletes an external network',
+ 'net-list': 'lists external networks from a datacenter'
+ }
+ for item in action_dict:
+ datacenter_action_parser = subparsers.add_parser('datacenter-'+item, parents=[parent_parser], help=action_dict[item])
+ datacenter_action_parser.add_argument("datacenter", help="name or uuid of the datacenter")
+ if item=='net-edit' or item=='net-delete':
+ datacenter_action_parser.add_argument("net", help="name or uuid of the datacenter net")
+ if item=='net-edit':
+ datacenter_action_parser.add_argument("file", help="json/yaml text or file with the changes").completer = FilesCompleter
+ if item!='net-list':
+ datacenter_action_parser.add_argument("-f","--force", action="store_true", help="do not prompt for confirmation")
+ datacenter_action_parser.set_defaults(func=datacenter_net_action, action=item)
+
+
+ action_dict={'netmap-upload': 'create network senario netmap base on the datacenter networks',
+ 'netmap-create': 'create a new network senario netmap',
+ 'netmap-edit': 'edit name of a network senario netmap',
+ 'netmap-delete': 'deletes a network scenario netmap (--all for clearing all)',
+ 'netmap-list': 'list/show network scenario netmaps'
+ }
+ for item in action_dict:
+ datacenter_action_parser = subparsers.add_parser('datacenter-'+item, parents=[parent_parser], help=action_dict[item])
+ datacenter_action_parser.add_argument("--datacenter", help="name or uuid of the datacenter")
+ #if item=='net-add':
+ # datacenter_action_parser.add_argument("net", help="name of the network")
+ if item=='netmap-delete':
+ datacenter_action_parser.add_argument("netmap", nargs='?',help="name or uuid of the datacenter netmap to delete")
+ datacenter_action_parser.add_argument("--all", action="store_true", help="delete all netmap of this datacenter")
+ datacenter_action_parser.add_argument("-f","--force", action="store_true", help="do not prompt for confirmation")
+ if item=='netmap-edit':
+ datacenter_action_parser.add_argument("netmap", help="name or uuid of the datacenter netmap do edit")
+ datacenter_action_parser.add_argument("file", nargs='?', help="json/yaml text or file with the changes").completer = FilesCompleter
+ datacenter_action_parser.add_argument("--name", action='store', help="name to assign to the datacenter netmap")
+ datacenter_action_parser.add_argument('--vim-id', action='store', help="specify vim network uuid")
+ datacenter_action_parser.add_argument("-f","--force", action="store_true", help="do not prompt for confirmation")
+ if item=='netmap-list':
+ datacenter_action_parser.add_argument("netmap", nargs='?',help="name or uuid of the datacenter netmap to show")
+ if item=='netmap-create':
+ datacenter_action_parser.add_argument("file", nargs='?', help="json/yaml text or file descriptor with the changes").completer = FilesCompleter
+ datacenter_action_parser.add_argument("--name", action='store', help="name to assign to the datacenter netmap, by default same as vim-name")
+ datacenter_action_parser.add_argument('--vim-id', action='store', help="specify vim network uuid")
+ datacenter_action_parser.add_argument('--vim-name', action='store', help="specify vim network name")
+ if item=='netmap-upload':
+ datacenter_action_parser.add_argument("-f","--force", action="store_true", help="do not prompt for confirmation")
+ datacenter_action_parser.set_defaults(func=datacenter_netmap_action, action=item)
+
+ for item in ("network", "tenant"):
+ if item=="network":
+ commnad_name = 'vim-net'
+ else:
+ commnad_name = 'vim-'+item
+ vim_item_list_parser = subparsers.add_parser(commnad_name + '-list', parents=[parent_parser], help="list the vim " + item + "s")
+ vim_item_list_parser.add_argument("name", nargs='?', help="name or uuid of the " + item + "s")
+ vim_item_list_parser.add_argument("--datacenter", action="store", help="specifies the datacenter")
+ vim_item_list_parser.set_defaults(func=vim_action, item=item, action="list")
+
+ vim_item_del_parser = subparsers.add_parser(commnad_name + '-delete', parents=[parent_parser], help="list the vim " + item + "s")
+ vim_item_del_parser.add_argument("name", help="name or uuid of the " + item + "s")
+ vim_item_del_parser.add_argument("--datacenter", action="store", help="specifies the datacenter")
+ vim_item_del_parser.set_defaults(func=vim_action, item=item, action="delete")
+
+ vim_item_create_parser = subparsers.add_parser(commnad_name + '-create', parents=[parent_parser], help="create a "+item+" at vim")
+ vim_item_create_parser.add_argument("file", nargs='?', help="descriptor of the %s. Must be a file or yaml/json text" % item).completer = FilesCompleter
+ vim_item_create_parser.add_argument("--name", action="store", help="name of the %s" % item )
+ vim_item_create_parser.add_argument("--datacenter", action="store", help="specifies the datacenter")
+ if item=="network":
+ vim_item_create_parser.add_argument("--type", action="store", help="type of network, data, ptp, bridge")
+ vim_item_create_parser.add_argument("--shared", action="store_true", help="Private or shared")
+ vim_item_create_parser.add_argument("--bind-net", action="store", help="For openvim datacenter type, net to be bind to, for vlan type, use sufix ':<vlan_tag>'")
+ else:
+ vim_item_create_parser.add_argument("--description", action="store", help="description of the %s" % item)
+ vim_item_create_parser.set_defaults(func=vim_action, item=item, action="create")
+
+ argcomplete.autocomplete(main_parser)
+
+ try:
+ args = main_parser.parse_args()
+ #logging info
+ level = logging.CRITICAL
+ streamformat = "%(asctime)s %(name)s %(levelname)s: %(message)s"
+ if "debug" in args and args.debug:
+ level = logging.DEBUG
+ logging.basicConfig(format=streamformat, level= level)
+ logger = logging.getLogger('mano')
+ logger.setLevel(level)
+ result = args.func(args)
+ if result == None:
+ result = 0
+ #for some reason it fails if call exit inside try instance. Need to call exit at the end !?
+ except (requests.exceptions.ConnectionError):
+ print "Connection error: not possible to contact OPENMANO-SERVER (openmanod)"
+ result = -2
+ except (KeyboardInterrupt):
+ print 'Exiting openmano'
+ result = -3
+ except (SystemExit, ArgumentParserError):
+ result = -4
+ except OpenmanoCLIError as e:
+ print str(e)
+ result = -5
+
+ #print result
+ exit(result)
+
diff --git a/models/openmano/bin/openmano_cleanup.sh b/models/openmano/bin/openmano_cleanup.sh
new file mode 100755
index 0000000..326018d
--- /dev/null
+++ b/models/openmano/bin/openmano_cleanup.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+# Run this on openmano VM to clean up all instances, scenarios and vnfs.
+
+./openmano instance-scenario-list | cut -d " " -f1 | while read line; do
+./openmano instance-scenario-delete $line -f
+done
+
+./openmano scenario-list | cut -d " " -f1 | while read line; do
+./openmano scenario-delete $line -f
+done
+
+./openmano vnf-list | cut -d " " -f1 | while read line; do
+./openmano vnf-delete $line -f
+done
diff --git a/models/openmano/python/CMakeLists.txt b/models/openmano/python/CMakeLists.txt
new file mode 100644
index 0000000..abbf139
--- /dev/null
+++ b/models/openmano/python/CMakeLists.txt
@@ -0,0 +1,13 @@
+# Creation Date: 2016/1/12
+# RIFT_IO_STANDARD_CMAKE_COPYRIGHT_HEADER(END)
+
+cmake_minimum_required(VERSION 2.8)
+
+
+rift_python_install_tree(
+ FILES
+ rift/openmano/__init__.py
+ rift/openmano/rift2openmano.py
+ rift/openmano/openmano_client.py
+ COMPONENT ${PKG_LONG_NAME}
+ PYTHON3_ONLY)
diff --git a/models/openmano/python/rift/openmano/__init__.py b/models/openmano/python/rift/openmano/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/models/openmano/python/rift/openmano/__init__.py
diff --git a/models/openmano/python/rift/openmano/openmano_client.py b/models/openmano/python/rift/openmano/openmano_client.py
new file mode 100755
index 0000000..bd34be1
--- /dev/null
+++ b/models/openmano/python/rift/openmano/openmano_client.py
@@ -0,0 +1,524 @@
+#!/usr/bin/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 re
+import subprocess
+import sys
+import tempfile
+import requests
+import json
+
+
+class OpenmanoCommandFailed(Exception):
+ pass
+
+
+class OpenmanoUnexpectedOutput(Exception):
+ pass
+
+
+class VNFExistsError(Exception):
+ pass
+
+
+class InstanceStatusError(Exception):
+ pass
+
+
+class OpenmanoHttpAPI(object):
+ def __init__(self, log, host, port, tenant):
+ self._log = log
+ self._host = host
+ self._port = port
+ self._tenant = tenant
+
+ self._session = requests.Session()
+
+ def get_instance(self, instance_uuid):
+ url = "http://{host}:{port}/openmano/{tenant}/instances/{instance}".format(
+ host=self._host,
+ port=self._port,
+ tenant=self._tenant,
+ instance=instance_uuid,
+ )
+
+ resp = self._session.get(url)
+ try:
+ resp.raise_for_status()
+ except requests.exceptions.HTTPError as e:
+ raise InstanceStatusError(e)
+
+ return resp.json()
+
+ def get_instance_vm_console_url(self, instance_uuid, vim_uuid):
+ url = "http://{host}:{port}/openmano/{tenant}/instances/{instance}/action".format(
+ host=self._host,
+ port=self._port,
+ tenant=self._tenant,
+ instance=instance_uuid,
+ )
+
+ console_types = ("novnc", "spice-html5", "xvpnvc", "rdp-html5")
+ for console_type in console_types:
+ payload_input = {"console":console_type, "vms":[vim_uuid]}
+ payload_data = json.dumps(payload_input)
+ resp = self._session.post(url, headers={'content-type': 'application/json'},
+ data=payload_data)
+ try:
+ resp.raise_for_status()
+ except requests.exceptions.HTTPError as e:
+ raise InstanceStatusError(e)
+ result = resp.json()
+ if vim_uuid in result and (result[vim_uuid]["vim_result"] == 1 or result[vim_uuid]["vim_result"] == 200):
+ return result[vim_uuid]["description"]
+
+ return None
+
+
+class OpenmanoCliAPI(object):
+ """ This class implements the necessary funtionality to interact with """
+
+ CMD_TIMEOUT = 30
+
+ def __init__(self, log, host, port, tenant):
+ self._log = log
+ self._host = host
+ self._port = port
+ self._tenant = tenant
+
+ @staticmethod
+ def openmano_cmd_path():
+ return os.path.join(
+ os.environ["RIFT_INSTALL"],
+ "usr/bin/openmano"
+ )
+
+ def _openmano_cmd(self, arg_list, expected_lines=None):
+ cmd_args = list(arg_list)
+ cmd_args.insert(0, self.openmano_cmd_path())
+
+ env = {
+ "OPENMANO_HOST": self._host,
+ "OPENMANO_PORT": str(self._port),
+ "OPENMANO_TENANT": self._tenant,
+ }
+
+ self._log.debug(
+ "Running openmano command (%s) using env (%s)",
+ subprocess.list2cmdline(cmd_args),
+ env,
+ )
+
+ proc = subprocess.Popen(
+ cmd_args,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ universal_newlines=True,
+ env=env
+ )
+ try:
+ stdout, stderr = proc.communicate(timeout=self.CMD_TIMEOUT)
+ except subprocess.TimeoutExpired:
+ self._log.error("Openmano command timed out")
+ proc.terminate()
+ stdout, stderr = proc.communicate(timeout=self.CMD_TIMEOUT)
+
+ if proc.returncode != 0:
+ self._log.error(
+ "Openmano command failed (rc=%s) with stdout: %s",
+ proc.returncode, stdout
+ )
+ raise OpenmanoCommandFailed(stdout)
+
+ self._log.debug("Openmano command completed with stdout: %s", stdout)
+
+ output_lines = stdout.splitlines()
+ if expected_lines is not None:
+ if len(output_lines) != expected_lines:
+ msg = "Expected %s lines from openmano command. Got %s" % (expected_lines, len(output_lines))
+ self._log.error(msg)
+ raise OpenmanoUnexpectedOutput(msg)
+
+ return output_lines
+
+
+ def vnf_create(self, vnf_yaml_str):
+ """ Create a Openmano VNF from a Openmano VNF YAML string """
+
+ self._log.debug("Creating VNF: %s", vnf_yaml_str)
+
+ with tempfile.NamedTemporaryFile() as vnf_file_hdl:
+ vnf_file_hdl.write(vnf_yaml_str.encode())
+ vnf_file_hdl.flush()
+
+ try:
+ output_lines = self._openmano_cmd(
+ ["vnf-create", vnf_file_hdl.name],
+ expected_lines=1
+ )
+ except OpenmanoCommandFailed as e:
+ if "already in use" in str(e):
+ raise VNFExistsError("VNF was already added")
+ raise
+
+ vnf_info_line = output_lines[0]
+ vnf_id, vnf_name = vnf_info_line.split(" ", 1)
+
+ self._log.info("VNF %s Created: %s", vnf_name, vnf_id)
+
+ return vnf_id, vnf_name
+
+ def vnf_delete(self, vnf_uuid):
+ self._openmano_cmd(
+ ["vnf-delete", vnf_uuid, "-f"],
+ )
+
+ self._log.info("VNF Deleted: %s", vnf_uuid)
+
+ def vnf_list(self):
+ try:
+ output_lines = self._openmano_cmd(
+ ["vnf-list"],
+ )
+ except OpenmanoCommandFailed as e:
+ self._log.warning("Vnf listing returned an error: %s", str(e))
+ return {}
+
+ name_uuid_map = {}
+ for line in output_lines:
+ line = line.strip()
+ uuid, name = line.split(" ", 1)
+ name_uuid_map[name] = uuid
+
+ return name_uuid_map
+
+ def ns_create(self, ns_yaml_str, name=None):
+ self._log.info("Creating NS: %s", ns_yaml_str)
+
+ with tempfile.NamedTemporaryFile() as ns_file_hdl:
+ ns_file_hdl.write(ns_yaml_str.encode())
+ ns_file_hdl.flush()
+
+ cmd_args = ["scenario-create", ns_file_hdl.name]
+ if name is not None:
+ cmd_args.extend(["--name", name])
+
+ output_lines = self._openmano_cmd(
+ cmd_args,
+ expected_lines=1
+ )
+
+ ns_info_line = output_lines[0]
+ ns_id, ns_name = ns_info_line.split(" ", 1)
+
+ self._log.info("NS %s Created: %s", ns_name, ns_id)
+
+ return ns_id, ns_name
+
+ def ns_list(self):
+ self._log.debug("Getting NS list")
+
+ try:
+ output_lines = self._openmano_cmd(
+ ["scenario-list"],
+ )
+
+ except OpenmanoCommandFailed as e:
+ self._log.warning("NS listing returned an error: %s", str(e))
+ return {}
+
+ name_uuid_map = {}
+ for line in output_lines:
+ line = line.strip()
+ uuid, name = line.split(" ", 1)
+ name_uuid_map[name] = uuid
+
+ return name_uuid_map
+
+ def ns_delete(self, ns_uuid):
+ self._log.info("Deleting NS: %s", ns_uuid)
+
+ self._openmano_cmd(
+ ["scenario-delete", ns_uuid, "-f"],
+ )
+
+ self._log.info("NS Deleted: %s", ns_uuid)
+
+ def ns_instance_list(self):
+ self._log.debug("Getting NS instance list")
+
+ try:
+ output_lines = self._openmano_cmd(
+ ["instance-scenario-list"],
+ )
+
+ except OpenmanoCommandFailed as e:
+ self._log.warning("Instance scenario listing returned an error: %s", str(e))
+ return {}
+
+ if "No scenario instances were found" in output_lines[0]:
+ self._log.debug("No openmano instances were found")
+ return {}
+
+ name_uuid_map = {}
+ for line in output_lines:
+ line = line.strip()
+ uuid, name = line.split(" ", 1)
+ name_uuid_map[name] = uuid
+
+ return name_uuid_map
+
+ def ns_instance_scenario_create(self, instance_yaml_str):
+ """ Create a Openmano NS instance from input YAML string """
+
+ self._log.debug("Instantiating instance: %s", instance_yaml_str)
+
+ with tempfile.NamedTemporaryFile() as ns_instance_file_hdl:
+ ns_instance_file_hdl.write(instance_yaml_str.encode())
+ ns_instance_file_hdl.flush()
+
+ try:
+ output_lines = self._openmano_cmd(
+ ["instance-scenario-create", ns_instance_file_hdl.name],
+ expected_lines=1
+ )
+ except OpenmanoCommandFailed as e:
+ raise
+
+ uuid, _ = output_lines[0].split(" ", 1)
+
+ self._log.info("NS Instance Created: %s", uuid)
+
+ return uuid
+
+ def ns_instantiate(self, scenario_name, instance_name, datacenter_name=None):
+ self._log.info(
+ "Instantiating NS %s using instance name %s",
+ scenario_name,
+ instance_name,
+ )
+
+ cmd_args = ["scenario-deploy", scenario_name, instance_name]
+ if datacenter_name is not None:
+ cmd_args.extend(["--datacenter", datacenter_name])
+
+ output_lines = self._openmano_cmd(
+ cmd_args,
+ expected_lines=4
+ )
+
+ uuid, _ = output_lines[0].split(" ", 1)
+
+ self._log.info("NS Instance Created: %s", uuid)
+
+ return uuid
+
+ def ns_terminate(self, ns_instance_name):
+ self._log.info("Terminating NS: %s", ns_instance_name)
+
+ self._openmano_cmd(
+ ["instance-scenario-delete", ns_instance_name, "-f"],
+ )
+
+ self._log.info("NS Instance Deleted: %s", ns_instance_name)
+
+ def datacenter_list(self):
+ lines = self._openmano_cmd(["datacenter-list",])
+
+ # The results returned from openmano are formatted with whitespace and
+ # datacenter names may contain whitespace as well, so we use a regular
+ # expression to parse each line of the results return from openmano to
+ # extract the uuid and name of a datacenter.
+ hex = '[0-9a-fA-F]'
+ uuid_pattern = '(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)'.replace('x', hex)
+ name_pattern = '(.+?)'
+ datacenter_regex = re.compile(r'{uuid}\s+\b{name}\s*$'.format(
+ uuid=uuid_pattern,
+ name=name_pattern,
+ ))
+
+ # Parse the results for the datacenter uuids and names
+ datacenters = list()
+ for line in lines:
+ result = datacenter_regex.match(line)
+ if result is not None:
+ uuid, name = result.groups()
+ datacenters.append((uuid, name))
+
+ return datacenters
+
+
+def valid_uuid(uuid_str):
+ uuid_re = re.compile(
+ "^xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx$".replace('x', '[0-9a-fA-F]')
+ )
+
+ if not uuid_re.match(uuid_str):
+ raise argparse.ArgumentTypeError("Got a valid uuid: %s" % uuid_str)
+
+ return uuid_str
+
+
+def parse_args(argv=sys.argv[1:]):
+ """ Parse the command line arguments
+
+ Arguments:
+ argv - The list of arguments to parse
+
+ Returns:
+ Argparse Namespace instance
+ """
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ '-d', '--host',
+ default='localhost',
+ help="Openmano host/ip",
+ )
+
+ parser.add_argument(
+ '-p', '--port',
+ default='9090',
+ help="Openmano port",
+ )
+
+ parser.add_argument(
+ '-t', '--tenant',
+ required=True,
+ type=valid_uuid,
+ help="Openmano tenant uuid to use",
+ )
+
+ subparsers = parser.add_subparsers(dest='command', help='openmano commands')
+
+ vnf_create_parser = subparsers.add_parser(
+ 'vnf-create',
+ help="Adds a openmano vnf into the catalog"
+ )
+ vnf_create_parser.add_argument(
+ "file",
+ help="location of the JSON file describing the VNF",
+ type=argparse.FileType('rb'),
+ )
+
+ vnf_delete_parser = subparsers.add_parser(
+ 'vnf-delete',
+ help="Deletes a openmano vnf into the catalog"
+ )
+ vnf_delete_parser.add_argument(
+ "uuid",
+ help="The vnf to delete",
+ type=valid_uuid,
+ )
+
+
+ ns_create_parser = subparsers.add_parser(
+ 'scenario-create',
+ help="Adds a openmano ns scenario into the catalog"
+ )
+ ns_create_parser.add_argument(
+ "file",
+ help="location of the JSON file describing the NS",
+ type=argparse.FileType('rb'),
+ )
+
+ ns_delete_parser = subparsers.add_parser(
+ 'scenario-delete',
+ help="Deletes a openmano ns into the catalog"
+ )
+ ns_delete_parser.add_argument(
+ "uuid",
+ help="The ns to delete",
+ type=valid_uuid,
+ )
+
+
+ ns_instance_create_parser = subparsers.add_parser(
+ 'scenario-deploy',
+ help="Deploys a openmano ns scenario into the catalog"
+ )
+ ns_instance_create_parser.add_argument(
+ "scenario_name",
+ help="The ns scenario name to deploy",
+ )
+ ns_instance_create_parser.add_argument(
+ "instance_name",
+ help="The ns instance name to deploy",
+ )
+
+
+ ns_instance_delete_parser = subparsers.add_parser(
+ 'instance-scenario-delete',
+ help="Deploys a openmano ns scenario into the catalog"
+ )
+ ns_instance_delete_parser.add_argument(
+ "instance_name",
+ help="The ns instance name to delete",
+ )
+
+
+ _ = subparsers.add_parser(
+ 'datacenter-list',
+ )
+
+ args = parser.parse_args(argv)
+
+ return args
+
+
+def main():
+ logging.basicConfig(level=logging.DEBUG)
+ logger = logging.getLogger("openmano_client.py")
+
+ if "RIFT_INSTALL" not in os.environ:
+ logger.error("Must be in rift-shell to run.")
+ sys.exit(1)
+
+ args = parse_args()
+ openmano_cli = OpenmanoCliAPI(logger, args.host, args.port, args.tenant)
+
+ if args.command == "vnf-create":
+ openmano_cli.vnf_create(args.file.read())
+
+ elif args.command == "vnf-delete":
+ openmano_cli.vnf_delete(args.uuid)
+
+ elif args.command == "scenario-create":
+ openmano_cli.ns_create(args.file.read())
+
+ elif args.command == "scenario-delete":
+ openmano_cli.ns_delete(args.uuid)
+
+ elif args.command == "scenario-deploy":
+ openmano_cli.ns_instantiate(args.scenario_name, args.instance_name)
+
+ elif args.command == "instance-scenario-delete":
+ openmano_cli.ns_terminate(args.instance_name)
+
+ elif args.command == "datacenter-list":
+ for uuid, name in openmano_cli.datacenter_list():
+ print("{} {}".format(uuid, name))
+
+ else:
+ logger.error("Unknown command: %s", args.command)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/models/openmano/python/rift/openmano/rift2openmano.py b/models/openmano/python/rift/openmano/rift2openmano.py
new file mode 100755
index 0000000..a98335b
--- /dev/null
+++ b/models/openmano/python/rift/openmano/rift2openmano.py
@@ -0,0 +1,566 @@
+#!/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 collections
+import logging
+import math
+import os
+import sys
+import tempfile
+import yaml
+
+from gi.repository import (
+ RwYang,
+ RwVnfdYang,
+ RwNsdYang,
+ )
+
+logger = logging.getLogger("rift2openmano.py")
+
+
+class VNFNotFoundError(Exception):
+ pass
+
+
+class RiftNSD(object):
+ model = RwYang.Model.create_libncx()
+ model.load_module('nsd')
+ model.load_module('rw-nsd')
+
+ def __init__(self, descriptor):
+ self._nsd = descriptor
+
+ def __str__(self):
+ return str(self._nsd)
+
+ @property
+ def name(self):
+ return self._nsd.name
+
+ @property
+ def id(self):
+ return self._nsd.id
+
+ @property
+ def vnfd_ids(self):
+ return [c.vnfd_id_ref for c in self._nsd.constituent_vnfd]
+
+ @property
+ def constituent_vnfds(self):
+ return self._nsd.constituent_vnfd
+
+ @property
+ def vlds(self):
+ return self._nsd.vld
+
+ @property
+ def cps(self):
+ return self._nsd.connection_point
+
+ @property
+ def description(self):
+ return self._nsd.description
+
+ @classmethod
+ def from_xml_file_hdl(cls, hdl):
+ hdl.seek(0)
+ descriptor = RwNsdYang.YangData_Nsd_NsdCatalog_Nsd()
+ descriptor.from_xml_v2(RiftNSD.model, hdl.read())
+ return cls(descriptor)
+
+ @classmethod
+ def from_yaml_file_hdl(cls, hdl):
+ hdl.seek(0)
+ descriptor = RwNsdYang.YangData_Nsd_NsdCatalog_Nsd()
+ descriptor.from_yaml(RiftNSD.model, hdl.read())
+ return cls(descriptor)
+
+ @classmethod
+ def from_dict(cls, nsd_dict):
+ descriptor = RwNsdYang.YangData_Nsd_NsdCatalog_Nsd.from_dict(nsd_dict)
+ return cls(descriptor)
+
+
+class RiftVNFD(object):
+ model = RwYang.Model.create_libncx()
+ model.load_module('vnfd')
+ model.load_module('rw-vnfd')
+
+ def __init__(self, descriptor):
+ self._vnfd = descriptor
+
+ def __str__(self):
+ return str(self._vnfd)
+
+ @property
+ def id(self):
+ return self._vnfd.id
+
+ @property
+ def name(self):
+ return self._vnfd.name
+
+ @property
+ def description(self):
+ return self._vnfd.description
+
+ @property
+ def cps(self):
+ return self._vnfd.connection_point
+
+ @property
+ def vdus(self):
+ return self._vnfd.vdu
+
+ @property
+ def internal_vlds(self):
+ return self._vnfd.internal_vld
+
+ @classmethod
+ def from_xml_file_hdl(cls, hdl):
+ hdl.seek(0)
+ descriptor = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd()
+ descriptor.from_xml_v2(RiftVNFD.model, hdl.read())
+ return cls(descriptor)
+
+ @classmethod
+ def from_yaml_file_hdl(cls, hdl):
+ hdl.seek(0)
+ descriptor = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd()
+ descriptor.from_yaml(RiftVNFD.model, hdl.read())
+ return cls(descriptor)
+
+ @classmethod
+ def from_dict(cls, vnfd_dict):
+ descriptor = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd.from_dict(vnfd_dict)
+ return cls(descriptor)
+
+
+def is_writable_directory(dir_path):
+ """ Returns True if dir_path is writable, False otherwise
+
+ Arguments:
+ dir_path - A directory path
+ """
+ if not os.path.exists(dir_path):
+ raise ValueError("Directory does not exist: %s", dir_path)
+
+ try:
+ testfile = tempfile.TemporaryFile(dir=dir_path)
+ testfile.close()
+ except OSError:
+ return False
+
+ return True
+
+
+def create_vnfd_from_xml_files(vnfd_file_hdls):
+ """ Create a list of RiftVNFD instances from xml file handles
+
+ Arguments:
+ vnfd_file_hdls - Rift VNFD XML file handles
+
+ Returns:
+ A list of RiftVNFD instances
+ """
+ vnfd_dict = {}
+ for vnfd_file_hdl in vnfd_file_hdls:
+ vnfd = RiftVNFD.from_xml_file_hdl(vnfd_file_hdl)
+ vnfd_dict[vnfd.id] = vnfd
+
+ return vnfd_dict
+
+def create_vnfd_from_yaml_files(vnfd_file_hdls):
+ """ Create a list of RiftVNFD instances from xml file handles
+
+ Arguments:
+ vnfd_file_hdls - Rift VNFD YAML file handles
+
+ Returns:
+ A list of RiftVNFD instances
+ """
+ vnfd_dict = {}
+ for vnfd_file_hdl in vnfd_file_hdls:
+ vnfd = RiftVNFD.from_yaml_file_hdl(vnfd_file_hdl)
+ vnfd_dict[vnfd.id] = vnfd
+
+ return vnfd_dict
+
+
+def create_nsd_from_xml_file(nsd_file_hdl):
+ """ Create a list of RiftNSD instances from xml file handles
+
+ Arguments:
+ nsd_file_hdls - Rift NSD XML file handles
+
+ Returns:
+ A list of RiftNSD instances
+ """
+ nsd = RiftNSD.from_xml_file_hdl(nsd_file_hdl)
+ return nsd
+
+def create_nsd_from_yaml_file(nsd_file_hdl):
+ """ Create a list of RiftNSD instances from yaml file handles
+
+ Arguments:
+ nsd_file_hdls - Rift NSD XML file handles
+
+ Returns:
+ A list of RiftNSD instances
+ """
+ nsd = RiftNSD.from_yaml_file_hdl(nsd_file_hdl)
+ return nsd
+
+
+def ddict():
+ return collections.defaultdict(dict)
+
+def convert_vnfd_name(vnfd_name, member_idx):
+ return vnfd_name + "__" + str(member_idx)
+
+
+def rift2openmano_nsd(rift_nsd, rift_vnfds):
+ for vnfd_id in rift_nsd.vnfd_ids:
+ if vnfd_id not in rift_vnfds:
+ raise VNFNotFoundError("VNF id %s not provided" % vnfd_id)
+
+ openmano = {}
+ openmano["name"] = rift_nsd.name
+ openmano["description"] = rift_nsd.description
+ topology = {}
+ openmano["topology"] = topology
+
+ topology["nodes"] = {}
+ for vnfd in rift_nsd.constituent_vnfds:
+ vnfd_id = vnfd.vnfd_id_ref
+ rift_vnfd = rift_vnfds[vnfd_id]
+ member_idx = vnfd.member_vnf_index
+ topology["nodes"][rift_vnfd.name + "__" + str(member_idx)] = {
+ "type": "VNF",
+ "VNF model": rift_vnfd.name
+ }
+
+ for vld in rift_nsd.vlds:
+ # Openmano has both bridge_net and dataplane_net models for network types
+ # For now, since we are using openmano in developer mode lets just hardcode
+ # to bridge_net since it won't matter anyways.
+ # topology["nodes"][vld.name] = {"type": "network", "model": "bridge_net"}
+ pass
+
+ topology["connections"] = {}
+ for vld in rift_nsd.vlds:
+
+ # Create a connections entry for each external VLD
+ topology["connections"][vld.name] = {}
+ topology["connections"][vld.name]["nodes"] = []
+
+ if vld.vim_network_name:
+ if vld.name not in topology["nodes"]:
+ topology["nodes"][vld.name] = {
+ "type": "external_network",
+ "model": vld.name,
+ }
+
+ # Add the external network to the list of connection points
+ topology["connections"][vld.name]["nodes"].append(
+ {vld.name: "0"}
+ )
+ elif vld.provider_network.has_field("physical_network"):
+ # Add the external datacenter network to the topology
+ # node list if it isn't already added
+ ext_net_name = vld.provider_network.physical_network
+ ext_net_name_with_seg = ext_net_name
+ if vld.provider_network.has_field("segmentation_id"):
+ ext_net_name_with_seg += ":{}".format(vld.provider_network.segmentation_id)
+
+ if ext_net_name not in topology["nodes"]:
+ topology["nodes"][ext_net_name] = {
+ "type": "external_network",
+ "model": ext_net_name_with_seg,
+ }
+
+ # Add the external network to the list of connection points
+ topology["connections"][vld.name]["nodes"].append(
+ {ext_net_name: "0"}
+ )
+
+
+ for vnfd_cp in vld.vnfd_connection_point_ref:
+
+ # Get the RIFT VNF for this external VLD connection point
+ vnfd = rift_vnfds[vnfd_cp.vnfd_id_ref]
+
+ # For each VNF in this connection, use the same interface name
+ topology["connections"][vld.name]["type"] = "link"
+ # Vnf ref is the vnf name with the member_vnf_idx appended
+ member_idx = vnfd_cp.member_vnf_index_ref
+ vnf_ref = vnfd.name + "__" + str(member_idx)
+ topology["connections"][vld.name]["nodes"].append(
+ {
+ vnf_ref: vnfd_cp.vnfd_connection_point_ref
+ }
+ )
+
+ return openmano
+
+
+def rift2openmano_vnfd(rift_vnfd):
+ openmano_vnf = {"vnf":{}}
+ vnf = openmano_vnf["vnf"]
+
+ vnf["name"] = rift_vnfd.name
+ vnf["description"] = rift_vnfd.description
+
+ vnf["external-connections"] = []
+
+ def find_vdu_and_ext_if_by_cp_ref(cp_ref_name):
+ for vdu in rift_vnfd.vdus:
+ for ext_if in vdu.external_interface:
+ if ext_if.vnfd_connection_point_ref == cp_ref_name:
+ return vdu, ext_if
+
+ raise ValueError("External connection point reference %s not found" % cp_ref_name)
+
+ def find_vdu_and_int_if_by_cp_ref(cp_ref_id):
+ for vdu in rift_vnfd.vdus:
+ for int_if in vdu.internal_interface:
+ if int_if.vdu_internal_connection_point_ref == cp_ref_id:
+ return vdu, int_if
+
+ raise ValueError("Internal connection point reference %s not found" % cp_ref_id)
+
+ def rift2openmano_if_type(rift_type):
+ if rift_type == "OM_MGMT":
+ return "mgmt"
+ elif rift_type == "VIRTIO":
+ return "bridge"
+ else:
+ return "data"
+
+ # Add all external connections
+ for cp in rift_vnfd.cps:
+ # Find the VDU and and external interface for this connection point
+ vdu, ext_if = find_vdu_and_ext_if_by_cp_ref(cp.name)
+ connection = {
+ "name": cp.name,
+ "type": rift2openmano_if_type(ext_if.virtual_interface.type_yang),
+ "VNFC": vdu.name,
+ "local_iface_name": ext_if.name,
+ "description": "%s iface on VDU %s" % (ext_if.name, vdu.name),
+ }
+
+ vnf["external-connections"].append(connection)
+
+ # Add all internal networks
+ for vld in rift_vnfd.internal_vlds:
+ connection = {
+ "name": vld.name,
+ "description": vld.description,
+ "type": "data",
+ "elements": [],
+ }
+
+ # Add the specific VDU connection points
+ for int_cp_ref in vld.internal_connection_point_ref:
+ vdu, int_if = find_vdu_and_int_if_by_cp_ref(int_cp_ref)
+ connection["elements"].append({
+ "VNFC": vdu.name,
+ "local_iface_name": int_if.name,
+ })
+ if "internal-connections" not in vnf:
+ vnf["internal-connections"] = []
+
+ vnf["internal-connections"].append(connection)
+
+ # Add VDU's
+ vnf["VNFC"] = []
+ for vdu in rift_vnfd.vdus:
+ vnfc = {
+ "name": vdu.name,
+ "description": vdu.name,
+ "VNFC image": vdu.image if os.path.isabs(vdu.image) else "/var/images/{}".format(vdu.image),
+ "numas": [{
+ "memory": max(int(vdu.vm_flavor.memory_mb/1024), 1),
+ "interfaces":[],
+ }],
+ "bridge-ifaces": [],
+ }
+
+ numa_node_policy = vdu.guest_epa.numa_node_policy
+ if numa_node_policy.has_field("node"):
+ numa_node = numa_node_policy.node[0]
+
+ if numa_node.has_field("paired_threads"):
+ if numa_node.paired_threads.has_field("num_paired_threads"):
+ vnfc["numas"][0]["paired-threads"] = numa_node.paired_threads.num_paired_threads
+ if len(numa_node.paired_threads.paired_thread_ids) > 0:
+ vnfc["numas"][0]["paired-threads-id"] = []
+ for pair in numa_node.paired_threads.paired_thread_ids:
+ vnfc["numas"][0]["paired-threads-id"].append(
+ [pair.thread_a, pair.thread_b]
+ )
+
+ else:
+ if vdu.vm_flavor.has_field("vcpu_count"):
+ vnfc["numas"][0]["cores"] = max(vdu.vm_flavor.vcpu_count, 1)
+
+ if vdu.has_field("hypervisor_epa"):
+ vnfc["hypervisor"] = {}
+ if vdu.hypervisor_epa.has_field("type"):
+ if vdu.hypervisor_epa.type_yang == "REQUIRE_KVM":
+ vnfc["hypervisor"]["type"] = "QEMU-kvm"
+
+ if vdu.hypervisor_epa.has_field("version"):
+ vnfc["hypervisor"]["version"] = vdu.hypervisor_epa.version
+
+ if vdu.has_field("host_epa"):
+ vnfc["processor"] = {}
+ if vdu.host_epa.has_field("om_cpu_model_string"):
+ vnfc["processor"]["model"] = vdu.host_epa.om_cpu_model_string
+ if vdu.host_epa.has_field("om_cpu_feature"):
+ vnfc["processor"]["features"] = []
+ for feature in vdu.host_epa.om_cpu_feature:
+ vnfc["processor"]["features"].append(feature)
+
+
+ if vdu.vm_flavor.has_field("storage_gb"):
+ vnfc["disk"] = vdu.vm_flavor.storage_gb
+
+ vnf["VNFC"].append(vnfc)
+
+ for int_if in list(vdu.internal_interface) + list(vdu.external_interface):
+ intf = {
+ "name": int_if.name,
+ }
+ if int_if.virtual_interface.has_field("vpci"):
+ intf["vpci"] = int_if.virtual_interface.vpci
+
+ if int_if.virtual_interface.type_yang in ["VIRTIO", "OM_MGMT"]:
+ vnfc["bridge-ifaces"].append(intf)
+
+ elif int_if.virtual_interface.type_yang == "SR-IOV":
+ intf["bandwidth"] = "10 Gbps"
+ intf["dedicated"] = "yes:sriov"
+ vnfc["numas"][0]["interfaces"].append(intf)
+
+ elif int_if.virtual_interface.type_yang == "PCI_PASSTHROUGH":
+ intf["bandwidth"] = "10 Gbps"
+ intf["dedicated"] = "yes"
+ if "interfaces" not in vnfc["numas"][0]:
+ vnfc["numas"][0]["interfaces"] = []
+ vnfc["numas"][0]["interfaces"].append(intf)
+ else:
+ raise ValueError("Interface type %s not supported" % int_if.virtual_interface)
+
+ if int_if.virtual_interface.has_field("bandwidth"):
+ if int_if.virtual_interface.bandwidth != 0:
+ bps = int_if.virtual_interface.bandwidth
+
+ # Calculate the bits per second conversion
+ for x in [('M', 1000000), ('G', 1000000000)]:
+ if bps/x[1] >= 1:
+ intf["bandwidth"] = "{} {}bps".format(math.ceil(bps/x[1]), x[0])
+
+
+ return openmano_vnf
+
+
+def parse_args(argv=sys.argv[1:]):
+ """ Parse the command line arguments
+
+ Arguments:
+ arv - The list of arguments to parse
+
+ Returns:
+ Argparse Namespace instance
+ """
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ '-o', '--outdir',
+ default='-',
+ help="Directory to output converted descriptors. Default is stdout",
+ )
+
+ parser.add_argument(
+ '-n', '--nsd-file-hdl',
+ metavar="nsd_xml_file",
+ type=argparse.FileType('r'),
+ help="Rift NSD Descriptor File",
+ )
+
+ parser.add_argument(
+ '-v', '--vnfd-file-hdls',
+ metavar="vnfd_xml_file",
+ action='append',
+ type=argparse.FileType('r'),
+ help="Rift VNFD Descriptor File",
+ )
+
+ args = parser.parse_args(argv)
+
+ if not os.path.exists(args.outdir):
+ os.makedirs(args.outdir)
+
+ if not is_writable_directory(args.outdir):
+ logging.error("Directory %s is not writable", args.outdir)
+ sys.exit(1)
+
+ return args
+
+
+def write_yaml_to_file(name, outdir, desc_dict):
+ file_name = "%s.yaml" % name
+ yaml_str = yaml.dump(desc_dict)
+ if outdir == "-":
+ sys.stdout.write(yaml_str)
+ return
+
+ file_path = os.path.join(outdir, file_name)
+ dir_path = os.path.dirname(file_path)
+ if not os.path.exists(dir_path):
+ os.makedirs(dir_path)
+
+ with open(file_path, "w") as hdl:
+ hdl.write(yaml_str)
+
+ logger.info("Wrote descriptor to %s", file_path)
+
+
+def main(argv=sys.argv[1:]):
+ args = parse_args(argv)
+
+ nsd = None
+ if args.vnfd_file_hdls is not None:
+ vnf_dict = create_vnfd_from_xml_files(args.vnfd_file_hdls)
+
+ if args.nsd_file_hdl is not None:
+ nsd = create_nsd_from_xml_file(args.nsd_file_hdl)
+
+ openmano_nsd = rift2openmano_nsd(nsd, vnf_dict)
+
+ write_yaml_to_file(openmano_nsd["name"], args.outdir, openmano_nsd)
+
+ for vnf in vnf_dict.values():
+ openmano_vnf = rift2openmano_vnfd(vnf)
+ write_yaml_to_file(openmano_vnf["vnf"]["name"], args.outdir, openmano_vnf)
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.WARNING)
+ main()
diff --git a/models/openmano/src/CMakeLists.txt b/models/openmano/src/CMakeLists.txt
new file mode 100644
index 0000000..949bb8b
--- /dev/null
+++ b/models/openmano/src/CMakeLists.txt
@@ -0,0 +1,82 @@
+#
+# 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.
+#
+# Author(s): Anil Gunturu
+# Creation Date: 2014/12/11
+#
+
+cmake_minimum_required(VERSION 2.8)
+
+configure_file(
+ ${CMAKE_CURRENT_SOURCE_DIR}/generate_tidgen_packages.sh.in
+ ${CMAKE_CURRENT_BINARY_DIR}/generate_tidgen_packages.sh
+ ESCAPE_QUOTES @ONLY
+ )
+
+add_custom_command(
+ OUTPUT
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_2sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_2sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_4sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_4sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_2sriov_no_ctrlnet.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_2sriov_no_ctrlnet.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_4sriov_no_ctrlnet.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_4sriov_no_ctrlnet.tar.gz
+
+ COMMAND
+ ${CMAKE_CURRENT_BINARY_DIR}/generate_tidgen_packages.sh
+
+ DEPENDS
+ ${RIFT_SUBMODULE_SOURCE_ROOT}/models/openmano/test/tidgen_ns_2sriov.yaml
+ ${RIFT_SUBMODULE_SOURCE_ROOT}/models/openmano/test/tidgen_ns_4sriov.yaml
+ ${RIFT_SUBMODULE_SOURCE_ROOT}/models/openmano/test/tidgen_vnf_2sriov.yaml
+ ${RIFT_SUBMODULE_SOURCE_ROOT}/models/openmano/test/tidgen_vnf_4sriov.yaml
+ ${RIFT_SUBMODULE_SOURCE_ROOT}/models/openmano/test/tidgen_ns_2sriov_no_ctrlnet.yaml
+ ${RIFT_SUBMODULE_SOURCE_ROOT}/models/openmano/test/tidgen_ns_4sriov_no_ctrlnet.yaml
+ ${RIFT_SUBMODULE_SOURCE_ROOT}/models/openmano/test/tidgen_vnf_2sriov_no_ctrlnet.yaml
+ ${RIFT_SUBMODULE_SOURCE_ROOT}/models/openmano/test/tidgen_vnf_4sriov_no_ctrlnet.yaml
+ ${RIFT_SUBMODULE_SOURCE_ROOT}/models/openmano/src/openmano2rift.py
+ )
+
+add_custom_target(tidgen ALL
+ DEPENDS
+ mano_yang
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_2sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_2sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_4sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_4sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_2sriov_no_ctrlnet.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_2sriov_no_ctrlnet.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_4sriov_no_ctrlnet.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_4sriov_no_ctrlnet.tar.gz
+ )
+
+install(
+ FILES
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_4sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_4sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_2sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_2sriov.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_4sriov_no_ctrlnet.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_4sriov_no_ctrlnet.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/2tidgenMWC_2sriov_no_ctrlnet.tar.gz
+ ${CMAKE_CURRENT_BINARY_DIR}/tidgenMWC_2sriov_no_ctrlnet.tar.gz
+
+
+ DESTINATION
+ usr/rift/mano/examples/tidgen_ns
+ COMPONENT ${PKG_LONG_NAME}
+ )
diff --git a/models/openmano/src/generate_tidgen_packages.sh.in b/models/openmano/src/generate_tidgen_packages.sh.in
new file mode 100755
index 0000000..208d2cd
--- /dev/null
+++ b/models/openmano/src/generate_tidgen_packages.sh.in
@@ -0,0 +1,40 @@
+#! /bin/bash
+
+set -e
+
+SOURCE_DIR=@CMAKE_CURRENT_SOURCE_DIR@
+BINARY_DIR=@CMAKE_CURRENT_BINARY_DIR@
+PROJECT_TOP_DIR=@PROJECT_TOP_DIR@
+
+# These paths are needed for finding the overrides and so files
+PYTHONPATH=${PYTHONPATH}:@RIFT_SUBMODULE_SOURCE_ROOT@/rwvcs/ra:@RIFT_SUBMODULE_BINARY_ROOT@/models/plugins/yang
+PYTHON3PATH=${PYTHON3PATH}:@RIFT_SUBMODULE_SOURCE_ROOT@/rwvcs/ra:@RIFT_SUBMODULE_BINARY_ROOT@/models/plugins/yang
+LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:@RIFT_SUBMODULE_BINARY_ROOT@/models/plugins/yang
+
+# Remove any old directories
+rm -rf ${BINARY_DIR}/2tidgenMWC_4sriov
+rm -rf ${BINARY_DIR}/tidgenMWC_4sriov
+rm -rf ${BINARY_DIR}/2tidgenMWC_2sriov
+rm -rf ${BINARY_DIR}/tidgenMWC_2sriov
+rm -rf ${BINARY_DIR}/2tidgenMWC_2sriov_noctrlnet
+rm -rf ${BINARY_DIR}/tidgenMWC_2sriov_noctrlnet
+rm -rf ${BINARY_DIR}/2tidgenMWC_4sriov_noctrlnet
+rm -rf ${BINARY_DIR}/tidgenMWC_4sriov_noctrlnet
+
+
+# Generate the descriptors
+${SOURCE_DIR}/openmano2rift.py -o ${BINARY_DIR} @RIFT_SUBMODULE_SOURCE_ROOT@/models/openmano/test/tidgen_ns_4sriov.yaml @RIFT_SUBMODULE_SOURCE_ROOT@/models/openmano/test/tidgen_vnf_4sriov.yaml
+${SOURCE_DIR}/openmano2rift.py -o ${BINARY_DIR} @RIFT_SUBMODULE_SOURCE_ROOT@/models/openmano/test/tidgen_ns_2sriov.yaml @RIFT_SUBMODULE_SOURCE_ROOT@/models/openmano/test/tidgen_vnf_2sriov.yaml
+${SOURCE_DIR}/openmano2rift.py -o ${BINARY_DIR} @RIFT_SUBMODULE_SOURCE_ROOT@/models/openmano/test/tidgen_ns_4sriov_no_ctrlnet.yaml @RIFT_SUBMODULE_SOURCE_ROOT@/models/openmano/test/tidgen_vnf_4sriov_no_ctrlnet.yaml
+${SOURCE_DIR}/openmano2rift.py -o ${BINARY_DIR} @RIFT_SUBMODULE_SOURCE_ROOT@/models/openmano/test/tidgen_ns_2sriov_no_ctrlnet.yaml @RIFT_SUBMODULE_SOURCE_ROOT@/models/openmano/test/tidgen_vnf_2sriov_no_ctrlnet.yaml
+
+
+# Generate the tar files
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} tidgenMWC_4sriov
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} 2tidgenMWC_4sriov
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} tidgenMWC_2sriov
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} 2tidgenMWC_2sriov
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} tidgenMWC_2sriov_no_ctrlnet
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} 2tidgenMWC_2sriov_no_ctrlnet
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} tidgenMWC_4sriov_no_ctrlnet
+${RIFT_INSTALL}/usr/rift/toolchain/cmake/bin/generate_descriptor_pkg.sh ${BINARY_DIR} 2tidgenMWC_4sriov_no_ctrlnet
diff --git a/models/openmano/src/openmano2rift.py b/models/openmano/src/openmano2rift.py
new file mode 100755
index 0000000..503ad89
--- /dev/null
+++ b/models/openmano/src/openmano2rift.py
@@ -0,0 +1,485 @@
+#!/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 itertools
+import logging
+import os
+import sys
+import tempfile
+import uuid
+import yaml
+
+import gi
+gi.require_version('RwYang', '1.0')
+gi.require_version('RwVnfdYang', '1.0')
+gi.require_version('RwNsdYang', '1.0')
+from gi.repository import (
+ RwYang,
+ RwVnfdYang,
+ RwNsdYang,
+ )
+
+logging.basicConfig(level=logging.WARNING)
+logger = logging.getLogger("openmano2rift.py")
+
+
+class UnknownVNFError(Exception):
+ pass
+
+
+class DescriptorFileWriter(object):
+ def __init__(self, module_list, output_dir, output_format):
+ self._model = RwYang.Model.create_libncx()
+ for module in module_list:
+ self._model.load_module(module)
+
+ self._output_dir = output_dir
+ self._output_format = output_format
+
+ def _write_file(self, file_name, output):
+ file_path = os.path.join(self._output_dir, file_name)
+ dir_path = os.path.dirname(file_path)
+ if not os.path.exists(dir_path):
+ os.makedirs(dir_path)
+
+ with open(file_path, "w") as hdl:
+ hdl.write(output)
+
+ logger.info("Wrote descriptor to %s", file_path)
+
+ def _write_json(self, descriptor, subdir):
+ self._write_file(
+ '%s.json' % os.path.join(descriptor.name, subdir, descriptor.name),
+ descriptor.descriptor.to_json(self._model)
+ )
+
+ def _write_xml(self, descriptor, subdir):
+ self._write_file(
+ '%s.xml' % os.path.join(descriptor.name, subdir, descriptor.name),
+ descriptor.descriptor.to_xml_v2(self._model, pretty_print=True)
+ )
+
+ def _write_yaml(self, descriptor, subdir):
+ self._write_file(
+ '%s.yaml' % os.path.join(descriptor.name, subdir, descriptor.name),
+ yaml.dump(descriptor.descriptor.as_dict()),
+ )
+
+ def write_descriptor(self, descriptor, subdir=""):
+ if self._output_format == 'json':
+ self._write_json(descriptor, subdir=subdir)
+
+ elif self._output_format == 'xml':
+ self._write_xml(descriptor, subdir=subdir)
+
+ elif self._output_format == 'yaml':
+ self._write_yaml(descriptor, subdir=subdir)
+
+
+class RiftManoDescriptor(object):
+ def __init__(self, openmano=None):
+ self.openmano = openmano
+ self.descriptor = None
+
+
+class RiftNS(RiftManoDescriptor):
+ def __init__(self, openmano=None):
+ super().__init__(openmano)
+ self.nsd_catalog = None
+ self.nsd = None
+ self.name = None
+
+ def get_vnfd_id(self, vnf_list, vnf_name):
+ for vnf in vnf_list:
+ if vnf.name == vnf_name:
+ return vnf.vnfd.id
+
+ # Didn't find the vnf just return the vnf_name
+ return vnf_name
+
+ def openmano2rift(self, vnf_list):
+ self.descriptor = RwNsdYang.YangData_Nsd_NsdCatalog()
+ openmano_nsd = self.openmano.dictionary
+ self.name = openmano_nsd['name']
+ nsd = self.descriptor.nsd.add()
+ nsd.id = str(uuid.uuid1())
+ nsd.name = self.name
+ nsd.short_name = self.name
+ nsd.description = openmano_nsd['description']
+
+ nodes = openmano_nsd['topology']['nodes']
+ connections = openmano_nsd['topology']['connections']
+
+ def create_consituent_vnfds():
+ vnf_member_index_dict = {}
+
+ vnfd_idx_gen = itertools.count(1)
+ for key in nodes:
+ node = nodes[key]
+ if node['type'] != 'VNF':
+ continue
+
+ vnfd_idx = next(vnfd_idx_gen)
+ constituent_vnfd = nsd.constituent_vnfd.add()
+ constituent_vnfd.member_vnf_index = vnfd_idx
+ constituent_vnfd.vnfd_id_ref = self.get_vnfd_id(vnf_list, node['VNF model'])
+ vnf_member_index_dict[key] = vnfd_idx
+
+ return vnf_member_index_dict
+
+ def create_connections(vnf_member_index_dict):
+ keys = connections.keys()
+ for key in keys:
+ # TODO: Need clarification from TEF
+ # skip the mgmtnet in OpenMANO descriptor
+ if key == 'mgmtnet':
+ continue
+ conn = connections[key]
+ vld = nsd.vld.add()
+ vld.from_dict(dict(
+ id=str(uuid.uuid1()),
+ name=key,
+ short_name=key,
+ type_yang='ELAN',
+ ))
+
+ nodes = conn['nodes']
+ for node, node_keys in [(node, node.keys()) for node in nodes]:
+ for node_key in node_keys:
+ topo_node = openmano_nsd['topology']['nodes'][node_key]
+ if topo_node['type'] == 'VNF':
+ cpref = vld.vnfd_connection_point_ref.add()
+ cpref.from_dict(dict(
+ member_vnf_index_ref=vnf_member_index_dict[node_key],
+ vnfd_id_ref=self.get_vnfd_id(vnf_list, topo_node['VNF model']),
+ #vnfd_id_ref=topo_node['VNF model'],
+ vnfd_connection_point_ref=node[node_key],
+ ))
+ if key != 'control-net':
+ vld.provider_network.physical_network = 'physnet_sriov'
+ vld.provider_network.overlay_type = 'VLAN'
+
+ vnf_member_index_dict = create_consituent_vnfds()
+ create_connections(vnf_member_index_dict)
+
+
+class RiftVnfd(RiftManoDescriptor):
+ def __init__(self, openmano=None):
+ super().__init__(openmano)
+ self.vnfd_catalog = None
+ self.vnfd = None
+
+ def find_external_connection(self, vdu_name, if_name):
+ """
+ Find if the vdu interface has an external connection.
+ """
+ openmano_vnfd = self.openmano.dictionary['vnf']
+ if 'external-connections' not in openmano_vnfd:
+ return None
+
+ ext_conn_list = openmano_vnfd['external-connections']
+ for ext_conn in ext_conn_list:
+ if ((ext_conn['VNFC'] == vdu_name) and
+ (ext_conn['local_iface_name'] == if_name)):
+ return ext_conn
+
+ return None
+
+ def openmano2rift(self):
+ self.descriptor = RwVnfdYang.YangData_Vnfd_VnfdCatalog()
+ vnfd = self.descriptor.vnfd.add()
+ self.vnfd = vnfd
+ vnfd.id = str(uuid.uuid1())
+
+ openmano_vnfd = self.openmano.dictionary['vnf']
+ self.name = openmano_vnfd['name']
+ vnfd.name = self.name
+ if "description" in openmano_vnfd:
+ vnfd.description = openmano_vnfd['description']
+
+ # Parse and add all the external connection points
+ if 'external-connections' in openmano_vnfd:
+ ext_conn_list = openmano_vnfd['external-connections']
+
+ for ext_conn in ext_conn_list:
+ # TODO: Fix this
+ if ext_conn['name'] == 'eth0':
+ continue
+ conn_point = vnfd.connection_point.add()
+ conn_point.name = ext_conn['name']
+ conn_point.type_yang = 'VPORT'
+
+ # TODO: Need a concrete example of how openmano descriptor
+ # uses internal connections.
+ if 'internal-connections' in openmano_vnfd:
+ int_conn_list = openmano_vnfd['internal-connections']
+
+ def add_external_interfaces(vdu, numa):
+ if 'interfaces' not in numa:
+ return
+
+ numa_if_list = numa['interfaces']
+ for numa_if in numa_if_list:
+ ext_conn = self.find_external_connection(vdu.name, numa_if['name'])
+ if not ext_conn:
+ continue
+
+ ext_iface = vdu.external_interface.add()
+ ext_iface.name = numa_if['name']
+ ext_iface.vnfd_connection_point_ref = ext_conn['name']
+ ext_iface.virtual_interface.vpci = numa_if['vpci']
+ if numa_if['dedicated'] == 'no':
+ ext_iface.virtual_interface.type_yang = 'SR_IOV'
+ else:
+ ext_iface.virtual_interface.type_yang = 'PCI_PASSTHROUGH'
+
+ vnfc_list = openmano_vnfd['VNFC']
+ for vnfc in vnfc_list:
+ vdu = vnfd.vdu.add()
+ vdu_dict = dict(
+ id=str(uuid.uuid1()),
+ name=vnfc['name'],
+ image=vnfc['VNFC image'],
+ vm_flavor={"storage_gb": vnfc["disk"] if "disk" in vnfc else 20},
+ )
+ if "description" in vnfc:
+ vdu_dict["description"] = vnfc['description']
+
+ vdu.from_dict(vdu_dict)
+
+ vnfd.mgmt_interface.vdu_id = vdu.id
+
+ numa_list = vnfc['numas']
+ memory = 0
+ vcpu_count = 0
+ numa_node_cnt = 0
+
+ for numa in numa_list:
+ node = vdu.guest_epa.numa_node_policy.node.add()
+ node.id = numa_node_cnt
+ # node.memory_mb = int(numa['memory']) * 1024
+ numa_node_cnt += 1
+
+ memory = memory + node.memory_mb
+ # Need a better explanation of "cores", "paired-threads", "threads"
+ # in openmano descriptor. Particularly how they map to cpu and
+ # thread pinning policies
+ if 'paired-threads' in numa:
+ vcpu_count = vcpu_count + int(numa['paired-threads']) * 2
+
+ if 'cores' in numa:
+ vcpu_count = vcpu_count + int(numa['cores'])
+
+ add_external_interfaces(vdu, numa)
+
+
+ # vdu.vm_flavor.memory_mb = memory
+ vdu.vm_flavor.memory_mb = 12 * 1024
+ vdu.vm_flavor.vcpu_count = vcpu_count
+ vdu.guest_epa.numa_node_policy.node_cnt = numa_node_cnt
+ vdu.guest_epa.numa_node_policy.mem_policy = 'STRICT'
+ vdu.guest_epa.mempage_size = 'LARGE'
+ vdu.guest_epa.cpu_pinning_policy = 'DEDICATED'
+ vdu.guest_epa.cpu_thread_pinning_policy = 'PREFER'
+
+ # TODO: Enable hypervisor epa
+ # vdu.hypervisor_epa.version = vnfc['hypervisor']['version']
+ # if vnfc['hypervisor']['type'] == 'QEMU-kvm':
+ # vdu.hypervisor_epa.type_yang = 'REQUIRE_KVM'
+ # else:
+ # vdu.hypervisor_epa.type_yang = 'PREFER_KVM'
+
+ # TODO: Enable host epa
+ # vdu.host_epa.cpu_feature = vnfc['processor']['features']
+
+ # Parse the bridge interfaces
+ if 'bridge-ifaces' in vnfc:
+ bridge_ifaces = vnfc['bridge-ifaces']
+
+
+ for bridge_iface in bridge_ifaces:
+ # TODO: Fix this
+ if bridge_iface['name'] == 'eth0':
+ continue
+
+ ext_conn = self.find_external_connection(vdu.name,
+ bridge_iface['name'])
+ if ext_conn:
+ ext_iface = vdu.external_interface.add()
+ ext_iface.name = bridge_iface['name']
+ ext_iface.vnfd_connection_point_ref = ext_conn['name']
+ if 'vpci' in bridge_iface:
+ ext_iface.virtual_interface.vpci = bridge_iface['vpci']
+ ext_iface.virtual_interface.type_yang = 'VIRTIO'
+
+ # set vpci information for the 'default' network
+ # TODO: This needs to be inferred gtom bridge ifaces,
+ # need input from TEF
+ vdu.mgmt_vpci = "0000:00:0a.0"
+
+
+class OpenManoDescriptor(object):
+ def __init__(self, yaml_file_hdl):
+ self.dictionary = yaml.load(yaml_file_hdl)
+
+ @property
+ def type(self):
+ """ The descriptor type (ns or vnf)"""
+ if 'vnf' in self.dictionary:
+ return "vnf"
+ else:
+ return "ns"
+
+ def dump(self):
+ """ Dump the Descriptor out to stdout """
+ print(yaml.dump(self.dictionary))
+
+
+def is_writable_directory(dir_path):
+ """ Returns True if dir_path is writable, False otherwise
+
+ Arguments:
+ dir_path - A directory path
+ """
+ if not os.path.exists(dir_path):
+ raise ValueError("Directory does not exist: %s", dir_path)
+
+ try:
+ testfile = tempfile.TemporaryFile(dir=dir_path)
+ testfile.close()
+ except OSError:
+ return False
+
+ return True
+
+
+def create_vnfs_from_yaml_files(yaml_file_hdls):
+ """ Create a list of RiftVnfd instances from yaml file handles
+
+ Arguments:
+ yaml_file_hdls - OpenMano Yaml file handles
+
+ Returns:
+ A list of RiftVnfd instances
+ """
+ vnf_list = []
+ for yaml_file_hdl in yaml_file_hdls:
+ openmano = OpenManoDescriptor(yaml_file_hdl)
+ yaml_file_hdl.seek(0)
+
+ if openmano.type != "vnf":
+ continue
+
+ vnf = RiftVnfd(openmano)
+ vnf.openmano2rift()
+ vnf_list.append(vnf)
+
+ return vnf_list
+
+
+def create_ns_from_yaml_files(yaml_file_hdls, vnf_list):
+ """ Create a list of RiftNS instances from yaml file handles
+
+ Arguments:
+ yaml_file_hdls - OpenMano Yaml file handles
+ vnf_list - list of RiftVnfd
+
+ Returns:
+ A list of RiftNS instances
+ """
+ ns_list = []
+ for yaml_file_hdl in yaml_file_hdls:
+ openmano = OpenManoDescriptor(yaml_file_hdl)
+ if openmano.type != "ns":
+ continue
+
+ net_svc = RiftNS(openmano)
+ net_svc.openmano2rift(vnf_list)
+ ns_list.append(net_svc)
+
+ return ns_list
+
+
+def parse_args(argv=sys.argv[1:]):
+ """ Parse the command line arguments
+
+ Arguments:
+ arv - The list of arguments to parse
+
+ Returns:
+ Argparse Namespace instance
+
+ """
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ '-o', '--outdir',
+ default='.',
+ help="Directory to output converted descriptors",
+ )
+
+ parser.add_argument(
+ '-f', '--format',
+ choices=['yaml', 'xml', 'json'],
+ default='xml',
+ help="Descriptor output format",
+ )
+
+ parser.add_argument(
+ 'yaml_file_hdls',
+ metavar="yaml_file",
+ nargs="+",
+ type=argparse.FileType('r'),
+ help="OpenMano YAML Descriptor File",
+ )
+
+ args = parser.parse_args(argv)
+
+ if not os.path.exists(args.outdir):
+ os.makedirs(args.outdir)
+
+ if not is_writable_directory(args.outdir):
+ logging.error("Directory %s is not writable", args.outdir)
+ sys.exit(1)
+
+ return args
+
+
+def main(argv=sys.argv[1:]):
+ args = parse_args(argv)
+
+ vnf_list = create_vnfs_from_yaml_files(args.yaml_file_hdls)
+ ns_list = create_ns_from_yaml_files(args.yaml_file_hdls, vnf_list)
+
+ writer = DescriptorFileWriter(
+ module_list=['nsd', 'rw-nsd', 'vnfd', 'rw-vnfd'],
+ output_dir=args.outdir,
+ output_format=args.format,
+ )
+
+ for nw_svc in ns_list:
+ writer.write_descriptor(nw_svc, subdir="nsd")
+
+ for vnf in vnf_list:
+ writer.write_descriptor(vnf, subdir="vnfd")
+
+
+if __name__ == "__main__":
+ main()
+
diff --git a/models/openmano/test/tidgen_ns_2sriov.yaml b/models/openmano/test/tidgen_ns_2sriov.yaml
new file mode 100644
index 0000000..9c39816
--- /dev/null
+++ b/models/openmano/test/tidgen_ns_2sriov.yaml
@@ -0,0 +1,34 @@
+---
+name: 2tidgenMWC_2sriov
+description: scenario with 2 tidgenMWC VNFs
+topology:
+ nodes:
+ tidgen1: #VNF name
+ type: VNF
+ VNF model: tidgenMWC_2sriov #VNF type
+ tidgen2:
+ type: VNF
+ VNF model: tidgenMWC_2sriov
+ default: #Name of external network
+ type: external_network
+ model: default
+ connections:
+ mgmtnet:
+ nodes:
+ - tidgen1: eth0
+ - tidgen2: eth0
+ datanet0:
+ nodes:
+ - tidgen1: xe0
+ - tidgen2: xe0
+ datanet1:
+ nodes:
+ - tidgen1: xe1
+ - tidgen2: xe1
+ control-net:
+ nodes:
+ - default: null
+ - tidgen1: eth1
+ - tidgen2: eth1
+
+
diff --git a/models/openmano/test/tidgen_ns_2sriov_no_ctrlnet.yaml b/models/openmano/test/tidgen_ns_2sriov_no_ctrlnet.yaml
new file mode 100644
index 0000000..d174895
--- /dev/null
+++ b/models/openmano/test/tidgen_ns_2sriov_no_ctrlnet.yaml
@@ -0,0 +1,29 @@
+---
+name: 2tidgenMWC_2sriov_no_ctrlnet
+description: scenario with 2 tidgenMWC VNFs
+topology:
+ nodes:
+ tidgen1: #VNF name
+ type: VNF
+ VNF model: tidgenMWC_2sriov_no_ctrlnet #VNF type
+ tidgen2:
+ type: VNF
+ VNF model: tidgenMWC_2sriov_no_ctrlnet
+ default: #Name of external network
+ type: external_network
+ model: default
+ connections:
+ mgmtnet:
+ nodes:
+ - tidgen1: eth0
+ - tidgen2: eth0
+ datanet0:
+ nodes:
+ - tidgen1: xe0
+ - tidgen2: xe0
+ datanet1:
+ nodes:
+ - tidgen1: xe1
+ - tidgen2: xe1
+
+
diff --git a/models/openmano/test/tidgen_ns_4sriov.yaml b/models/openmano/test/tidgen_ns_4sriov.yaml
new file mode 100644
index 0000000..4034f8a
--- /dev/null
+++ b/models/openmano/test/tidgen_ns_4sriov.yaml
@@ -0,0 +1,42 @@
+---
+name: 2tidgenMWC_4sriov
+description: scenario with 2 tidgenMWC VNFs
+topology:
+ nodes:
+ tidgen1: #VNF name
+ type: VNF
+ VNF model: tidgenMWC_4sriov #VNF type
+ tidgen2:
+ type: VNF
+ VNF model: tidgenMWC_4sriov
+ default: #Name of external network
+ type: external_network
+ model: default
+ connections:
+ mgmtnet:
+ nodes:
+ - tidgen1: eth0
+ - tidgen2: eth0
+ datanet0:
+ nodes:
+ - tidgen1: xe0
+ - tidgen2: xe0
+ datanet1:
+ nodes:
+ - tidgen1: xe1
+ - tidgen2: xe1
+ datanet2:
+ nodes:
+ - tidgen1: xe2
+ - tidgen2: xe2
+ datanet3:
+ nodes:
+ - tidgen1: xe3
+ - tidgen2: xe3
+ control-net:
+ nodes:
+ - default: null
+ - tidgen1: eth1
+ - tidgen2: eth1
+
+
diff --git a/models/openmano/test/tidgen_ns_4sriov_no_ctrlnet.yaml b/models/openmano/test/tidgen_ns_4sriov_no_ctrlnet.yaml
new file mode 100644
index 0000000..ee07a26
--- /dev/null
+++ b/models/openmano/test/tidgen_ns_4sriov_no_ctrlnet.yaml
@@ -0,0 +1,33 @@
+---
+name: 2tidgenMWC_4sriov_no_ctrlnet
+description: scenario with 2 tidgenMWC VNFs
+topology:
+ nodes:
+ tidgen1: #VNF name
+ type: VNF
+ VNF model: tidgenMWC_4sriov_no_ctrlnet #VNF type
+ tidgen2:
+ type: VNF
+ VNF model: tidgenMWC_4sriov_no_ctrlnet
+ default: #Name of external network
+ type: external_network
+ model: default
+ connections:
+ datanet0:
+ nodes:
+ - tidgen1: xe0
+ - tidgen2: xe0
+ datanet1:
+ nodes:
+ - tidgen1: xe1
+ - tidgen2: xe1
+ datanet2:
+ nodes:
+ - tidgen1: xe2
+ - tidgen2: xe2
+ datanet3:
+ nodes:
+ - tidgen1: xe3
+ - tidgen2: xe3
+
+
diff --git a/models/openmano/test/tidgen_vnf_2sriov.yaml b/models/openmano/test/tidgen_vnf_2sriov.yaml
new file mode 100644
index 0000000..983490b
--- /dev/null
+++ b/models/openmano/test/tidgen_vnf_2sriov.yaml
@@ -0,0 +1,58 @@
+---
+vnf:
+ name: tidgenMWC_2sriov
+ description: tidgen for MWC2016; 12G 10 cores
+ class: TID
+ external-connections:
+ - name: eth0
+ type: bridge
+ VNFC: tidgenMWC-VM
+ local_iface_name: eth0
+ description: Bridge interface, request for dhcp
+ - name: eth1
+ type: mgmt # "mgmt"(autoconnect to management net), "bridge", "data"
+ VNFC: tidgenMWC-VM # Virtual Machine this interface belongs to
+ local_iface_name: eth1 # name inside this Virtual Machine
+ description: Other management interface for general use
+ - name: xe0
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe0
+ description: Data interface 1
+ - name: xe1
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe1
+ description: Data interface 2
+ VNFC: # Virtual machine array
+ - name: tidgenMWC-VM # name of Virtual Machine
+ disk: 10
+ description: tidgen for MWC 12G 10 cores
+ # VNFC image: /mnt/powervault/virtualization/vnfs/tid/tidgenMWC.qcow2
+ VNFC image: tidgenMWC
+ image metadata: {"use_incremental": "no" } #is already incremental
+ processor: #Optional, leave it
+ model: Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz
+ features: ["64b", "iommu", "lps", "tlbps", "hwsv", "dioc", "ht"]
+ hypervisor: #Optional, leave it
+ type: QEMU-kvm
+ version: "10002|12001|2.6.32-358.el6.x86_64"
+ numas:
+ - paired-threads: 5 # "cores", "paired-threads", "threads"
+ memory: 12 # GBytes
+ interfaces:
+ - name: xe0
+ vpci: "0000:00:10.0"
+ dedicated: "no" # "yes"(passthrough), "no"(sriov)
+ bandwidth: 10 Gbps
+ - name: xe1
+ vpci: "0000:00:11.0"
+ dedicated: "no"
+ bandwidth: 10 Gbps
+ bridge-ifaces:
+ - name: eth0
+ vpci: "0000:00:0a.0" # Optional
+ bandwidth: 1 Mbps # Optional, informative only
+ - name: eth1
+ vpci: "0000:00:0b.0"
+ bandwidth: 1 Mbps
diff --git a/models/openmano/test/tidgen_vnf_2sriov_no_ctrlnet.yaml b/models/openmano/test/tidgen_vnf_2sriov_no_ctrlnet.yaml
new file mode 100644
index 0000000..6c7df27
--- /dev/null
+++ b/models/openmano/test/tidgen_vnf_2sriov_no_ctrlnet.yaml
@@ -0,0 +1,50 @@
+---
+vnf:
+ name: tidgenMWC_2sriov_no_ctrlnet
+ description: tidgen for MWC2016; 12G 10 cores
+ class: TID
+ external-connections:
+ - name: eth0
+ type: bridge
+ VNFC: tidgenMWC-VM
+ local_iface_name: eth0
+ description: Bridge interface, request for dhcp
+ - name: xe0
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe0
+ description: Data interface 1
+ - name: xe1
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe1
+ description: Data interface 2
+ VNFC: # Virtual machine array
+ - name: tidgenMWC-VM # name of Virtual Machine
+ disk: 10
+ description: tidgen for MWC 12G 10 cores
+ # VNFC image: /mnt/powervault/virtualization/vnfs/tid/tidgenMWC.qcow2
+ VNFC image: tidgenMWC
+ image metadata: {"use_incremental": "no" } #is already incremental
+ processor: #Optional, leave it
+ model: Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz
+ features: ["64b", "iommu", "lps", "tlbps", "hwsv", "dioc", "ht"]
+ hypervisor: #Optional, leave it
+ type: QEMU-kvm
+ version: "10002|12001|2.6.32-358.el6.x86_64"
+ numas:
+ - paired-threads: 5 # "cores", "paired-threads", "threads"
+ memory: 12 # GBytes
+ interfaces:
+ - name: xe0
+ vpci: "0000:00:10.0"
+ dedicated: "no" # "yes"(passthrough), "no"(sriov)
+ bandwidth: 10 Gbps
+ - name: xe1
+ vpci: "0000:00:11.0"
+ dedicated: "no"
+ bandwidth: 10 Gbps
+ bridge-ifaces:
+ - name: eth0
+ vpci: "0000:00:0a.0"
+ bandwidth: 1 Mbps
diff --git a/models/openmano/test/tidgen_vnf_4sriov.yaml b/models/openmano/test/tidgen_vnf_4sriov.yaml
new file mode 100644
index 0000000..af315d2
--- /dev/null
+++ b/models/openmano/test/tidgen_vnf_4sriov.yaml
@@ -0,0 +1,76 @@
+---
+vnf:
+ name: tidgenMWC_4sriov
+ description: tidgen for MWC2016; 12G 10 cores
+ class: TID
+ external-connections:
+ - name: eth0
+ type: bridge
+ VNFC: tidgenMWC-VM
+ local_iface_name: eth0
+ description: Bridge interface, request for dhcp
+ - name: eth1
+ type: mgmt # "mgmt"(autoconnect to management net), "bridge", "data"
+ VNFC: tidgenMWC-VM # Virtual Machine this interface belongs to
+ local_iface_name: eth1 # name inside this Virtual Machine
+ description: Other management interface for general use
+ - name: xe0
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe0
+ description: Data interface 1
+ - name: xe1
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe1
+ description: Data interface 2
+ - name: xe2
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe2
+ description: Data interface 3
+ - name: xe3
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe3
+ description: Data interface 4
+ VNFC: # Virtual machine array
+ - name: tidgenMWC-VM # name of Virtual Machine
+ disk: 10
+ description: tidgen for MWC 12G 10 cores
+ # VNFC image: /mnt/powervault/virtualization/vnfs/tid/tidgenMWC.qcow2
+ VNFC image: tidgenMWC
+ image metadata: {"use_incremental": "no" } #is already incremental
+ processor: #Optional, leave it
+ model: Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz
+ features: ["64b", "iommu", "lps", "tlbps", "hwsv", "dioc", "ht"]
+ hypervisor: #Optional, leave it
+ type: QEMU-kvm
+ version: "10002|12001|2.6.32-358.el6.x86_64"
+ numas:
+ - paired-threads: 5 # "cores", "paired-threads", "threads"
+ memory: 12 # GBytes
+ interfaces:
+ - name: xe0
+ vpci: "0000:00:10.0"
+ dedicated: "no" # "yes"(passthrough), "no"(sriov)
+ bandwidth: 10 Gbps
+ - name: xe1
+ vpci: "0000:00:11.0"
+ dedicated: "no"
+ bandwidth: 10 Gbps
+ - name: xe2
+ vpci: "0000:00:12.0"
+ dedicated: "no" # "yes"(passthrough), "no"(sriov)
+ bandwidth: 10 Gbps
+ - name: xe3
+ vpci: "0000:00:13.0"
+ dedicated: "no"
+ bandwidth: 10 Gbps
+ bridge-ifaces:
+ - name: eth0
+ vpci: "0000:00:0a.0" # Optional
+ bandwidth: 1 Mbps # Optional, informative only
+ - name: eth1
+ vpci: "0000:00:0b.0" # Optional
+ bandwidth: 1 Mbps # Optional, informative only
diff --git a/models/openmano/test/tidgen_vnf_4sriov_no_ctrlnet.yaml b/models/openmano/test/tidgen_vnf_4sriov_no_ctrlnet.yaml
new file mode 100644
index 0000000..9cb9c4d
--- /dev/null
+++ b/models/openmano/test/tidgen_vnf_4sriov_no_ctrlnet.yaml
@@ -0,0 +1,68 @@
+---
+vnf:
+ name: tidgenMWC_4sriov_no_ctrlnet
+ description: tidgen for MWC2016; 12G 10 cores
+ class: TID
+ external-connections:
+ - name: eth0
+ type: bridge
+ VNFC: tidgenMWC-VM
+ local_iface_name: eth0
+ description: Bridge interface, request for dhcp
+ - name: xe0
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe0
+ description: Data interface 1
+ - name: xe1
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe1
+ description: Data interface 2
+ - name: xe2
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe2
+ description: Data interface 3
+ - name: xe3
+ type: data
+ VNFC: tidgenMWC-VM
+ local_iface_name: xe3
+ description: Data interface 4
+ VNFC: # Virtual machine array
+ - name: tidgenMWC-VM # name of Virtual Machine
+ disk: 10
+ description: tidgen for MWC 12G 10 cores
+ # VNFC image: /mnt/powervault/virtualization/vnfs/tid/tidgenMWC.qcow2
+ VNFC image: tidgenMWC
+ image metadata: {"use_incremental": "no" } #is already incremental
+ processor: #Optional, leave it
+ model: Intel(R) Xeon(R) CPU E5-4620 0 @ 2.20GHz
+ features: ["64b", "iommu", "lps", "tlbps", "hwsv", "dioc", "ht"]
+ hypervisor: #Optional, leave it
+ type: QEMU-kvm
+ version: "10002|12001|2.6.32-358.el6.x86_64"
+ numas:
+ - paired-threads: 5 # "cores", "paired-threads", "threads"
+ memory: 12 # GBytes
+ interfaces:
+ - name: xe0
+ vpci: "0000:00:10.0"
+ dedicated: "no" # "yes"(passthrough), "no"(sriov)
+ bandwidth: 10 Gbps
+ - name: xe1
+ vpci: "0000:00:11.0"
+ dedicated: "no"
+ bandwidth: 10 Gbps
+ - name: xe2
+ vpci: "0000:00:12.0"
+ dedicated: "no" # "yes"(passthrough), "no"(sriov)
+ bandwidth: 10 Gbps
+ - name: xe3
+ vpci: "0000:00:13.0"
+ dedicated: "no"
+ bandwidth: 10 Gbps
+ bridge-ifaces:
+ - name: eth0
+ vpci: "0000:00:0a.0" # Optional
+ bandwidth: 1 Mbps # Optional, informative only