New translation commands for SOL006: recursive package-translate, descriptor-translate
[osm/osmclient.git] / osmclient / scripts / osm.py
index 1df00d6..d9136f3 100755 (executable)
@@ -71,7 +71,7 @@ def check_client_version(obj, what, version='sol005'):
 
 def get_project(project_list, item):
     # project_list = ctx.obj.project.list()
-    item_project_list = item.get('_admin').get('projects_read')
+    item_project_list = item.get('_admin', {}).get('projects_read')
     project_id = 'None'
     project_name = 'None'
     if item_project_list:
@@ -84,6 +84,15 @@ def get_project(project_list, item):
     return project_id, project_name
 
 
+def get_vim_name(vim_list, vim_id):
+    vim_name = '-'
+    for v in vim_list:
+        if v['uuid'] == vim_id:
+            vim_name = v['name']
+            break
+    return vim_name
+
+
 @click.group(context_settings=dict(help_option_names=['-h', '--help'], max_content_width=160))
 @click.option('--hostname',
               default="127.0.0.1",
@@ -342,7 +351,10 @@ def ns_list(ctx, filter, long):
          'deployment status',
          'configuration status'])
         project_list = ctx.obj.project.list()
-        vim_list = ctx.obj.vim.list()
+        try:
+            vim_list = ctx.obj.vim.list()
+        except:
+            vim_list = []
     else:
         table = PrettyTable(
         ['ns instance name',
@@ -363,20 +375,12 @@ def ns_list(ctx, filter, long):
             if long:
                 deployment_status = summarize_deployment_status(nsr.get('deploymentStatus'))
                 config_status = summarize_config_status(nsr.get('configurationStatus'))
-                project_id = nsr.get('_admin').get('projects_read')[0]
-                project_name = '-'
-                for p in project_list:
-                    if p['_id'] == project_id:
-                        project_name = p['name']
-                        break
+                project_id, project_name = get_project(project_list, nsr)
                 #project = '{} ({})'.format(project_name, project_id)
                 project = project_name
                 vim_id = nsr.get('datacenter')
-                vim_name = '-'
-                for v in vim_list:
-                    if v['uuid'] == vim_id:
-                        vim_name = v['name']
-                        break
+                vim_name = get_vim_name(vim_list, vim_id)
+
                 #vim = '{} ({})'.format(vim_name, vim_id)
                 vim = vim_name
             if 'currentOperation' in nsr:
@@ -444,7 +448,7 @@ def nsd_list(ctx, filter, long):
         else:
             table = PrettyTable(['nsd name', 'id'])
         for nsd in resp:
-            name = nsd.get('name','-')
+            name = nsd.get('id', '-')
             if long:
                 onb_state = nsd['_admin'].get('onboardingState','-')
                 op_state = nsd['_admin'].get('operationalState','-')
@@ -484,6 +488,26 @@ def nsd_list2(ctx, filter, long):
     nsd_list(ctx, filter, long)
 
 
+def pkg_repo_list(ctx, pkgtype, filter, repo, long):
+    resp = ctx.obj.osmrepo.pkg_list(pkgtype, filter, repo)
+    if long:
+        table = PrettyTable(['nfpkg name', 'vendor', 'version', 'latest', 'description', 'repository'])
+    else:
+        table = PrettyTable(['nfpkg name', 'repository'])
+    for vnfd in resp:
+        name = vnfd.get('id', vnfd.get('name','-'))
+        repository = vnfd.get('repository')
+        if long:
+            vendor = vnfd.get('provider', vnfd.get('vendor'))
+            version = vnfd.get('version')
+            description = vnfd.get('description')
+            latest = vnfd.get('latest')
+            table.add_row([name, vendor, version, latest, description, repository])
+        else:
+            table.add_row([name, repository])
+        table.align = 'l'
+    print(table)
+
 def vnfd_list(ctx, nf_type, filter, long):
     logger.debug("")
     if nf_type:
@@ -513,23 +537,24 @@ def vnfd_list(ctx, nf_type, filter, long):
     fullclassname = ctx.obj.__module__ + "." + ctx.obj.__class__.__name__
     if fullclassname == 'osmclient.sol005.client.Client':
         if long:
-            table = PrettyTable(['nfpkg name', 'id', 'vendor', 'version', 'onboarding state', 'operational state',
+            table = PrettyTable(['nfpkg name', 'id', 'desc type', 'vendor', 'version', 'onboarding state', 'operational state',
                                   'usage state', 'date', 'last update'])
         else:
-            table = PrettyTable(['nfpkg name', 'id'])
+            table = PrettyTable(['nfpkg name', 'id', 'desc type'])
         for vnfd in resp:
-            name = vnfd['name'] if 'name' in vnfd else '-'
+            name = vnfd.get('id', vnfd.get('name','-'))
+            descriptor_type = 'sol006' if 'product-name' in vnfd else 'rel8'
             if long:
                 onb_state = vnfd['_admin'].get('onboardingState','-')
                 op_state = vnfd['_admin'].get('operationalState','-')
-                vendor = vnfd.get('vendor')
+                vendor = vnfd.get('provider', vnfd.get('vendor'))
                 version = vnfd.get('version')
                 usage_state = vnfd['_admin'].get('usageState','-')
                 date = datetime.fromtimestamp(vnfd['_admin']['created']).strftime("%Y-%m-%dT%H:%M:%S")
                 last_update = datetime.fromtimestamp(vnfd['_admin']['modified']).strftime("%Y-%m-%dT%H:%M:%S")
-                table.add_row([name, vnfd['_id'], vendor, version, onb_state, op_state, usage_state, date, last_update])
+                table.add_row([name, vnfd['_id'], descriptor_type, vendor, version, onb_state, op_state, usage_state, date, last_update])
             else:
-                table.add_row([name, vnfd['_id']])
+                table.add_row([name, vnfd['_id'], descriptor_type])
     else:
         table = PrettyTable(['nfpkg name', 'id'])
         for vnfd in resp:
@@ -579,29 +604,6 @@ def nfpkg_list(ctx, nf_type, filter, long):
     #     exit(1)
 
 
-def pkg_repo_list(ctx, pkgtype, filter, repo, long):
-    if filter:
-        filter='&'.join(filter)
-    resp = ctx.obj.osmrepo.pkg_list(pkgtype, filter, repo)
-    if long:
-        table = PrettyTable(['nfpkg name', 'vendor', 'version', 'latest', 'description', 'repository'])
-    else:
-        table = PrettyTable(['nfpkg name', 'repository'])
-    for vnfd in resp:
-        name = vnfd.get('name', '-')
-        repository = vnfd.get('repository')
-        if long:
-            vendor = vnfd.get('vendor')
-            version = vnfd.get('version')
-            description = vnfd.get('description')
-            latest = vnfd.get('latest')
-            table.add_row([name, vendor, version, latest, description, repository])
-        else:
-            table.add_row([name, repository])
-        table.align = 'l'
-    print(table)
-
-
 @cli_osm.command(name='vnfpkg-repo-list', short_help='list all xNF from OSM repositories')
 @click.option('--filter', default=None, multiple=True,
               help='restricts the list to the NFpkg matching the filter')
@@ -614,7 +616,6 @@ def nfpkg_repo_list1(ctx, filter, repo, long):
     pkgtype = 'vnf'
     pkg_repo_list(ctx, pkgtype, filter, repo, long)
 
-
 @cli_osm.command(name='nfpkg-repo-list', short_help='list all xNF from OSM repositories')
 @click.option('--filter', default=None, multiple=True,
               help='restricts the list to the NFpkg matching the filter')
@@ -628,32 +629,6 @@ def nfpkg_repo_list2(ctx, filter, repo, long):
     pkg_repo_list(ctx, pkgtype, filter, repo, long)
 
 
-@cli_osm.command(name='nsd-repo-list', short_help='list all NS from OSM repositories')
-@click.option('--filter', default=None, multiple=True,
-              help='restricts the list to the NS matching the filter')
-@click.option('--repo', default=None,
-              help='restricts the list to a particular OSM repository')
-@click.option('--long', is_flag=True, help='get more details')
-@click.pass_context
-def nspkg_repo_list(ctx, filter, repo, long):
-    """list xNF packages from OSM repositories"""
-    pkgtype = 'ns'
-    pkg_repo_list(ctx, pkgtype, filter, repo, long)
-
-
-@cli_osm.command(name='nspkg-repo-list', short_help='list all NS from OSM repositories')
-@click.option('--filter', default=None, multiple=True,
-              help='restricts the list to the NS matching the filter')
-@click.option('--repo', default=None,
-              help='restricts the list to a particular OSM repository')
-@click.option('--long', is_flag=True, help='get more details')
-@click.pass_context
-def nspkg_repo_list2(ctx, filter, repo, long):
-    """list xNF packages from OSM repositories"""
-    pkgtype = 'ns'
-    pkg_repo_list(ctx, pkgtype, filter, repo, long)
-
-
 def vnf_list(ctx, ns, filter, long):
     # try:
     if ns or filter:
@@ -717,6 +692,29 @@ def vnf_list1(ctx, ns, filter, long):
     logger.debug("")
     vnf_list(ctx, ns, filter, long)
 
+@cli_osm.command(name='nsd-repo-list', short_help='list all NS from OSM repositories')
+@click.option('--filter', default=None, multiple=True,
+              help='restricts the list to the NS matching the filter')
+@click.option('--repo', default=None,
+              help='restricts the list to a particular OSM repository')
+@click.option('--long', is_flag=True, help='get more details')
+@click.pass_context
+def nspkg_repo_list(ctx, filter, repo, long):
+    """list xNF packages from OSM repositories"""
+    pkgtype = 'ns'
+    pkg_repo_list(ctx, pkgtype, filter, repo, long)
+
+@cli_osm.command(name='nspkg-repo-list', short_help='list all NS from OSM repositories')
+@click.option('--filter', default=None, multiple=True,
+              help='restricts the list to the NS matching the filter')
+@click.option('--repo', default=None,
+              help='restricts the list to a particular OSM repository')
+@click.option('--long', is_flag=True, help='get more details')
+@click.pass_context
+def nspkg_repo_list2(ctx, filter, repo, long):
+    """list xNF packages from OSM repositories"""
+    pkgtype = 'ns'
+    pkg_repo_list(ctx, pkgtype, filter, repo, long)
 
 @cli_osm.command(name='nf-list', short_help='list all NF instances')
 @click.option('--ns', default=None, help='NS instance id or name to restrict the NF list')
@@ -1139,7 +1137,6 @@ def vnfd_show2(ctx, name, literal):
     logger.debug("")
     vnfd_show(ctx, name, literal)
 
-
 @cli_osm.command(name='vnfpkg-repo-show', short_help='shows the details of a NF package in an OSM repository')
 @click.option('--literal', is_flag=True,
               help='print literally, no pretty table')
@@ -1183,7 +1180,6 @@ def nsd_repo_show(ctx, name, repo, version, literal=None, filter=None):
     pkgtype = 'ns'
     pkg_repo_show(ctx, pkgtype, name, repo, version, filter, literal)
 
-
 @cli_osm.command(name='nspkg-repo-show', short_help='shows the details of a NS package in an OSM repository')
 @click.option('--literal', is_flag=True,
               help='print literally, no pretty table')
@@ -1357,7 +1353,6 @@ def vnf_show(ctx, name, literal, filter, kdu):
         return
 
     table = PrettyTable(['field', 'value'])
-
     for k, v in list(resp.items()):
         if not filter or k in filter:
             table.add_row([k, wrap_text(text=json.dumps(v,indent=2),width=100)])
@@ -3155,23 +3150,30 @@ def k8scluster_list(ctx, filter, literal, long):
         project_list = ctx.obj.project.list()
     else:
         table = PrettyTable(['Name', 'Id', 'VIM', 'Operational State', 'Op. state details'])
+    try:
+        vim_list = ctx.obj.vim.list()
+    except:
+        vim_list = []
     for cluster in resp:
+        logger.debug('Cluster details: {}'.format(yaml.safe_dump(cluster)))
+        vim_name = get_vim_name(vim_list, cluster['vim_account'])
+        #vim_info = '{} ({})'.format(vim_name,cluster['vim_account'])
+        vim_info = vim_name
         op_state_details = "Helm: {}\nJuju: {}".format(
-                           cluster["_admin"].get("helm-chart", "-").get("operationalState", "-"),
-                           cluster["_admin"].get("juju-bundle", "-").get("operationalState", "-"))
+                           cluster["_admin"].get("helm-chart", {}).get("operationalState", "-"),
+                           cluster["_admin"].get("juju-bundle", {}).get("operationalState", "-"))
         if long:
-            logger.debug('Cluster details: {}'.format(yaml.safe_dump(cluster)))
             project_id, project_name = get_project(project_list, cluster)
             #project_info = '{} ({})'.format(project_name, project_id)
             project_info = project_name
             detailed_status = cluster["_admin"].get("detailed-status","-")
             table.add_row([cluster['name'], cluster['_id'], project_info,
-                           cluster['k8s_version'], cluster['vim_account'],
+                           cluster['k8s_version'], vim_info,
                            json.dumps(cluster['nets']), cluster["_admin"]["operationalState"],
                            op_state_details, trunc_text(cluster.get('description') or '', 40),
                            wrap_text(text=detailed_status, width=40)])
         else:
-            table.add_row([cluster['name'], cluster['_id'], cluster['vim_account'],
+            table.add_row([cluster['name'], cluster['_id'], vim_info,
                            cluster["_admin"]["operationalState"], op_state_details])
     table.align = 'l'
     print(table)
@@ -4222,7 +4224,7 @@ def role_show(ctx, name):
 
 
 @cli_osm.command(name='package-create',
-             short_help='Create a package descriptor')
+             short_help='Create empty NS package structure')
 @click.argument('package-type')
 @click.argument('package-name')
 @click.option('--base-directory',
@@ -4288,6 +4290,7 @@ def package_create(ctx,
     """
 
     # try:
+    logger.debug("")
     check_client_version(ctx.obj, ctx.command.name)
     print("Creating the {} structure: {}/{}".format(package_type.upper(), base_directory, package_name))
     resp = ctx.obj.package_tool.create(package_type,
@@ -4310,7 +4313,7 @@ def package_create(ctx,
     #     exit(1)
 
 @cli_osm.command(name='package-validate',
-             short_help='Validate a package descriptor')
+                 short_help='Validate descriptors given a base directory')
 @click.argument('base-directory',
                 default=".",
                 required=False)
@@ -4318,19 +4321,25 @@ def package_create(ctx,
               default=True,
               help='The activated recursive option will validate the yaml files'
                    ' within the indicated directory and in its subdirectories')
+@click.option('--old',
+              is_flag=True,
+              default=False,
+              help='Validates also the descriptors using the previous OSM format (pre SOL006)')
 @click.pass_context
 def package_validate(ctx,
                      base_directory,
-                     recursive):
+                     recursive,
+                     old):
     """
     Validate descriptors given a base directory.
 
     \b
-    BASE_DIRECTORY: Stub folder for NS, VNF or NST package.
+    BASE_DIRECTORY: Base folder for NS, VNF or NST package.
     """
     # try:
+    logger.debug("")
     check_client_version(ctx.obj, ctx.command.name)
-    results = ctx.obj.package_tool.validate(base_directory, recursive)
+    results = ctx.obj.package_tool.validate(base_directory, recursive, old)
     table = PrettyTable()
     table.field_names = ["TYPE", "PATH", "VALID", "ERROR"]
     # Print the dictionary generated by the validation function
@@ -4345,6 +4354,47 @@ def package_validate(ctx,
     #     print("ERROR: {}".format(inst))
     #     exit(1)
 
+@cli_osm.command(name='package-translate',
+                 short_help='Translate descriptors given a base directory')
+@click.argument('base-directory',
+                default=".",
+                required=False)
+@click.option('--recursive/--no-recursive',
+              default=True,
+              help='The activated recursive option will translate the yaml files'
+                   ' within the indicated directory and in its subdirectories')
+@click.option('--dryrun',
+              is_flag=True,
+              default=False,
+              help='Do not translate yet, only make a dry-run to test translation')
+@click.pass_context
+def package_translate(ctx,
+                     base_directory,
+                     recursive,
+                     dryrun):
+    """
+    Translate descriptors given a base directory.
+
+    \b
+    BASE_DIRECTORY: Stub folder for NS, VNF or NST package.
+    """
+    logger.debug("")
+    check_client_version(ctx.obj, ctx.command.name)
+    results = ctx.obj.package_tool.translate(base_directory, recursive, dryrun)
+    table = PrettyTable()
+    table.field_names = ["CURRENT TYPE", "NEW TYPE", "PATH", "VALID", "TRANSLATED", "ERROR"]
+    # Print the dictionary generated by the validation function
+    for result in results:
+        table.add_row([result["current type"], result["new type"], result["path"], result["valid"], result["translated"], result["error"]])
+    table.sortby = "TRANSLATED"
+    table.align["PATH"] = "l"
+    table.align["TYPE"] = "l"
+    table.align["ERROR"] = "l"
+    print(table)
+    # except ClientException as inst:
+    #     print("ERROR: {}".format(inst))
+    #     exit(1)
+
 @cli_osm.command(name='package-build',
              short_help='Build the tar.gz of the package')
 @click.argument('package-folder')
@@ -4366,6 +4416,7 @@ def package_build(ctx,
     PACKAGE_FOLDER: Folder of the NS, VNF or NST to be packaged
     """
     # try:
+    logger.debug("")
     check_client_version(ctx.obj, ctx.command.name)
     results = ctx.obj.package_tool.build(package_folder,
                                          skip_validation=skip_validation,
@@ -4375,6 +4426,24 @@ def package_build(ctx,
     #     print("ERROR: {}".format(inst))
     #     exit(1)
 
+@cli_osm.command(name='descriptor-translate',
+                 short_help='Translate input descriptor file from Rel EIGHT OSM descriptors to SOL006 and prints in standard output')
+@click.argument('descriptor-file',
+                required=True)
+@click.pass_context
+def descriptor_translate(ctx,
+                         descriptor_file):
+    """
+    Translate input descriptor.
+
+    \b
+    DESCRIPTOR_FILE: Descriptor file for NS, VNF or Network Slice.
+    """
+    logger.debug("")
+    check_client_version(ctx.obj, ctx.command.name)
+    result = ctx.obj.package_tool.descriptor_translate(descriptor_file)
+    print(result)
+
 
 def cli():
     try: