1 # Copyright 2017-2018 Sandvine
2 # Copyright 2018 Telefonica
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
22 from osmclient
import client
23 from osmclient
.common
.exceptions
import ClientException
, NotFound
24 from osmclient
.common
.utils
import validate_uuid4
25 from prettytable
import PrettyTable
34 from datetime
import datetime
35 from typing
import Any
, Dict
38 def wrap_text(text
, width
):
39 wrapper
= textwrap
.TextWrapper(width
=width
)
40 lines
= text
.splitlines()
41 return "\n".join(map(wrapper
.fill
, lines
))
44 def trunc_text(text
, length
):
45 if len(text
) > length
:
46 return text
[: (length
- 3)] + "..."
51 def check_client_version(obj
, what
, version
="sol005"):
53 Checks the version of the client object and raises error if it not the expected.
55 :param obj: the client object
56 :what: the function or command under evaluation (used when an error is raised)
58 :raises ClientError: if the specified version does not match the client version
61 fullclassname
= obj
.__module
__ + "." + obj
.__class
__.__name
__
62 message
= 'The following commands or options are only supported with the option "--sol005": {}'.format(
66 message
= 'The following commands or options are not supported when using option "--sol005": {}'.format(
69 if fullclassname
!= "osmclient.{}.client.Client".format(version
):
70 raise ClientException(message
)
74 def get_project(project_list
, item
):
75 # project_list = ctx.obj.project.list()
76 item_project_list
= item
.get("_admin", {}).get("projects_read")
80 for p1
in item_project_list
:
82 for p2
in project_list
:
83 if p2
["_id"] == project_id
:
84 project_name
= p2
["name"]
85 return project_id
, project_name
86 return project_id
, project_name
89 def get_vim_name(vim_list
, vim_id
):
92 if v
["uuid"] == vim_id
:
98 def create_config(config_file
, json_string
):
100 Combines a YAML or JSON file with a JSON string into a Python3 structure
101 It loads the YAML or JSON file 'cfile' into a first dictionary.
102 It loads the JSON string into a second dictionary.
103 Then it updates the first dictionary with the info in the second dictionary.
104 If the field is present in both cfile and cdict, the field in cdict prevails.
105 If both cfile and cdict are None, it returns an empty dict (i.e. {})
109 with
open(config_file
, "r") as cf
:
110 config
= yaml
.safe_load(cf
.read())
112 cdict
= yaml
.safe_load(json_string
)
113 for k
, v
in cdict
.items():
119 context_settings
=dict(help_option_names
=["-h", "--help"], max_content_width
=160)
124 envvar
="OSM_HOSTNAME",
125 help="hostname of server. " + "Also can set OSM_HOSTNAME in environment",
131 help="user (defaults to admin). " + "Also can set OSM_USER in environment",
136 envvar
="OSM_PASSWORD",
137 help="password (defaults to admin). " + "Also can set OSM_PASSWORD in environment",
142 envvar
="OSM_PROJECT",
143 help="project (defaults to admin). " + "Also can set OSM_PROJECT in environment",
149 help="increase verbosity (-v INFO, -vv VERBOSE, -vvv DEBUG)",
151 @click.option("--all-projects", default
=None, is_flag
=True, help="include all projects")
153 "--public/--no-public",
155 help="flag for public items (packages, instances, VIM accounts, etc.)",
158 "--project-domain-name",
159 "project_domain_name",
161 envvar
="OSM_PROJECT_DOMAIN_NAME",
162 help="project domain name for keystone authentication (default to None). "
163 + "Also can set OSM_PROJECT_DOMAIN_NAME in environment",
166 "--user-domain-name",
169 envvar
="OSM_USER_DOMAIN_NAME",
170 help="user domain name for keystone authentication (default to None). "
171 + "Also can set OSM_USER_DOMAIN_NAME in environment",
174 def cli_osm(ctx
, **kwargs
):
176 hostname
= kwargs
.pop("hostname", None)
180 "either hostname option or OSM_HOSTNAME "
181 + "environment variable needs to be specified"
186 kwargs
= {k
: v
for k
, v
in kwargs
.items() if v
is not None}
187 sol005
= os
.getenv("OSM_SOL005", True)
188 ctx
.obj
= client
.Client(host
=hostname
, sol005
=sol005
, **kwargs
)
189 logger
= logging
.getLogger("osmclient")
197 @cli_osm.command(name
="ns-list", short_help
="list all NS instances")
202 help="restricts the list to the NS instances matching the filter.",
207 help="get more details of the NS (project, vim, deployment status, configuration status.",
210 def ns_list(ctx
, filter, long):
211 """list all NS instances
215 --filter filterExpr Restricts the list to the NS instances matching the filter
218 filterExpr consists of one or more strings formatted according to "simpleFilterExpr",
219 concatenated using the "&" character:
222 filterExpr := <simpleFilterExpr>["&"<simpleFilterExpr>]*
223 simpleFilterExpr := <attrName>["."<attrName>]*["."<op>]"="<value>[","<value>]*
224 op := "eq" | "neq" | "gt" | "lt" | "gte" | "lte" | "cont" | "ncont"
226 value := scalar value
230 * zero or more occurrences
231 ? zero or one occurrence
232 [] grouping of expressions to be used with ? and *
233 "" quotation marks for marking string constants
237 "AttrName" is the name of one attribute in the data type that defines the representation
238 of the resource. The dot (".") character in "simpleFilterExpr" allows concatenation of
239 <attrName> entries to filter by attributes deeper in the hierarchy of a structured document.
240 "Op" stands for the comparison operator. If the expression has concatenated <attrName>
241 entries, it means that the operator "op" is applied to the attribute addressed by the last
242 <attrName> entry included in the concatenation. All simple filter expressions are combined
243 by the "AND" logical operator. In a concatenation of <attrName> entries in a <simpleFilterExpr>,
244 the rightmost "attrName" entry in a "simpleFilterExpr" is called "leaf attribute". The
245 concatenation of all "attrName" entries except the leaf attribute is called the "attribute
246 prefix". If an attribute referenced in an expression is an array, an object that contains a
247 corresponding array shall be considered to match the expression if any of the elements in the
248 array matches all expressions that have the same attribute prefix.
252 --filter admin-status=ENABLED
253 --filter nsd-ref=<NSD_NAME>
254 --filter nsd.vendor=<VENDOR>
255 --filter nsd.vendor=<VENDOR>&nsd-ref=<NSD_NAME>
256 --filter nsd.constituent-vnfd.vnfd-id-ref=<VNFD_NAME>
259 def summarize_deployment_status(status_dict
):
266 net_list
= status_dict
.get("nets", [])
269 if net
["status"] not in status_nets
:
270 status_nets
[net
["status"]] = 1
272 status_nets
[net
["status"]] += 1
274 for k
, v
in status_nets
.items():
275 message
+= "{}:{},".format(k
, v
)
276 message
+= "TOTAL:{}".format(n_nets
)
277 summary
+= "{}".format(message
)
282 vnf_list
= status_dict
["vnfs"]
284 member_vnf_index
= vnf
["member_vnf_index"]
285 if member_vnf_index
not in status_vnfs
:
286 status_vnfs
[member_vnf_index
] = {}
287 for vm
in vnf
["vms"]:
289 if vm
["status"] not in status_vms
:
290 status_vms
[vm
["status"]] = 1
292 status_vms
[vm
["status"]] += 1
293 if vm
["status"] not in status_vnfs
[member_vnf_index
]:
294 status_vnfs
[member_vnf_index
][vm
["status"]] = 1
296 status_vnfs
[member_vnf_index
][vm
["status"]] += 1
298 for k
, v
in status_vms
.items():
299 message
+= "{}:{},".format(k
, v
)
300 message
+= "TOTAL:{}".format(n_vms
)
301 summary
+= "\n{}".format(message
)
303 for k
, v
in status_vnfs
.items():
305 message
= "\n {} VMs: ".format(k
)
306 for k2
, v2
in v
.items():
307 message
+= "{}:{},".format(k2
, v2
)
309 message
+= "TOTAL:{}".format(total
)
313 def summarize_config_status(ee_list
):
321 if ee
["elementType"] not in status_ee
:
322 status_ee
[ee
["elementType"]] = {}
323 status_ee
[ee
["elementType"]][ee
["status"]] = 1
325 if ee
["status"] in status_ee
[ee
["elementType"]]:
326 status_ee
[ee
["elementType"]][ee
["status"]] += 1
328 status_ee
[ee
["elementType"]][ee
["status"]] = 1
329 for elementType
in ["KDU", "VDU", "PDU", "VNF", "NS"]:
330 if elementType
in status_ee
:
333 for k
, v
in status_ee
[elementType
].items():
334 message
+= "{}:{},".format(k
, v
)
336 message
+= "TOTAL:{}\n".format(total
)
337 summary
+= "{}: {}".format(elementType
, message
)
338 summary
+= "TOTAL Exec. Env.: {}".format(n_ee
)
343 check_client_version(ctx
.obj
, "--filter")
344 filter = "&".join(filter)
345 resp
= ctx
.obj
.ns
.list(filter)
347 resp
= ctx
.obj
.ns
.list()
360 "configuration status",
363 project_list
= ctx
.obj
.project
.list()
365 vim_list
= ctx
.obj
.vim
.list()
380 fullclassname
= ctx
.obj
.__module
__ + "." + ctx
.obj
.__class
__.__name
__
381 if fullclassname
== "osmclient.sol005.client.Client":
383 logger
.debug("NS info: {}".format(nsr
))
384 nsr_name
= nsr
["name"]
386 date
= datetime
.fromtimestamp(nsr
["create-time"]).strftime(
389 ns_state
= nsr
.get("nsState", nsr
["_admin"]["nsState"])
391 deployment_status
= summarize_deployment_status(
392 nsr
.get("deploymentStatus")
394 config_status
= summarize_config_status(nsr
.get("configurationStatus"))
395 project_id
, project_name
= get_project(project_list
, nsr
)
396 # project = '{} ({})'.format(project_name, project_id)
397 project
= project_name
398 vim_id
= nsr
.get("datacenter")
399 vim_name
= get_vim_name(vim_list
, vim_id
)
401 # vim = '{} ({})'.format(vim_name, vim_id)
403 if "currentOperation" in nsr
:
404 current_operation
= "{} ({})".format(
405 nsr
["currentOperation"], nsr
["currentOperationID"]
408 current_operation
= "{} ({})".format(
409 nsr
["_admin"].get("current-operation", "-"),
410 nsr
["_admin"]["nslcmop"],
412 error_details
= "N/A"
415 or ns_state
== "DEGRADED"
416 or ("currentOperation" not in nsr
and nsr
.get("errorDescription"))
418 error_details
= "{}\nDetail: {}".format(
419 nsr
["errorDescription"], nsr
["errorDetail"]
422 nsopdata
= ctx
.obj
.ns
.get_opdata(ns
["id"])
423 nsr
= nsopdata
["nsr:nsr"]
424 nsr_name
= nsr
["name-ref"]
425 nsr_id
= nsr
["ns-instance-config-ref"]
428 deployment_status
= (
429 nsr
["operational-status"]
430 if "operational-status" in nsr
433 ns_state
= deployment_status
434 config_status
= nsr
.get("config-status", "Not found")
435 current_operation
= "Unknown"
436 error_details
= nsr
.get("detailed-status", "Not found")
437 if config_status
== "config_not_needed":
438 config_status
= "configured (no charms)"
448 wrap_text(text
=error_details
, width
=40),
463 wrap_text(text
=error_details
, width
=40),
468 print('To get the history of all operations over a NS, run "osm ns-op-list NS_ID"')
470 'For more details on the current operation, run "osm ns-op-show OPERATION_ID"'
474 def nsd_list(ctx
, filter, long):
477 check_client_version(ctx
.obj
, "--filter")
478 filter = "&".join(filter)
479 resp
= ctx
.obj
.nsd
.list(filter)
481 resp
= ctx
.obj
.nsd
.list()
482 # print(yaml.safe_dump(resp))
483 fullclassname
= ctx
.obj
.__module
__ + "." + ctx
.obj
.__class
__.__name
__
484 if fullclassname
== "osmclient.sol005.client.Client":
498 table
= PrettyTable(["nsd name", "id"])
500 name
= nsd
.get("id", "-")
502 onb_state
= nsd
["_admin"].get("onboardingState", "-")
503 op_state
= nsd
["_admin"].get("operationalState", "-")
504 usage_state
= nsd
["_admin"].get("usageState", "-")
505 date
= datetime
.fromtimestamp(nsd
["_admin"]["created"]).strftime(
508 last_update
= datetime
.fromtimestamp(
509 nsd
["_admin"]["modified"]
510 ).strftime("%Y-%m-%dT%H:%M:%S")
523 table
.add_row([name
, nsd
["_id"]])
525 table
= PrettyTable(["nsd name", "id"])
527 table
.add_row([nsd
["name"], nsd
["id"]])
532 @cli_osm.command(name
="nsd-list", short_help
="list all NS packages")
537 help="restricts the list to the NSD/NSpkg matching the filter",
539 @click.option("--long", is_flag
=True, help="get more details")
541 def nsd_list1(ctx
, filter, long):
542 """list all NSD/NS pkg in the system"""
544 nsd_list(ctx
, filter, long)
547 @cli_osm.command(name
="nspkg-list", short_help
="list all NS packages")
552 help="restricts the list to the NSD/NSpkg matching the filter",
554 @click.option("--long", is_flag
=True, help="get more details")
556 def nsd_list2(ctx
, filter, long):
557 """list all NS packages"""
559 nsd_list(ctx
, filter, long)
562 def pkg_repo_list(ctx
, pkgtype
, filter, repo
, long):
563 resp
= ctx
.obj
.osmrepo
.pkg_list(pkgtype
, filter, repo
)
566 ["nfpkg name", "vendor", "version", "latest", "description", "repository"]
569 table
= PrettyTable(["nfpkg name", "repository"])
571 name
= vnfd
.get("id", vnfd
.get("name", "-"))
572 repository
= vnfd
.get("repository")
574 vendor
= vnfd
.get("provider", vnfd
.get("vendor"))
575 version
= vnfd
.get("version")
576 description
= vnfd
.get("description")
577 latest
= vnfd
.get("latest")
578 table
.add_row([name
, vendor
, version
, latest
, description
, repository
])
580 table
.add_row([name
, repository
])
585 def vnfd_list(ctx
, nf_type
, filter, long):
588 check_client_version(ctx
.obj
, "--nf_type")
590 check_client_version(ctx
.obj
, "--filter")
592 filter = "&".join(filter)
595 nf_filter
= "_admin.type=vnfd"
596 elif nf_type
== "pnf":
597 nf_filter
= "_admin.type=pnfd"
598 elif nf_type
== "hnf":
599 nf_filter
= "_admin.type=hnfd"
601 raise ClientException(
602 'wrong value for "--nf_type" option, allowed values: vnf, pnf, hnf'
605 filter = "{}&{}".format(nf_filter
, filter)
609 resp
= ctx
.obj
.vnfd
.list(filter)
611 resp
= ctx
.obj
.vnfd
.list()
612 # print(yaml.safe_dump(resp))
613 fullclassname
= ctx
.obj
.__module
__ + "." + ctx
.obj
.__class
__.__name
__
614 if fullclassname
== "osmclient.sol005.client.Client":
631 table
= PrettyTable(["nfpkg name", "id", "desc type"])
633 name
= vnfd
.get("id", vnfd
.get("name", "-"))
634 descriptor_type
= "sol006" if "product-name" in vnfd
else "rel8"
636 onb_state
= vnfd
["_admin"].get("onboardingState", "-")
637 op_state
= vnfd
["_admin"].get("operationalState", "-")
638 vendor
= vnfd
.get("provider", vnfd
.get("vendor"))
639 version
= vnfd
.get("version")
640 usage_state
= vnfd
["_admin"].get("usageState", "-")
641 date
= datetime
.fromtimestamp(vnfd
["_admin"]["created"]).strftime(
644 last_update
= datetime
.fromtimestamp(
645 vnfd
["_admin"]["modified"]
646 ).strftime("%Y-%m-%dT%H:%M:%S")
662 table
.add_row([name
, vnfd
["_id"], descriptor_type
])
664 table
= PrettyTable(["nfpkg name", "id"])
666 table
.add_row([vnfd
["name"], vnfd
["id"]])
671 @cli_osm.command(name
="vnfd-list", short_help
="list all xNF packages (VNF, HNF, PNF)")
672 @click.option("--nf_type", help="type of NF (vnf, pnf, hnf)")
677 help="restricts the list to the NF pkg matching the filter",
679 @click.option("--long", is_flag
=True, help="get more details")
681 def vnfd_list1(ctx
, nf_type
, filter, long):
682 """list all xNF packages (VNF, HNF, PNF)"""
684 vnfd_list(ctx
, nf_type
, filter, long)
687 @cli_osm.command(name
="vnfpkg-list", short_help
="list all xNF packages (VNF, HNF, PNF)")
688 @click.option("--nf_type", help="type of NF (vnf, pnf, hnf)")
693 help="restricts the list to the NFpkg matching the filter",
695 @click.option("--long", is_flag
=True, help="get more details")
697 def vnfd_list2(ctx
, nf_type
, filter, long):
698 """list all xNF packages (VNF, HNF, PNF)"""
700 vnfd_list(ctx
, nf_type
, filter, long)
703 @cli_osm.command(name
="nfpkg-list", short_help
="list all xNF packages (VNF, HNF, PNF)")
704 @click.option("--nf_type", help="type of NF (vnf, pnf, hnf)")
709 help="restricts the list to the NFpkg matching the filter",
711 @click.option("--long", is_flag
=True, help="get more details")
713 def nfpkg_list(ctx
, nf_type
, filter, long):
714 """list all xNF packages (VNF, HNF, PNF)"""
717 check_client_version(ctx
.obj
, ctx
.command
.name
)
718 vnfd_list(ctx
, nf_type
, filter, long)
719 # except ClientException as e:
725 name
="vnfpkg-repo-list", short_help
="list all xNF from OSM repositories"
731 help="restricts the list to the NFpkg matching the filter",
734 "--repo", default
=None, help="restricts the list to a particular OSM repository"
736 @click.option("--long", is_flag
=True, help="get more details")
738 def nfpkg_repo_list1(ctx
, filter, repo
, long):
739 """list xNF packages from OSM repositories"""
741 pkg_repo_list(ctx
, pkgtype
, filter, repo
, long)
745 name
="nfpkg-repo-list", short_help
="list all xNF from OSM repositories"
751 help="restricts the list to the NFpkg matching the filter",
754 "--repo", default
=None, help="restricts the list to a particular OSM repository"
756 @click.option("--long", is_flag
=True, help="get more details")
758 def nfpkg_repo_list2(ctx
, filter, repo
, long):
759 """list xNF packages from OSM repositories"""
761 pkg_repo_list(ctx
, pkgtype
, filter, repo
, long)
764 def vnf_list(ctx
, ns
, filter, long):
768 check_client_version(ctx
.obj
, "--ns")
770 filter = "&".join(filter)
771 check_client_version(ctx
.obj
, "--filter")
772 resp
= ctx
.obj
.vnf
.list(ns
, filter)
774 resp
= ctx
.obj
.vnf
.list()
775 # except ClientException as e:
778 fullclassname
= ctx
.obj
.__module
__ + "." + ctx
.obj
.__class
__.__name
__
779 if fullclassname
== "osmclient.sol005.client.Client":
801 table
= PrettyTable(field_names
)
803 name
= vnfr
["name"] if "name" in vnfr
else "-"
808 vnfr
["member-vnf-index-ref"],
810 vnfr
["vim-account-id"],
814 date
= datetime
.fromtimestamp(vnfr
["_admin"]["created"]).strftime(
817 last_update
= datetime
.fromtimestamp(
818 vnfr
["_admin"]["modified"]
819 ).strftime("%Y-%m-%dT%H:%M:%S")
820 new_row
.extend([date
, last_update
])
821 table
.add_row(new_row
)
823 table
= PrettyTable(["vnf name", "id", "operational status", "config status"])
825 if "mgmt-interface" not in vnfr
:
826 vnfr
["mgmt-interface"] = {}
827 vnfr
["mgmt-interface"]["ip-address"] = None
832 vnfr
["operational-status"],
833 vnfr
["config-status"],
840 @cli_osm.command(name
="vnf-list", short_help
="list all NF instances")
842 "--ns", default
=None, help="NS instance id or name to restrict the NF list"
848 help="restricts the list to the NF instances matching the filter.",
850 @click.option("--long", is_flag
=True, help="get more details")
852 def vnf_list1(ctx
, ns
, filter, long):
853 """list all NF instances"""
855 vnf_list(ctx
, ns
, filter, long)
858 @cli_osm.command(name
="nsd-repo-list", short_help
="list all NS from OSM repositories")
863 help="restricts the list to the NS matching the filter",
866 "--repo", default
=None, help="restricts the list to a particular OSM repository"
868 @click.option("--long", is_flag
=True, help="get more details")
870 def nspkg_repo_list(ctx
, filter, repo
, long):
871 """list xNF packages from OSM repositories"""
873 pkg_repo_list(ctx
, pkgtype
, filter, repo
, long)
876 @cli_osm.command(name
="nspkg-repo-list", short_help
="list all NS from OSM repositories")
881 help="restricts the list to the NS matching the filter",
884 "--repo", default
=None, help="restricts the list to a particular OSM repository"
886 @click.option("--long", is_flag
=True, help="get more details")
888 def nspkg_repo_list2(ctx
, filter, repo
, long):
889 """list xNF packages from OSM repositories"""
891 pkg_repo_list(ctx
, pkgtype
, filter, repo
, long)
894 @cli_osm.command(name
="nf-list", short_help
="list all NF instances")
896 "--ns", default
=None, help="NS instance id or name to restrict the NF list"
902 help="restricts the list to the NF instances matching the filter.",
904 @click.option("--long", is_flag
=True, help="get more details")
906 def nf_list(ctx
, ns
, filter, long):
907 """list all NF instances
911 --ns TEXT NS instance id or name to restrict the VNF list
912 --filter filterExpr Restricts the list to the VNF instances matching the filter
915 filterExpr consists of one or more strings formatted according to "simpleFilterExpr",
916 concatenated using the "&" character:
919 filterExpr := <simpleFilterExpr>["&"<simpleFilterExpr>]*
920 simpleFilterExpr := <attrName>["."<attrName>]*["."<op>]"="<value>[","<value>]*
921 op := "eq" | "neq" | "gt" | "lt" | "gte" | "lte" | "cont" | "ncont"
923 value := scalar value
927 * zero or more occurrences
928 ? zero or one occurrence
929 [] grouping of expressions to be used with ? and *
930 "" quotation marks for marking string constants
934 "AttrName" is the name of one attribute in the data type that defines the representation
935 of the resource. The dot (".") character in "simpleFilterExpr" allows concatenation of
936 <attrName> entries to filter by attributes deeper in the hierarchy of a structured document.
937 "Op" stands for the comparison operator. If the expression has concatenated <attrName>
938 entries, it means that the operator "op" is applied to the attribute addressed by the last
939 <attrName> entry included in the concatenation. All simple filter expressions are combined
940 by the "AND" logical operator. In a concatenation of <attrName> entries in a <simpleFilterExpr>,
941 the rightmost "attrName" entry in a "simpleFilterExpr" is called "leaf attribute". The
942 concatenation of all "attrName" entries except the leaf attribute is called the "attribute
943 prefix". If an attribute referenced in an expression is an array, an object that contains a
944 corresponding array shall be considered to match the expression if any of the elements in the
945 array matches all expressions that have the same attribute prefix.
949 --filter vim-account-id=<VIM_ACCOUNT_ID>
950 --filter vnfd-ref=<VNFD_NAME>
951 --filter vdur.ip-address=<IP_ADDRESS>
952 --filter vnfd-ref=<VNFD_NAME>,vdur.ip-address=<IP_ADDRESS>
955 vnf_list(ctx
, ns
, filter, long)
959 name
="ns-op-list", short_help
="shows the history of operations over a NS instance"
961 @click.argument("name")
963 "--long", is_flag
=True, help="get more details of the NS operation (date, )."
966 def ns_op_list(ctx
, name
, long):
967 """shows the history of operations over a NS instance
969 NAME: name or ID of the NS instance
972 def formatParams(params
):
973 if params
["lcmOperationType"] == "instantiate":
974 params
.pop("nsDescription")
978 elif params
["lcmOperationType"] == "action":
979 params
.pop("primitive")
980 params
.pop("lcmOperationType")
981 params
.pop("nsInstanceId")
986 check_client_version(ctx
.obj
, ctx
.command
.name
)
987 resp
= ctx
.obj
.ns
.list_op(name
)
988 # except ClientException as e:
1006 table
= PrettyTable(
1007 ["id", "operation", "action_name", "status", "date", "detail"]
1010 # print(yaml.safe_dump(resp))
1013 if op
["lcmOperationType"] == "action":
1014 action_name
= op
["operationParams"]["primitive"]
1016 if op
["operationState"] == "PROCESSING":
1017 if op
.get("queuePosition") is not None and op
.get("queuePosition") > 0:
1018 detail
= "In queue. Current position: {}".format(op
["queuePosition"])
1019 elif op
["lcmOperationType"] in ("instantiate", "terminate"):
1021 detail
= op
["stage"]
1022 elif op
["operationState"] in ("FAILED", "FAILED_TEMP"):
1023 detail
= op
.get("errorMessage", "-")
1024 date
= datetime
.fromtimestamp(op
["startTime"]).strftime("%Y-%m-%dT%H:%M:%S")
1025 last_update
= datetime
.fromtimestamp(op
["statusEnteredTime"]).strftime(
1032 op
["lcmOperationType"],
1035 text
=json
.dumps(formatParams(op
["operationParams"]), indent
=2),
1038 op
["operationState"],
1041 wrap_text(text
=detail
, width
=50),
1048 op
["lcmOperationType"],
1050 op
["operationState"],
1052 wrap_text(text
=detail
or "", width
=50),
1059 def nsi_list(ctx
, filter):
1060 """list all Network Slice Instances"""
1063 check_client_version(ctx
.obj
, ctx
.command
.name
)
1065 filter = "&".join(filter)
1066 resp
= ctx
.obj
.nsi
.list(filter)
1067 # except ClientException as e:
1070 table
= PrettyTable(
1072 "netslice instance name",
1074 "operational status",
1080 nsi_name
= nsi
["name"]
1083 nsi
["operational-status"] if "operational-status" in nsi
else "Not found"
1085 configstatus
= nsi
["config-status"] if "config-status" in nsi
else "Not found"
1087 nsi
["detailed-status"] if "detailed-status" in nsi
else "Not found"
1089 if configstatus
== "config_not_needed":
1090 configstatus
= "configured (no charms)"
1091 table
.add_row([nsi_name
, nsi_id
, opstatus
, configstatus
, detailed_status
])
1096 @cli_osm.command(name
="nsi-list", short_help
="list all Network Slice Instances (NSI)")
1101 help="restricts the list to the Network Slice Instances matching the filter",
1104 def nsi_list1(ctx
, filter):
1105 """list all Network Slice Instances (NSI)"""
1107 nsi_list(ctx
, filter)
1111 name
="netslice-instance-list", short_help
="list all Network Slice Instances (NSI)"
1117 help="restricts the list to the Network Slice Instances matching the filter",
1120 def nsi_list2(ctx
, filter):
1121 """list all Network Slice Instances (NSI)"""
1123 nsi_list(ctx
, filter)
1126 def nst_list(ctx
, filter):
1129 check_client_version(ctx
.obj
, ctx
.command
.name
)
1131 filter = "&".join(filter)
1132 resp
= ctx
.obj
.nst
.list(filter)
1133 # except ClientException as e:
1136 # print(yaml.safe_dump(resp))
1137 table
= PrettyTable(["nst name", "id"])
1139 name
= nst
["name"] if "name" in nst
else "-"
1140 table
.add_row([name
, nst
["_id"]])
1145 @cli_osm.command(name
="nst-list", short_help
="list all Network Slice Templates (NST)")
1150 help="restricts the list to the NST matching the filter",
1153 def nst_list1(ctx
, filter):
1154 """list all Network Slice Templates (NST) in the system"""
1156 nst_list(ctx
, filter)
1160 name
="netslice-template-list", short_help
="list all Network Slice Templates (NST)"
1166 help="restricts the list to the NST matching the filter",
1169 def nst_list2(ctx
, filter):
1170 """list all Network Slice Templates (NST) in the system"""
1172 nst_list(ctx
, filter)
1175 def nsi_op_list(ctx
, name
):
1178 check_client_version(ctx
.obj
, ctx
.command
.name
)
1179 resp
= ctx
.obj
.nsi
.list_op(name
)
1180 # except ClientException as e:
1183 table
= PrettyTable(["id", "operation", "status"])
1185 table
.add_row([op
["id"], op
["lcmOperationType"], op
["operationState"]])
1192 short_help
="shows the history of operations over a Network Slice Instance (NSI)",
1194 @click.argument("name")
1196 def nsi_op_list1(ctx
, name
):
1197 """shows the history of operations over a Network Slice Instance (NSI)
1199 NAME: name or ID of the Network Slice Instance
1202 nsi_op_list(ctx
, name
)
1206 name
="netslice-instance-op-list",
1207 short_help
="shows the history of operations over a Network Slice Instance (NSI)",
1209 @click.argument("name")
1211 def nsi_op_list2(ctx
, name
):
1212 """shows the history of operations over a Network Slice Instance (NSI)
1214 NAME: name or ID of the Network Slice Instance
1217 nsi_op_list(ctx
, name
)
1220 @cli_osm.command(name
="pdu-list", short_help
="list all Physical Deployment Units (PDU)")
1225 help="restricts the list to the Physical Deployment Units matching the filter",
1228 def pdu_list(ctx
, filter):
1229 """list all Physical Deployment Units (PDU)"""
1232 check_client_version(ctx
.obj
, ctx
.command
.name
)
1234 filter = "&".join(filter)
1235 resp
= ctx
.obj
.pdu
.list(filter)
1236 # except ClientException as e:
1239 table
= PrettyTable(["pdu name", "id", "type", "mgmt ip address"])
1241 pdu_name
= pdu
["name"]
1243 pdu_type
= pdu
["type"]
1244 pdu_ipaddress
= "None"
1245 for iface
in pdu
["interfaces"]:
1247 pdu_ipaddress
= iface
["ip-address"]
1249 table
.add_row([pdu_name
, pdu_id
, pdu_type
, pdu_ipaddress
])
1254 ####################
1256 ####################
1259 def nsd_show(ctx
, name
, literal
):
1262 resp
= ctx
.obj
.nsd
.get(name
)
1263 # resp = ctx.obj.nsd.get_individual(name)
1264 # except ClientException as e:
1269 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
1272 table
= PrettyTable(["field", "value"])
1273 for k
, v
in list(resp
.items()):
1274 table
.add_row([k
, wrap_text(text
=json
.dumps(v
, indent
=2), width
=100)])
1279 @cli_osm.command(name
="nsd-show", short_help
="shows the details of a NS package")
1280 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1281 @click.argument("name")
1283 def nsd_show1(ctx
, name
, literal
):
1284 """shows the content of a NSD
1286 NAME: name or ID of the NSD/NSpkg
1289 nsd_show(ctx
, name
, literal
)
1292 @cli_osm.command(name
="nspkg-show", short_help
="shows the details of a NS package")
1293 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1294 @click.argument("name")
1296 def nsd_show2(ctx
, name
, literal
):
1297 """shows the content of a NSD
1299 NAME: name or ID of the NSD/NSpkg
1302 nsd_show(ctx
, name
, literal
)
1305 def vnfd_show(ctx
, name
, literal
):
1308 resp
= ctx
.obj
.vnfd
.get(name
)
1309 # resp = ctx.obj.vnfd.get_individual(name)
1310 # except ClientException as e:
1315 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
1318 table
= PrettyTable(["field", "value"])
1319 for k
, v
in list(resp
.items()):
1320 table
.add_row([k
, wrap_text(text
=json
.dumps(v
, indent
=2), width
=100)])
1325 def pkg_repo_show(ctx
, pkgtype
, name
, repo
, version
, filter, literal
):
1328 filter = "&".join(filter)
1330 resp
= ctx
.obj
.osmrepo
.pkg_get(pkgtype
, name
, repo
, version
, filter)
1333 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
1336 catalog
= pkgtype
+ "-catalog"
1337 full_catalog
= pkgtype
+ ":" + catalog
1338 if resp
.get(catalog
):
1339 resp
= resp
.pop(catalog
)[pkgtype
][0]
1340 elif resp
.get(full_catalog
):
1341 resp
= resp
.pop(full_catalog
)[pkgtype
][0]
1343 table
= PrettyTable(["field", "value"])
1344 for k
, v
in list(resp
.items()):
1345 table
.add_row([k
, wrap_text(text
=json
.dumps(v
, indent
=2), width
=100)])
1350 @cli_osm.command(name
="vnfd-show", short_help
="shows the details of a NF package")
1351 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1352 @click.argument("name")
1354 def vnfd_show1(ctx
, name
, literal
):
1355 """shows the content of a VNFD
1357 NAME: name or ID of the VNFD/VNFpkg
1360 vnfd_show(ctx
, name
, literal
)
1363 @cli_osm.command(name
="vnfpkg-show", short_help
="shows the details of a NF package")
1364 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1365 @click.argument("name")
1367 def vnfd_show2(ctx
, name
, literal
):
1368 """shows the content of a VNFD
1370 NAME: name or ID of the VNFD/VNFpkg
1373 vnfd_show(ctx
, name
, literal
)
1377 name
="vnfpkg-repo-show",
1378 short_help
="shows the details of a NF package in an OSM repository",
1380 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1381 @click.option("--repo", required
=True, help="Repository name")
1382 @click.argument("name")
1383 @click.option("--filter", default
=None, multiple
=True, help="filter by fields")
1384 @click.option("--version", default
="latest", help="package version")
1386 def vnfd_show3(ctx
, name
, repo
, version
, literal
=None, filter=None):
1387 """shows the content of a VNFD in a repository
1389 NAME: name or ID of the VNFD/VNFpkg
1392 pkg_repo_show(ctx
, pkgtype
, name
, repo
, version
, filter, literal
)
1396 name
="nsd-repo-show",
1397 short_help
="shows the details of a NS package in an OSM repository",
1399 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1400 @click.option("--repo", required
=True, help="Repository name")
1401 @click.argument("name")
1402 @click.option("--filter", default
=None, multiple
=True, help="filter by fields")
1403 @click.option("--version", default
="latest", help="package version")
1405 def nsd_repo_show(ctx
, name
, repo
, version
, literal
=None, filter=None):
1406 """shows the content of a VNFD in a repository
1408 NAME: name or ID of the VNFD/VNFpkg
1411 pkg_repo_show(ctx
, pkgtype
, name
, repo
, version
, filter, literal
)
1415 name
="nspkg-repo-show",
1416 short_help
="shows the details of a NS package in an OSM repository",
1418 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1419 @click.option("--repo", required
=True, help="Repository name")
1420 @click.argument("name")
1421 @click.option("--filter", default
=None, multiple
=True, help="filter by fields")
1422 @click.option("--version", default
="latest", help="package version")
1424 def nsd_repo_show2(ctx
, name
, repo
, version
, literal
=None, filter=None):
1425 """shows the content of a VNFD in a repository
1427 NAME: name or ID of the VNFD/VNFpkg
1430 pkg_repo_show(ctx
, pkgtype
, name
, repo
, version
, filter, literal
)
1433 @cli_osm.command(name
="nfpkg-show", short_help
="shows the details of a NF package")
1434 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1435 @click.argument("name")
1437 def nfpkg_show(ctx
, name
, literal
):
1438 """shows the content of a NF Descriptor
1440 NAME: name or ID of the NFpkg
1443 vnfd_show(ctx
, name
, literal
)
1447 name
="nfpkg-repo-show",
1448 short_help
="shows the details of a NF package in an OSM repository",
1450 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1451 @click.option("--repo", required
=True, help="Repository name")
1452 @click.argument("name")
1453 @click.option("--filter", default
=None, multiple
=True, help="filter by fields")
1454 @click.option("--version", default
="latest", help="package version")
1456 def vnfd_show4(ctx
, name
, repo
, version
, literal
=None, filter=None):
1457 """shows the content of a VNFD in a repository
1459 NAME: name or ID of the VNFD/VNFpkg
1462 pkg_repo_show(ctx
, pkgtype
, name
, repo
, version
, filter, literal
)
1465 @cli_osm.command(name
="ns-show", short_help
="shows the info of a NS instance")
1466 @click.argument("name")
1467 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1471 help="restricts the information to the fields in the filter",
1474 def ns_show(ctx
, name
, literal
, filter):
1475 """shows the info of a NS instance
1477 NAME: name or ID of the NS instance
1481 ns
= ctx
.obj
.ns
.get(name
)
1482 # except ClientException as e:
1487 print(yaml
.safe_dump(ns
, indent
=4, default_flow_style
=False))
1490 table
= PrettyTable(["field", "value"])
1492 for k
, v
in list(ns
.items()):
1493 if not filter or k
in filter:
1494 table
.add_row([k
, wrap_text(text
=json
.dumps(v
, indent
=2), width
=100)])
1496 fullclassname
= ctx
.obj
.__module
__ + "." + ctx
.obj
.__class
__.__name
__
1497 if fullclassname
!= "osmclient.sol005.client.Client":
1498 nsopdata
= ctx
.obj
.ns
.get_opdata(ns
["id"])
1499 nsr_optdata
= nsopdata
["nsr:nsr"]
1500 for k
, v
in list(nsr_optdata
.items()):
1501 if not filter or k
in filter:
1502 table
.add_row([k
, wrap_text(json
.dumps(v
, indent
=2), width
=100)])
1507 @cli_osm.command(name
="vnf-show", short_help
="shows the info of a VNF instance")
1508 @click.argument("name")
1509 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1513 help="restricts the information to the fields in the filter",
1515 @click.option("--kdu", default
=None, help="KDU name (whose status will be shown)")
1517 def vnf_show(ctx
, name
, literal
, filter, kdu
):
1518 """shows the info of a VNF instance
1520 NAME: name or ID of the VNF instance
1523 def print_kdu_status(op_info_status
):
1524 """print KDU status properly formatted"""
1526 op_status
= yaml
.safe_load(op_info_status
)
1528 "namespace" in op_status
1529 and "info" in op_status
1530 and "last_deployed" in op_status
["info"]
1531 and "status" in op_status
["info"]
1532 and "code" in op_status
["info"]["status"]
1533 and "resources" in op_status
["info"]["status"]
1534 and "seconds" in op_status
["info"]["last_deployed"]
1536 last_deployed_time
= datetime
.fromtimestamp(
1537 op_status
["info"]["last_deployed"]["seconds"]
1538 ).strftime("%a %b %d %I:%M:%S %Y")
1539 print("LAST DEPLOYED: {}".format(last_deployed_time
))
1540 print("NAMESPACE: {}".format(op_status
["namespace"]))
1541 status_code
= "UNKNOWN"
1542 if op_status
["info"]["status"]["code"] == 1:
1543 status_code
= "DEPLOYED"
1544 print("STATUS: {}".format(status_code
))
1547 print(op_status
["info"]["status"]["resources"])
1548 if "notes" in op_status
["info"]["status"]:
1550 print(op_status
["info"]["status"]["notes"])
1552 print(op_info_status
)
1554 print(op_info_status
)
1559 raise ClientException(
1560 '"--literal" option is incompatible with "--kdu" option'
1563 raise ClientException(
1564 '"--filter" option is incompatible with "--kdu" option'
1568 check_client_version(ctx
.obj
, ctx
.command
.name
)
1569 resp
= ctx
.obj
.vnf
.get(name
)
1572 ns_id
= resp
["nsr-id-ref"]
1574 op_data
["member_vnf_index"] = resp
["member-vnf-index-ref"]
1575 op_data
["kdu_name"] = kdu
1576 op_data
["primitive"] = "status"
1577 op_data
["primitive_params"] = {}
1578 op_id
= ctx
.obj
.ns
.exec_op(ns_id
, op_name
="action", op_data
=op_data
, wait
=False)
1581 op_info
= ctx
.obj
.ns
.get_op(op_id
)
1582 if op_info
["operationState"] == "COMPLETED":
1583 print_kdu_status(op_info
["detailed-status"])
1587 print("Could not determine KDU status")
1591 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
1594 table
= PrettyTable(["field", "value"])
1595 for k
, v
in list(resp
.items()):
1596 if not filter or k
in filter:
1597 table
.add_row([k
, wrap_text(text
=json
.dumps(v
, indent
=2), width
=100)])
1600 # except ClientException as e:
1605 # @cli_osm.command(name='vnf-monitoring-show')
1606 # @click.argument('vnf_name')
1607 # @click.pass_context
1608 # def vnf_monitoring_show(ctx, vnf_name):
1610 # check_client_version(ctx.obj, ctx.command.name, 'v1')
1611 # resp = ctx.obj.vnf.get_monitoring(vnf_name)
1612 # except ClientException as e:
1616 # table = PrettyTable(['vnf name', 'monitoring name', 'value', 'units'])
1617 # if resp is not None:
1618 # for monitor in resp:
1622 # monitor['value-integer'],
1623 # monitor['units']])
1628 # @cli_osm.command(name='ns-monitoring-show')
1629 # @click.argument('ns_name')
1630 # @click.pass_context
1631 # def ns_monitoring_show(ctx, ns_name):
1633 # check_client_version(ctx.obj, ctx.command.name, 'v1')
1634 # resp = ctx.obj.ns.get_monitoring(ns_name)
1635 # except ClientException as e:
1639 # table = PrettyTable(['vnf name', 'monitoring name', 'value', 'units'])
1640 # for key, val in list(resp.items()):
1641 # for monitor in val:
1645 # monitor['value-integer'],
1646 # monitor['units']])
1651 @cli_osm.command(name
="ns-op-show", short_help
="shows the info of a NS operation")
1652 @click.argument("id")
1656 help="restricts the information to the fields in the filter",
1658 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1660 def ns_op_show(ctx
, id, filter, literal
):
1661 """shows the detailed info of a NS operation
1663 ID: operation identifier
1667 check_client_version(ctx
.obj
, ctx
.command
.name
)
1668 op_info
= ctx
.obj
.ns
.get_op(id)
1669 # except ClientException as e:
1674 print(yaml
.safe_dump(op_info
, indent
=4, default_flow_style
=False))
1677 table
= PrettyTable(["field", "value"])
1678 for k
, v
in list(op_info
.items()):
1679 if not filter or k
in filter:
1680 table
.add_row([k
, wrap_text(json
.dumps(v
, indent
=2), 100)])
1685 def nst_show(ctx
, name
, literal
):
1688 check_client_version(ctx
.obj
, ctx
.command
.name
)
1689 resp
= ctx
.obj
.nst
.get(name
)
1690 # resp = ctx.obj.nst.get_individual(name)
1691 # except ClientException as e:
1696 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
1699 table
= PrettyTable(["field", "value"])
1700 for k
, v
in list(resp
.items()):
1701 table
.add_row([k
, wrap_text(json
.dumps(v
, indent
=2), 100)])
1707 name
="nst-show", short_help
="shows the content of a Network Slice Template (NST)"
1709 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1710 @click.argument("name")
1712 def nst_show1(ctx
, name
, literal
):
1713 """shows the content of a Network Slice Template (NST)
1715 NAME: name or ID of the NST
1718 nst_show(ctx
, name
, literal
)
1722 name
="netslice-template-show",
1723 short_help
="shows the content of a Network Slice Template (NST)",
1725 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1726 @click.argument("name")
1728 def nst_show2(ctx
, name
, literal
):
1729 """shows the content of a Network Slice Template (NST)
1731 NAME: name or ID of the NST
1734 nst_show(ctx
, name
, literal
)
1737 def nsi_show(ctx
, name
, literal
, filter):
1740 check_client_version(ctx
.obj
, ctx
.command
.name
)
1741 nsi
= ctx
.obj
.nsi
.get(name
)
1742 # except ClientException as e:
1747 print(yaml
.safe_dump(nsi
, indent
=4, default_flow_style
=False))
1750 table
= PrettyTable(["field", "value"])
1752 for k
, v
in list(nsi
.items()):
1753 if not filter or k
in filter:
1754 table
.add_row([k
, json
.dumps(v
, indent
=2)])
1761 name
="nsi-show", short_help
="shows the content of a Network Slice Instance (NSI)"
1763 @click.argument("name")
1764 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1768 help="restricts the information to the fields in the filter",
1771 def nsi_show1(ctx
, name
, literal
, filter):
1772 """shows the content of a Network Slice Instance (NSI)
1774 NAME: name or ID of the Network Slice Instance
1777 nsi_show(ctx
, name
, literal
, filter)
1781 name
="netslice-instance-show",
1782 short_help
="shows the content of a Network Slice Instance (NSI)",
1784 @click.argument("name")
1785 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1789 help="restricts the information to the fields in the filter",
1792 def nsi_show2(ctx
, name
, literal
, filter):
1793 """shows the content of a Network Slice Instance (NSI)
1795 NAME: name or ID of the Network Slice Instance
1798 nsi_show(ctx
, name
, literal
, filter)
1801 def nsi_op_show(ctx
, id, filter):
1804 check_client_version(ctx
.obj
, ctx
.command
.name
)
1805 op_info
= ctx
.obj
.nsi
.get_op(id)
1806 # except ClientException as e:
1810 table
= PrettyTable(["field", "value"])
1811 for k
, v
in list(op_info
.items()):
1812 if not filter or k
in filter:
1813 table
.add_row([k
, json
.dumps(v
, indent
=2)])
1820 short_help
="shows the info of an operation over a Network Slice Instance(NSI)",
1822 @click.argument("id")
1826 help="restricts the information to the fields in the filter",
1829 def nsi_op_show1(ctx
, id, filter):
1830 """shows the info of an operation over a Network Slice Instance(NSI)
1832 ID: operation identifier
1835 nsi_op_show(ctx
, id, filter)
1839 name
="netslice-instance-op-show",
1840 short_help
="shows the info of an operation over a Network Slice Instance(NSI)",
1842 @click.argument("id")
1846 help="restricts the information to the fields in the filter",
1849 def nsi_op_show2(ctx
, id, filter):
1850 """shows the info of an operation over a Network Slice Instance(NSI)
1852 ID: operation identifier
1855 nsi_op_show(ctx
, id, filter)
1859 name
="pdu-show", short_help
="shows the content of a Physical Deployment Unit (PDU)"
1861 @click.argument("name")
1862 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
1866 help="restricts the information to the fields in the filter",
1869 def pdu_show(ctx
, name
, literal
, filter):
1870 """shows the content of a Physical Deployment Unit (PDU)
1872 NAME: name or ID of the PDU
1876 check_client_version(ctx
.obj
, ctx
.command
.name
)
1877 pdu
= ctx
.obj
.pdu
.get(name
)
1878 # except ClientException as e:
1883 print(yaml
.safe_dump(pdu
, indent
=4, default_flow_style
=False))
1886 table
= PrettyTable(["field", "value"])
1888 for k
, v
in list(pdu
.items()):
1889 if not filter or k
in filter:
1890 table
.add_row([k
, json
.dumps(v
, indent
=2)])
1896 ####################
1898 ####################
1901 def nsd_create(ctx
, filename
, overwrite
, skip_charm_build
, repo
, vendor
, version
):
1904 check_client_version(ctx
.obj
, ctx
.command
.name
)
1906 filename
= ctx
.obj
.osmrepo
.get_pkg("ns", filename
, repo
, vendor
, version
)
1907 ctx
.obj
.nsd
.create(filename
, overwrite
=overwrite
, skip_charm_build
=skip_charm_build
)
1908 # except ClientException as e:
1913 @cli_osm.command(name
="nsd-create", short_help
="creates a new NSD/NSpkg")
1914 @click.argument("filename")
1918 default
=None, # hidden=True,
1919 help="Deprecated. Use override",
1925 help="overrides fields in descriptor, format: "
1926 '"key1.key2...=value[;key3...=value;...]"',
1929 "--skip-charm-build",
1932 help="The charm will not be compiled, it is assumed to already exist",
1934 @click.option("--repo", default
=None, help="[repository]: Repository name")
1935 @click.option("--vendor", default
=None, help="[repository]: filter by vendor]")
1939 help="[repository]: filter by version. Default: latest",
1942 def nsd_create1(ctx
, filename
, overwrite
, skip_charm_build
, repo
, vendor
, version
):
1943 """onboards a new NSpkg (alias of nspkg-create) (TO BE DEPRECATED)
1946 FILENAME: NF Package tar.gz file, NF Descriptor YAML file or NF Package folder
1947 If FILENAME is a file (NF Package tar.gz or NF Descriptor YAML), it is onboarded.
1948 If FILENAME is an NF Package folder, it is built and then onboarded.
1954 overwrite
=overwrite
,
1955 skip_charm_build
=skip_charm_build
,
1962 @cli_osm.command(name
="nspkg-create", short_help
="creates a new NSD/NSpkg")
1963 @click.argument("filename")
1967 default
=None, # hidden=True,
1968 help="Deprecated. Use override",
1974 help="overrides fields in descriptor, format: "
1975 '"key1.key2...=value[;key3...=value;...]"',
1978 "--skip-charm-build",
1981 help="The charm will not be compiled, it is assumed to already exist",
1983 @click.option("--repo", default
=None, help="[repository]: Repository name")
1984 @click.option("--vendor", default
=None, help="[repository]: filter by vendor]")
1988 help="[repository]: filter by version. Default: latest",
1991 def nsd_pkg_create(ctx
, filename
, overwrite
, skip_charm_build
, repo
, vendor
, version
):
1992 """onboards a new NSpkg
1994 FILENAME: NF Package tar.gz file, NF Descriptor YAML file or NF Package folder
1995 If FILENAME is a file (NF Package tar.gz or NF Descriptor YAML), it is onboarded.
1996 If FILENAME is an NF Package folder, it is built and then onboarded.
2002 overwrite
=overwrite
,
2003 skip_charm_build
=skip_charm_build
,
2024 check_client_version(ctx
.obj
, ctx
.command
.name
)
2026 filename
= ctx
.obj
.osmrepo
.get_pkg("vnf", filename
, repo
, vendor
, version
)
2027 ctx
.obj
.vnfd
.create(
2029 overwrite
=overwrite
,
2030 skip_charm_build
=skip_charm_build
,
2031 override_epa
=override_epa
,
2032 override_nonepa
=override_nonepa
,
2033 override_paravirt
=override_paravirt
,
2035 # except ClientException as e:
2040 @cli_osm.command(name
="vnfd-create", short_help
="creates a new VNFD/VNFpkg")
2041 @click.argument("filename")
2043 "--overwrite", "overwrite", default
=None, help="overwrite deprecated, use override"
2049 help="overrides fields in descriptor, format: "
2050 '"key1.key2...=value[;key3...=value;...]"',
2053 "--skip-charm-build",
2056 help="The charm will not be compiled, it is assumed to already exist",
2063 help="adds guest-epa parameters to all VDU",
2066 "--override-nonepa",
2070 help="removes all guest-epa parameters from all VDU",
2073 "--override-paravirt",
2077 help="overrides all VDU interfaces to PARAVIRT",
2079 @click.option("--repo", default
=None, help="[repository]: Repository name")
2080 @click.option("--vendor", default
=None, help="[repository]: filter by vendor]")
2084 help="[repository]: filter by version. Default: latest",
2099 """creates a new VNFD/VNFpkg
2101 FILENAME: NF Package tar.gz file, NF Descriptor YAML file or NF Package folder
2102 If FILENAME is a file (NF Package tar.gz or NF Descriptor YAML), it is onboarded.
2103 If FILENAME is an NF Package folder, it is built and then onboarded.
2109 overwrite
=overwrite
,
2110 skip_charm_build
=skip_charm_build
,
2111 override_epa
=override_epa
,
2112 override_nonepa
=override_nonepa
,
2113 override_paravirt
=override_paravirt
,
2120 @cli_osm.command(name
="vnfpkg-create", short_help
="creates a new VNFD/VNFpkg")
2121 @click.argument("filename")
2125 default
=None, # hidden=True,
2126 help="Deprecated. Use override",
2132 help="overrides fields in descriptor, format: "
2133 '"key1.key2...=value[;key3...=value;...]"',
2136 "--skip-charm-build",
2139 help="The charm will not be compiled, it is assumed to already exist",
2146 help="adds guest-epa parameters to all VDU",
2149 "--override-nonepa",
2153 help="removes all guest-epa parameters from all VDU",
2156 "--override-paravirt",
2160 help="overrides all VDU interfaces to PARAVIRT",
2162 @click.option("--repo", default
=None, help="[repository]: Repository name")
2163 @click.option("--vendor", default
=None, help="[repository]: filter by vendor]")
2167 help="[repository]: filter by version. Default: latest",
2182 """creates a new VNFD/VNFpkg
2184 FILENAME: NF Package tar.gz file, NF Descriptor YAML file or NF Package folder
2185 If FILENAME is a file (NF Package tar.gz or NF Descriptor YAML), it is onboarded.
2186 If FILENAME is an NF Package folder, it is built and then onboarded.
2192 overwrite
=overwrite
,
2193 skip_charm_build
=skip_charm_build
,
2194 override_epa
=override_epa
,
2195 override_nonepa
=override_nonepa
,
2196 override_paravirt
=override_paravirt
,
2203 @cli_osm.command(name
="nfpkg-create", short_help
="creates a new NFpkg")
2204 @click.argument("filename")
2208 default
=None, # hidden=True,
2209 help="Deprecated. Use override",
2215 help="overrides fields in descriptor, format: "
2216 '"key1.key2...=value[;key3...=value;...]"',
2219 "--skip-charm-build",
2222 help="The charm will not be compiled, it is assumed to already exist",
2229 help="adds guest-epa parameters to all VDU",
2232 "--override-nonepa",
2236 help="removes all guest-epa parameters from all VDU",
2239 "--override-paravirt",
2243 help="overrides all VDU interfaces to PARAVIRT",
2245 @click.option("--repo", default
=None, help="[repository]: Repository name")
2246 @click.option("--vendor", default
=None, help="[repository]: filter by vendor]")
2250 help="[repository]: filter by version. Default: latest",
2265 """creates a new NFpkg
2268 FILENAME: NF Package tar.gz file, NF Descriptor YAML file or NF Package folder
2269 If FILENAME is a file (NF Package tar.gz or NF Descriptor YAML), it is onboarded.
2270 If FILENAME is an NF Package folder, it is built and then onboarded.
2276 overwrite
=overwrite
,
2277 skip_charm_build
=skip_charm_build
,
2278 override_epa
=override_epa
,
2279 override_nonepa
=override_nonepa
,
2280 override_paravirt
=override_paravirt
,
2287 @cli_osm.command(name
="ns-create", short_help
="creates a new Network Service instance")
2288 @click.option("--ns_name", prompt
=True, help="name of the NS instance")
2289 @click.option("--nsd_name", prompt
=True, help="name of the NS descriptor")
2293 help="default VIM account id or name for the deployment",
2295 @click.option("--admin_status", default
="ENABLED", help="administration status")
2299 help="comma separated list of public key files to inject to vnfs",
2301 @click.option("--config", default
=None, help="ns specific yaml configuration")
2302 @click.option("--config_file", default
=None, help="ns specific yaml configuration file")
2308 help="do not return the control immediately, but keep it "
2309 "until the operation is completed, or timeout",
2311 @click.option("--timeout", default
=None, help="ns deployment timeout")
2325 """creates a new NS instance"""
2329 check_client_version(ctx
.obj
, "--config_file")
2331 raise ClientException(
2332 '"--config" option is incompatible with "--config_file" option'
2334 with
open(config_file
, "r") as cf
:
2341 account
=vim_account
,
2345 # except ClientException as e:
2350 def nst_create(ctx
, filename
, overwrite
):
2353 check_client_version(ctx
.obj
, ctx
.command
.name
)
2354 ctx
.obj
.nst
.create(filename
, overwrite
)
2355 # except ClientException as e:
2361 name
="nst-create", short_help
="creates a new Network Slice Template (NST)"
2363 @click.argument("filename")
2367 default
=None, # hidden=True,
2368 help="Deprecated. Use override",
2374 help="overrides fields in descriptor, format: "
2375 '"key1.key2...=value[;key3...=value;...]"',
2378 def nst_create1(ctx
, filename
, overwrite
):
2379 """creates a new Network Slice Template (NST)
2381 FILENAME: NST package folder, NST yaml file or NSTpkg tar.gz file
2384 nst_create(ctx
, filename
, overwrite
)
2388 name
="netslice-template-create",
2389 short_help
="creates a new Network Slice Template (NST)",
2391 @click.argument("filename")
2395 default
=None, # hidden=True,
2396 help="Deprecated. Use override",
2402 help="overrides fields in descriptor, format: "
2403 '"key1.key2...=value[;key3...=value;...]"',
2406 def nst_create2(ctx
, filename
, overwrite
):
2407 """creates a new Network Slice Template (NST)
2409 FILENAME: NST yaml file or NSTpkg tar.gz file
2412 nst_create(ctx
, filename
, overwrite
)
2416 ctx
, nst_name
, nsi_name
, vim_account
, ssh_keys
, config
, config_file
, wait
2418 """creates a new Network Slice Instance (NSI)"""
2421 check_client_version(ctx
.obj
, ctx
.command
.name
)
2424 raise ClientException(
2425 '"--config" option is incompatible with "--config_file" option'
2427 with
open(config_file
, "r") as cf
:
2434 account
=vim_account
,
2437 # except ClientException as e:
2442 @cli_osm.command(name
="nsi-create", short_help
="creates a new Network Slice Instance")
2443 @click.option("--nsi_name", prompt
=True, help="name of the Network Slice Instance")
2444 @click.option("--nst_name", prompt
=True, help="name of the Network Slice Template")
2448 help="default VIM account id or name for the deployment",
2451 "--ssh_keys", default
=None, help="comma separated list of keys to inject to vnfs"
2456 help="Netslice specific yaml configuration:\n"
2457 "netslice_subnet: [\n"
2458 "id: TEXT, vim_account: TEXT,\n"
2459 "vnf: [member-vnf-index: TEXT, vim_account: TEXT]\n"
2460 "vld: [name: TEXT, vim-network-name: TEXT or DICT with vim_account, vim_net entries]\n"
2461 "additionalParamsForNsi: {param: value, ...}\n"
2462 "additionalParamsForsubnet: [{id: SUBNET_ID, additionalParamsForNs: {}, additionalParamsForVnf: {}}]\n"
2464 "netslice-vld: [name: TEXT, vim-network-name: TEXT or DICT with vim_account, vim_net entries]",
2467 "--config_file", default
=None, help="nsi specific yaml configuration file"
2474 help="do not return the control immediately, but keep it "
2475 "until the operation is completed, or timeout",
2479 ctx
, nst_name
, nsi_name
, vim_account
, ssh_keys
, config
, config_file
, wait
2481 """creates a new Network Slice Instance (NSI)"""
2484 ctx
, nst_name
, nsi_name
, vim_account
, ssh_keys
, config
, config_file
, wait
=wait
2489 name
="netslice-instance-create", short_help
="creates a new Network Slice Instance"
2491 @click.option("--nsi_name", prompt
=True, help="name of the Network Slice Instance")
2492 @click.option("--nst_name", prompt
=True, help="name of the Network Slice Template")
2496 help="default VIM account id or name for the deployment",
2499 "--ssh_keys", default
=None, help="comma separated list of keys to inject to vnfs"
2504 help="Netslice specific yaml configuration:\n"
2505 "netslice_subnet: [\n"
2506 "id: TEXT, vim_account: TEXT,\n"
2507 "vnf: [member-vnf-index: TEXT, vim_account: TEXT]\n"
2508 "vld: [name: TEXT, vim-network-name: TEXT or DICT with vim_account, vim_net entries]"
2510 "netslice-vld: [name: TEXT, vim-network-name: TEXT or DICT with vim_account, vim_net entries]",
2513 "--config_file", default
=None, help="nsi specific yaml configuration file"
2520 help="do not return the control immediately, but keep it "
2521 "until the operation is completed, or timeout",
2525 ctx
, nst_name
, nsi_name
, vim_account
, ssh_keys
, config
, config_file
, wait
2527 """creates a new Network Slice Instance (NSI)"""
2530 ctx
, nst_name
, nsi_name
, vim_account
, ssh_keys
, config
, config_file
, wait
=wait
2535 name
="pdu-create", short_help
="adds a new Physical Deployment Unit to the catalog"
2537 @click.option("--name", help="name of the Physical Deployment Unit")
2538 @click.option("--pdu_type", help="type of PDU (e.g. router, firewall, FW001)")
2541 help="interface(s) of the PDU: name=<NAME>,mgmt=<true|false>,ip-address=<IP_ADDRESS>"
2542 + "[,type=<overlay|underlay>][,mac-address=<MAC_ADDRESS>][,vim-network-name=<VIM_NET_NAME>]",
2545 @click.option("--description", help="human readable description")
2548 help="list of VIM accounts (in the same VIM) that can reach this PDU\n"
2549 + "The format for multiple VIMs is --vim_account <vim_account_id_1> "
2550 + "--vim_account <vim_account_id_2> ... --vim_account <vim_account_id_N>",
2554 "--descriptor_file",
2556 help="PDU descriptor file (as an alternative to using the other arguments)",
2560 ctx
, name
, pdu_type
, interface
, description
, vim_account
, descriptor_file
2562 """creates a new Physical Deployment Unit (PDU)"""
2565 check_client_version(ctx
.obj
, ctx
.command
.name
)
2567 pdu
= create_pdu_dictionary(
2568 name
, pdu_type
, interface
, description
, vim_account
, descriptor_file
2570 ctx
.obj
.pdu
.create(pdu
)
2573 ########################
2574 # UPDATE PDU operation #
2575 ########################
2579 name
="pdu-update", short_help
="updates a Physical Deployment Unit to the catalog"
2581 @click.argument("name")
2582 @click.option("--newname", help="New name for the Physical Deployment Unit")
2583 @click.option("--pdu_type", help="type of PDU (e.g. router, firewall, FW001)")
2586 help="interface(s) of the PDU: name=<NAME>,mgmt=<true|false>,ip-address=<IP_ADDRESS>"
2587 + "[,type=<overlay|underlay>][,mac-address=<MAC_ADDRESS>][,vim-network-name=<VIM_NET_NAME>]",
2590 @click.option("--description", help="human readable description")
2593 help="list of VIM accounts (in the same VIM) that can reach this PDU\n"
2594 + "The format for multiple VIMs is --vim_account <vim_account_id_1> "
2595 + "--vim_account <vim_account_id_2> ... --vim_account <vim_account_id_N>",
2599 "--descriptor_file",
2601 help="PDU descriptor file (as an alternative to using the other arguments)",
2605 ctx
, name
, newname
, pdu_type
, interface
, description
, vim_account
, descriptor_file
2607 """Updates a new Physical Deployment Unit (PDU)"""
2610 check_client_version(ctx
.obj
, ctx
.command
.name
)
2617 pdu
= create_pdu_dictionary(
2618 newname
, pdu_type
, interface
, description
, vim_account
, descriptor_file
, update
2620 ctx
.obj
.pdu
.update(name
, pdu
)
2623 def create_pdu_dictionary(
2624 name
, pdu_type
, interface
, description
, vim_account
, descriptor_file
, update
=False
2630 if not descriptor_file
:
2633 raise ClientException(
2634 'in absence of descriptor file, option "--name" is mandatory'
2637 raise ClientException(
2638 'in absence of descriptor file, option "--pdu_type" is mandatory'
2641 raise ClientException(
2642 'in absence of descriptor file, option "--interface" is mandatory (at least once)'
2645 raise ClientException(
2646 'in absence of descriptor file, option "--vim_account" is mandatory (at least once)'
2649 with
open(descriptor_file
, "r") as df
:
2650 pdu
= yaml
.safe_load(df
.read())
2654 pdu
["type"] = pdu_type
2656 pdu
["description"] = description
2658 pdu
["vim_accounts"] = vim_account
2661 for iface
in interface
:
2662 new_iface
= {k
: v
for k
, v
in [i
.split("=") for i
in iface
.split(",")]}
2663 new_iface
["mgmt"] = new_iface
.get("mgmt", "false").lower() == "true"
2664 ifaces_list
.append(new_iface
)
2665 pdu
["interfaces"] = ifaces_list
2669 ####################
2671 ####################
2674 def nsd_update(ctx
, name
, content
):
2677 check_client_version(ctx
.obj
, ctx
.command
.name
)
2678 ctx
.obj
.nsd
.update(name
, content
)
2679 # except ClientException as e:
2684 @cli_osm.command(name
="nsd-update", short_help
="updates a NSD/NSpkg")
2685 @click.argument("name")
2689 help="filename with the NSD/NSpkg replacing the current one",
2692 def nsd_update1(ctx
, name
, content
):
2693 """updates a NSD/NSpkg
2695 NAME: name or ID of the NSD/NSpkg
2698 nsd_update(ctx
, name
, content
)
2701 @cli_osm.command(name
="nspkg-update", short_help
="updates a NSD/NSpkg")
2702 @click.argument("name")
2706 help="filename with the NSD/NSpkg replacing the current one",
2709 def nsd_update2(ctx
, name
, content
):
2710 """updates a NSD/NSpkg
2712 NAME: name or ID of the NSD/NSpkg
2715 nsd_update(ctx
, name
, content
)
2718 def vnfd_update(ctx
, name
, content
):
2721 check_client_version(ctx
.obj
, ctx
.command
.name
)
2722 ctx
.obj
.vnfd
.update(name
, content
)
2723 # except ClientException as e:
2728 @cli_osm.command(name
="vnfd-update", short_help
="updates a new VNFD/VNFpkg")
2729 @click.argument("name")
2733 help="filename with the VNFD/VNFpkg replacing the current one",
2736 def vnfd_update1(ctx
, name
, content
):
2737 """updates a VNFD/VNFpkg
2739 NAME: name or ID of the VNFD/VNFpkg
2742 vnfd_update(ctx
, name
, content
)
2745 @cli_osm.command(name
="vnfpkg-update", short_help
="updates a VNFD/VNFpkg")
2746 @click.argument("name")
2750 help="filename with the VNFD/VNFpkg replacing the current one",
2753 def vnfd_update2(ctx
, name
, content
):
2754 """updates a VNFD/VNFpkg
2756 NAME: VNFD yaml file or VNFpkg tar.gz file
2759 vnfd_update(ctx
, name
, content
)
2762 @cli_osm.command(name
="nfpkg-update", short_help
="updates a NFpkg")
2763 @click.argument("name")
2765 "--content", default
=None, help="filename with the NFpkg replacing the current one"
2768 def nfpkg_update(ctx
, name
, content
):
2771 NAME: NF Descriptor yaml file or NFpkg tar.gz file
2774 vnfd_update(ctx
, name
, content
)
2777 def nst_update(ctx
, name
, content
):
2780 check_client_version(ctx
.obj
, ctx
.command
.name
)
2781 ctx
.obj
.nst
.update(name
, content
)
2782 # except ClientException as e:
2787 @cli_osm.command(name
="nst-update", short_help
="updates a Network Slice Template (NST)")
2788 @click.argument("name")
2792 help="filename with the NST/NSTpkg replacing the current one",
2795 def nst_update1(ctx
, name
, content
):
2796 """updates a Network Slice Template (NST)
2798 NAME: name or ID of the NSD/NSpkg
2801 nst_update(ctx
, name
, content
)
2805 name
="netslice-template-update", short_help
="updates a Network Slice Template (NST)"
2807 @click.argument("name")
2811 help="filename with the NST/NSTpkg replacing the current one",
2814 def nst_update2(ctx
, name
, content
):
2815 """updates a Network Slice Template (NST)
2817 NAME: name or ID of the NSD/NSpkg
2820 nst_update(ctx
, name
, content
)
2823 ####################
2825 ####################
2828 def nsd_delete(ctx
, name
, force
):
2832 ctx
.obj
.nsd
.delete(name
)
2834 check_client_version(ctx
.obj
, "--force")
2835 ctx
.obj
.nsd
.delete(name
, force
)
2836 # except ClientException as e:
2841 @cli_osm.command(name
="nsd-delete", short_help
="deletes a NSD/NSpkg")
2842 @click.argument("name")
2844 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
2847 def nsd_delete1(ctx
, name
, force
):
2848 """deletes a NSD/NSpkg
2850 NAME: name or ID of the NSD/NSpkg to be deleted
2853 nsd_delete(ctx
, name
, force
)
2856 @cli_osm.command(name
="nspkg-delete", short_help
="deletes a NSD/NSpkg")
2857 @click.argument("name")
2859 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
2862 def nsd_delete2(ctx
, name
, force
):
2863 """deletes a NSD/NSpkg
2865 NAME: name or ID of the NSD/NSpkg to be deleted
2868 nsd_delete(ctx
, name
, force
)
2871 def vnfd_delete(ctx
, name
, force
):
2875 ctx
.obj
.vnfd
.delete(name
)
2877 check_client_version(ctx
.obj
, "--force")
2878 ctx
.obj
.vnfd
.delete(name
, force
)
2879 # except ClientException as e:
2884 @cli_osm.command(name
="vnfd-delete", short_help
="deletes a VNFD/VNFpkg")
2885 @click.argument("name")
2887 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
2890 def vnfd_delete1(ctx
, name
, force
):
2891 """deletes a VNFD/VNFpkg
2893 NAME: name or ID of the VNFD/VNFpkg to be deleted
2896 vnfd_delete(ctx
, name
, force
)
2899 @cli_osm.command(name
="vnfpkg-delete", short_help
="deletes a VNFD/VNFpkg")
2900 @click.argument("name")
2902 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
2905 def vnfd_delete2(ctx
, name
, force
):
2906 """deletes a VNFD/VNFpkg
2908 NAME: name or ID of the VNFD/VNFpkg to be deleted
2911 vnfd_delete(ctx
, name
, force
)
2914 @cli_osm.command(name
="nfpkg-delete", short_help
="deletes a NFpkg")
2915 @click.argument("name")
2917 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
2920 def nfpkg_delete(ctx
, name
, force
):
2923 NAME: name or ID of the NFpkg to be deleted
2926 vnfd_delete(ctx
, name
, force
)
2929 @cli_osm.command(name
="ns-delete", short_help
="deletes a NS instance")
2930 @click.argument("name")
2932 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
2937 help="specific yaml configuration for the termination, e.g. '{autoremove: False, timeout_ns_terminate: "
2938 "600, skip_terminate_primitives: True}'",
2945 help="do not return the control immediately, but keep it "
2946 "until the operation is completed, or timeout",
2949 def ns_delete(ctx
, name
, force
, config
, wait
):
2950 """deletes a NS instance
2952 NAME: name or ID of the NS instance to be deleted
2957 ctx
.obj
.ns
.delete(name
, config
=config
, wait
=wait
)
2959 check_client_version(ctx
.obj
, "--force")
2960 ctx
.obj
.ns
.delete(name
, force
, config
=config
, wait
=wait
)
2961 # except ClientException as e:
2966 def nst_delete(ctx
, name
, force
):
2969 check_client_version(ctx
.obj
, ctx
.command
.name
)
2970 ctx
.obj
.nst
.delete(name
, force
)
2971 # except ClientException as e:
2976 @cli_osm.command(name
="nst-delete", short_help
="deletes a Network Slice Template (NST)")
2977 @click.argument("name")
2979 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
2982 def nst_delete1(ctx
, name
, force
):
2983 """deletes a Network Slice Template (NST)
2985 NAME: name or ID of the NST/NSTpkg to be deleted
2988 nst_delete(ctx
, name
, force
)
2992 name
="netslice-template-delete", short_help
="deletes a Network Slice Template (NST)"
2994 @click.argument("name")
2996 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
2999 def nst_delete2(ctx
, name
, force
):
3000 """deletes a Network Slice Template (NST)
3002 NAME: name or ID of the NST/NSTpkg to be deleted
3005 nst_delete(ctx
, name
, force
)
3008 def nsi_delete(ctx
, name
, force
, wait
):
3011 check_client_version(ctx
.obj
, ctx
.command
.name
)
3012 ctx
.obj
.nsi
.delete(name
, force
, wait
=wait
)
3013 # except ClientException as e:
3018 @cli_osm.command(name
="nsi-delete", short_help
="deletes a Network Slice Instance (NSI)")
3019 @click.argument("name")
3021 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
3028 help="do not return the control immediately, but keep it "
3029 "until the operation is completed, or timeout",
3032 def nsi_delete1(ctx
, name
, force
, wait
):
3033 """deletes a Network Slice Instance (NSI)
3035 NAME: name or ID of the Network Slice instance to be deleted
3038 nsi_delete(ctx
, name
, force
, wait
=wait
)
3042 name
="netslice-instance-delete", short_help
="deletes a Network Slice Instance (NSI)"
3044 @click.argument("name")
3046 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
3049 def nsi_delete2(ctx
, name
, force
, wait
):
3050 """deletes a Network Slice Instance (NSI)
3052 NAME: name or ID of the Network Slice instance to be deleted
3055 nsi_delete(ctx
, name
, force
, wait
=wait
)
3059 name
="pdu-delete", short_help
="deletes a Physical Deployment Unit (PDU)"
3061 @click.argument("name")
3063 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
3066 def pdu_delete(ctx
, name
, force
):
3067 """deletes a Physical Deployment Unit (PDU)
3069 NAME: name or ID of the PDU to be deleted
3073 check_client_version(ctx
.obj
, ctx
.command
.name
)
3074 ctx
.obj
.pdu
.delete(name
, force
)
3075 # except ClientException as e:
3085 def _check_ca_cert(vim_config
: dict) -> None:
3087 Checks if the VIM has a CA certificate.
3088 In that case, reads the content and add it to the config
3089 : param vim_config: configuration provided with the VIM creation
3093 if vim_config
.get("ca_cert"):
3094 with
open(vim_config
["ca_cert"], "r") as cert_f
:
3095 vim_config
["ca_cert_content"] = str(cert_f
.read())
3096 del vim_config
["ca_cert"]
3099 @cli_osm.command(name
="vim-create", short_help
="creates a new VIM account")
3100 @click.option("--name", required
=True, help="Name to create datacenter")
3101 @click.option("--user", default
=None, help="VIM username")
3102 @click.option("--password", default
=None, help="VIM password")
3103 @click.option("--auth_url", default
=None, help="VIM url")
3105 "--tenant", "--project", "tenant", default
=None, help="VIM tenant/project name"
3107 @click.option("--config", default
=None, help="VIM specific config parameters")
3111 help="VIM specific config parameters in YAML or JSON file",
3113 @click.option("--account_type", default
="openstack", help="VIM type")
3114 @click.option("--description", default
=None, help="human readable description")
3118 help="Name or id of the SDN controller associated to this VIM account",
3121 "--sdn_port_mapping",
3123 help="File describing the port mapping between compute nodes' ports and switch ports",
3130 help="do not return the control immediately, but keep it "
3131 "until the operation is completed, or timeout",
3133 @click.option("--vca", default
=None, help="VCA to be used in this VIM account")
3135 "--creds", default
=None, help="credentials file (only applycable for GCP VIM type)"
3138 "--prometheus_config_file",
3140 help="Prometheus configuration to get VIM data",
3159 prometheus_config_file
,
3161 """creates a new VIM account"""
3165 check_client_version(ctx
.obj
, "--sdn_controller")
3166 if sdn_port_mapping
:
3167 check_client_version(ctx
.obj
, "--sdn_port_mapping")
3169 if prometheus_config_file
:
3170 with
open(prometheus_config_file
) as prometheus_file
:
3171 prometheus_config_dict
= json
.load(prometheus_file
)
3172 vim
["prometheus-config"] = prometheus_config_dict
3174 vim
["vim-username"] = user
3175 vim
["vim-password"] = password
3176 vim
["vim-url"] = auth_url
3177 vim
["vim-tenant-name"] = tenant
3178 vim
["vim-type"] = account_type
3179 vim
["description"] = description
3182 vim_config
= create_config(config_file
, config
)
3183 _check_ca_cert(vim_config
)
3185 with
open(creds
, "r") as cf
:
3186 vim_config
["credentials"] = yaml
.safe_load(cf
.read())
3188 name
, vim
, vim_config
, sdn_controller
, sdn_port_mapping
, wait
=wait
3190 # except ClientException as e:
3195 @cli_osm.command(name
="vim-update", short_help
="updates a VIM account")
3196 @click.argument("name")
3197 @click.option("--newname", help="New name for the VIM account")
3198 @click.option("--user", help="VIM username")
3199 @click.option("--password", help="VIM password")
3200 @click.option("--auth_url", help="VIM url")
3201 @click.option("--tenant", help="VIM tenant name")
3202 @click.option("--config", help="VIM specific config parameters")
3206 help="VIM specific config parameters in YAML or JSON file",
3208 @click.option("--account_type", help="VIM type")
3209 @click.option("--description", help="human readable description")
3213 help="Name or id of the SDN controller to be associated with this VIM"
3214 "account. Use empty string to disassociate",
3217 "--sdn_port_mapping",
3219 help="File describing the port mapping between compute nodes' ports and switch ports",
3226 help="do not return the control immediately, but keep it "
3227 "until the operation is completed, or timeout",
3230 "--creds", default
=None, help="credentials file (only applycable for GCP VIM type)"
3233 "--prometheus_config_file",
3235 help="Prometheus configuration to get VIM data",
3254 prometheus_config_file
,
3256 """updates a VIM account
3258 NAME: name or ID of the VIM account
3262 check_client_version(ctx
.obj
, ctx
.command
.name
)
3265 vim
["name"] = newname
3267 vim
["vim_user"] = user
3269 vim
["vim_password"] = password
3271 vim
["vim_url"] = auth_url
3273 vim
["vim-tenant-name"] = tenant
3275 vim
["vim_type"] = account_type
3277 vim
["description"] = description
3279 if config
or config_file
:
3280 vim_config
= create_config(config_file
, config
)
3281 _check_ca_cert(vim_config
)
3283 with
open(creds
, "r") as cf
:
3284 vim_config
["credentials"] = yaml
.safe_load(cf
.read())
3285 if prometheus_config_file
:
3286 with
open(prometheus_config_file
) as prometheus_file
:
3287 prometheus_config_dict
= json
.load(prometheus_file
)
3288 vim
["prometheus-config"] = prometheus_config_dict
3289 logger
.info(f
"VIM: {vim}, VIM config: {vim_config}")
3291 name
, vim
, vim_config
, sdn_controller
, sdn_port_mapping
, wait
=wait
3293 # except ClientException as e:
3298 @cli_osm.command(name
="vim-delete", short_help
="deletes a VIM account")
3299 @click.argument("name")
3301 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
3308 help="do not return the control immediately, but keep it "
3309 "until the operation is completed, or timeout",
3312 def vim_delete(ctx
, name
, force
, wait
):
3313 """deletes a VIM account
3315 NAME: name or ID of the VIM account to be deleted
3320 ctx
.obj
.vim
.delete(name
, wait
=wait
)
3322 check_client_version(ctx
.obj
, "--force")
3323 ctx
.obj
.vim
.delete(name
, force
, wait
=wait
)
3324 # except ClientException as e:
3329 @cli_osm.command(name
="vim-list", short_help
="list all VIM accounts")
3330 # @click.option('--ro_update/--no_ro_update',
3332 # help='update list from RO')
3337 help="restricts the list to the VIM accounts matching the filter",
3342 help="get more details of the NS (project, vim, deployment status, configuration status.",
3345 def vim_list(ctx
, filter, long):
3346 """list all VIM accounts"""
3349 filter = "&".join(filter)
3350 check_client_version(ctx
.obj
, "--filter")
3352 # check_client_version(ctx.obj, '--ro_update', 'v1')
3353 fullclassname
= ctx
.obj
.__module
__ + "." + ctx
.obj
.__class
__.__name
__
3354 if fullclassname
== "osmclient.sol005.client.Client":
3355 resp
= ctx
.obj
.vim
.list(filter)
3357 # resp = ctx.obj.vim.list(ro_update)
3359 table
= PrettyTable(
3360 ["vim name", "uuid", "project", "operational state", "error details"]
3362 project_list
= ctx
.obj
.project
.list()
3364 table
= PrettyTable(["vim name", "uuid", "operational state"])
3367 if "vim_password" in vim
:
3368 vim
["vim_password"] = "********"
3369 if "config" in vim
and "credentials" in vim
["config"]:
3370 vim
["config"]["credentials"] = "********"
3371 logger
.debug("VIM details: {}".format(yaml
.safe_dump(vim
)))
3372 vim_state
= vim
["_admin"].get("operationalState", "-")
3373 error_details
= "N/A"
3374 if vim_state
== "ERROR":
3375 error_details
= vim
["_admin"].get("detailed-status", "Not found")
3376 project_id
, project_name
= get_project(project_list
, vim
)
3377 # project_info = '{} ({})'.format(project_name, project_id)
3378 project_info
= project_name
3385 wrap_text(text
=error_details
, width
=80),
3390 [vim
["name"], vim
["uuid"], vim
["_admin"].get("operationalState", "-")]
3396 @cli_osm.command(name
="vim-show", short_help
="shows the details of a VIM account")
3397 @click.argument("name")
3401 help="restricts the information to the fields in the filter",
3403 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
3405 def vim_show(ctx
, name
, filter, literal
):
3406 """shows the details of a VIM account
3408 NAME: name or ID of the VIM account
3412 resp
= ctx
.obj
.vim
.get(name
)
3413 if "vim_password" in resp
:
3414 resp
["vim_password"] = "********"
3415 if "config" in resp
and "credentials" in resp
["config"]:
3416 resp
["config"]["credentials"] = "********"
3417 # except ClientException as e:
3422 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
3424 table
= PrettyTable(["key", "attribute"])
3425 for k
, v
in list(resp
.items()):
3426 if not filter or k
in filter:
3427 table
.add_row([k
, wrap_text(text
=json
.dumps(v
, indent
=2), width
=100)])
3432 ####################
3434 ####################
3437 @cli_osm.command(name
="wim-create", short_help
="creates a new WIM account")
3438 @click.option("--name", prompt
=True, help="Name for the WIM account")
3439 @click.option("--user", help="WIM username")
3440 @click.option("--password", help="WIM password")
3441 @click.option("--url", prompt
=True, help="WIM url")
3442 # @click.option('--tenant',
3443 # help='wIM tenant name')
3444 @click.option("--config", default
=None, help="WIM specific config parameters")
3445 @click.option("--wim_type", help="WIM type")
3446 @click.option("--description", default
=None, help="human readable description")
3448 "--wim_port_mapping",
3450 help="File describing the port mapping between DC edge (datacenters, switches, ports) and WAN edge "
3451 "(WAN service endpoint id and info)",
3458 help="do not return the control immediately, but keep it "
3459 "until the operation is completed, or timeout",
3475 """creates a new WIM account"""
3478 check_client_version(ctx
.obj
, ctx
.command
.name
)
3479 # if sdn_controller:
3480 # check_client_version(ctx.obj, '--sdn_controller')
3481 # if sdn_port_mapping:
3482 # check_client_version(ctx.obj, '--sdn_port_mapping')
3487 wim
["password"] = password
3489 wim
["wim_url"] = url
3490 # if tenant: wim['tenant'] = tenant
3491 wim
["wim_type"] = wim_type
3493 wim
["description"] = description
3495 wim
["config"] = config
3496 ctx
.obj
.wim
.create(name
, wim
, wim_port_mapping
, wait
=wait
)
3497 # except ClientException as e:
3502 @cli_osm.command(name
="wim-update", short_help
="updates a WIM account")
3503 @click.argument("name")
3504 @click.option("--newname", help="New name for the WIM account")
3505 @click.option("--user", help="WIM username")
3506 @click.option("--password", help="WIM password")
3507 @click.option("--url", help="WIM url")
3508 @click.option("--config", help="WIM specific config parameters")
3509 @click.option("--wim_type", help="WIM type")
3510 @click.option("--description", help="human readable description")
3512 "--wim_port_mapping",
3514 help="File describing the port mapping between DC edge (datacenters, switches, ports) and WAN edge "
3515 "(WAN service endpoint id and info)",
3522 help="do not return the control immediately, but keep it until the operation is completed, or timeout",
3538 """updates a WIM account
3540 NAME: name or ID of the WIM account
3544 check_client_version(ctx
.obj
, ctx
.command
.name
)
3547 wim
["name"] = newname
3551 wim
["password"] = password
3554 # if tenant: wim['tenant'] = tenant
3556 wim
["wim_type"] = wim_type
3558 wim
["description"] = description
3560 wim
["config"] = config
3561 ctx
.obj
.wim
.update(name
, wim
, wim_port_mapping
, wait
=wait
)
3562 # except ClientException as e:
3567 @cli_osm.command(name
="wim-delete", short_help
="deletes a WIM account")
3568 @click.argument("name")
3570 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
3577 help="do not return the control immediately, but keep it until the operation is completed, or timeout",
3580 def wim_delete(ctx
, name
, force
, wait
):
3581 """deletes a WIM account
3583 NAME: name or ID of the WIM account to be deleted
3587 check_client_version(ctx
.obj
, ctx
.command
.name
)
3588 ctx
.obj
.wim
.delete(name
, force
, wait
=wait
)
3589 # except ClientException as e:
3594 @cli_osm.command(name
="wim-list", short_help
="list all WIM accounts")
3599 help="restricts the list to the WIM accounts matching the filter",
3602 def wim_list(ctx
, filter):
3603 """list all WIM accounts"""
3606 check_client_version(ctx
.obj
, ctx
.command
.name
)
3608 filter = "&".join(filter)
3609 resp
= ctx
.obj
.wim
.list(filter)
3610 table
= PrettyTable(["wim name", "uuid"])
3612 table
.add_row([wim
["name"], wim
["uuid"]])
3615 # except ClientException as e:
3620 @cli_osm.command(name
="wim-show", short_help
="shows the details of a WIM account")
3621 @click.argument("name")
3623 def wim_show(ctx
, name
):
3624 """shows the details of a WIM account
3626 NAME: name or ID of the WIM account
3630 check_client_version(ctx
.obj
, ctx
.command
.name
)
3631 resp
= ctx
.obj
.wim
.get(name
)
3632 if "password" in resp
:
3633 resp
["password"] = "********"
3634 # except ClientException as e:
3638 table
= PrettyTable(["key", "attribute"])
3639 for k
, v
in list(resp
.items()):
3640 table
.add_row([k
, json
.dumps(v
, indent
=2)])
3645 ####################
3646 # SDN controller operations
3647 ####################
3650 @cli_osm.command(name
="sdnc-create", short_help
="creates a new SDN controller")
3651 @click.option("--name", prompt
=True, help="Name to create sdn controller")
3652 @click.option("--type", prompt
=True, help="SDN controller type")
3654 "--sdn_controller_version", # hidden=True,
3655 help="Deprecated. Use --config {version: sdn_controller_version}",
3657 @click.option("--url", help="URL in format http[s]://HOST:IP/")
3658 @click.option("--ip_address", help="Deprecated. Use --url") # hidden=True,
3659 @click.option("--port", help="Deprecated. Use --url") # hidden=True,
3661 "--switch_dpid", help="Deprecated. Use --config {switch_id: DPID}" # hidden=True,
3665 help="Extra information for SDN in yaml format, as {switch_id: identity used for the plugin (e.g. DPID: "
3666 "Openflow Datapath ID), version: version}",
3668 @click.option("--user", help="SDN controller username")
3672 confirmation_prompt
=True,
3673 help="SDN controller password",
3675 @click.option("--description", default
=None, help="human readable description")
3681 help="do not return the control immediately, but keep it until the operation is completed, or timeout",
3684 def sdnc_create(ctx
, **kwargs
):
3685 """creates a new SDN controller"""
3690 if kwargs
[x
] and x
not in ("wait", "ip_address", "port", "switch_dpid")
3692 if kwargs
.get("port"):
3693 print("option '--port' is deprecated, use '--url' instead")
3694 sdncontroller
["port"] = int(kwargs
["port"])
3695 if kwargs
.get("ip_address"):
3696 print("option '--ip_address' is deprecated, use '--url' instead")
3697 sdncontroller
["ip"] = kwargs
["ip_address"]
3698 if kwargs
.get("switch_dpid"):
3700 "option '--switch_dpid' is deprecated, use '--config={switch_id: id|DPID}' instead"
3702 sdncontroller
["dpid"] = kwargs
["switch_dpid"]
3703 if kwargs
.get("sdn_controller_version"):
3705 "option '--sdn_controller_version' is deprecated, use '--config={version: SDN_CONTROLLER_VERSION}'"
3709 check_client_version(ctx
.obj
, ctx
.command
.name
)
3710 ctx
.obj
.sdnc
.create(kwargs
["name"], sdncontroller
, wait
=kwargs
["wait"])
3711 # except ClientException as e:
3716 @cli_osm.command(name
="sdnc-update", short_help
="updates an SDN controller")
3717 @click.argument("name")
3718 @click.option("--newname", help="New name for the SDN controller")
3719 @click.option("--description", default
=None, help="human readable description")
3720 @click.option("--type", help="SDN controller type")
3721 @click.option("--url", help="URL in format http[s]://HOST:IP/")
3724 help="Extra information for SDN in yaml format, as "
3725 "{switch_id: identity used for the plugin (e.g. DPID: "
3726 "Openflow Datapath ID), version: version}",
3728 @click.option("--user", help="SDN controller username")
3729 @click.option("--password", help="SDN controller password")
3730 @click.option("--ip_address", help="Deprecated. Use --url") # hidden=True
3731 @click.option("--port", help="Deprecated. Use --url") # hidden=True
3733 "--switch_dpid", help="Deprecated. Use --config {switch_dpid: DPID}"
3736 "--sdn_controller_version", help="Deprecated. Use --config {version: VERSION}"
3743 help="do not return the control immediately, but keep it until the operation is completed, or timeout",
3746 def sdnc_update(ctx
, **kwargs
):
3747 """updates an SDN controller
3749 NAME: name or ID of the SDN controller
3756 and x
not in ("wait", "ip_address", "port", "switch_dpid", "new_name")
3758 if kwargs
.get("newname"):
3759 sdncontroller
["name"] = kwargs
["newname"]
3760 if kwargs
.get("port"):
3761 print("option '--port' is deprecated, use '--url' instead")
3762 sdncontroller
["port"] = int(kwargs
["port"])
3763 if kwargs
.get("ip_address"):
3764 print("option '--ip_address' is deprecated, use '--url' instead")
3765 sdncontroller
["ip"] = kwargs
["ip_address"]
3766 if kwargs
.get("switch_dpid"):
3768 "option '--switch_dpid' is deprecated, use '--config={switch_id: id|DPID}' instead"
3770 sdncontroller
["dpid"] = kwargs
["switch_dpid"]
3771 if kwargs
.get("sdn_controller_version"):
3773 "option '--sdn_controller_version' is deprecated, use '---config={version: SDN_CONTROLLER_VERSION}'"
3778 check_client_version(ctx
.obj
, ctx
.command
.name
)
3779 ctx
.obj
.sdnc
.update(kwargs
["name"], sdncontroller
, wait
=kwargs
["wait"])
3780 # except ClientException as e:
3785 @cli_osm.command(name
="sdnc-delete", short_help
="deletes an SDN controller")
3786 @click.argument("name")
3788 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
3795 help="do not return the control immediately, but keep it until the operation is completed, or timeout",
3798 def sdnc_delete(ctx
, name
, force
, wait
):
3799 """deletes an SDN controller
3801 NAME: name or ID of the SDN controller to be deleted
3805 check_client_version(ctx
.obj
, ctx
.command
.name
)
3806 ctx
.obj
.sdnc
.delete(name
, force
, wait
=wait
)
3807 # except ClientException as e:
3812 @cli_osm.command(name
="sdnc-list", short_help
="list all SDN controllers")
3817 help="restricts the list to the SDN controllers matching the filter with format: 'k[.k..]=v[&k[.k]=v2]'",
3820 def sdnc_list(ctx
, filter):
3821 """list all SDN controllers"""
3824 check_client_version(ctx
.obj
, ctx
.command
.name
)
3826 filter = "&".join(filter)
3827 resp
= ctx
.obj
.sdnc
.list(filter)
3828 # except ClientException as e:
3831 table
= PrettyTable(["sdnc name", "id"])
3833 table
.add_row([sdnc
["name"], sdnc
["_id"]])
3838 @cli_osm.command(name
="sdnc-show", short_help
="shows the details of an SDN controller")
3839 @click.argument("name")
3841 def sdnc_show(ctx
, name
):
3842 """shows the details of an SDN controller
3844 NAME: name or ID of the SDN controller
3848 check_client_version(ctx
.obj
, ctx
.command
.name
)
3849 resp
= ctx
.obj
.sdnc
.get(name
)
3850 # except ClientException as e:
3854 table
= PrettyTable(["key", "attribute"])
3855 for k
, v
in list(resp
.items()):
3856 table
.add_row([k
, json
.dumps(v
, indent
=2)])
3861 ###########################
3862 # K8s cluster operations
3863 ###########################
3866 @cli_osm.command(name
="k8scluster-add", short_help
="adds a K8s cluster to OSM")
3867 @click.argument("name")
3869 "--creds", prompt
=True, help="credentials file, i.e. a valid `.kube/config` file"
3871 @click.option("--version", prompt
=True, help="Kubernetes version")
3873 "--vim", prompt
=True, help="VIM target, the VIM where the cluster resides"
3878 help='''list of VIM networks, in JSON inline format, where the cluster is
3879 accessible via L3 routing, e.g. "{(k8s_net1:vim_network1) [,(k8s_net2:vim_network2) ...]}"''',
3882 "--init-helm2/--skip-helm2",
3885 help="Initialize helm v2",
3888 "--init-helm3/--skip-helm3",
3891 help="Initialize helm v3",
3894 "--init-jujubundle/--skip-jujubundle",
3897 help="Initialize juju-bundle",
3899 @click.option("--description", default
=None, help="human readable description")
3902 default
="kube-system",
3903 help="namespace to be used for its operation, defaults to `kube-system`",
3910 help="do not return the control immediately, but keep it "
3911 "until the operation is completed, or timeout",
3916 help="list of CNI plugins, in JSON inline format, used in the cluster",
3918 # @click.option('--skip-init',
3920 # help='If set, K8s cluster is assumed to be ready for its use with OSM')
3921 # @click.option('--wait',
3923 # help='do not return the control immediately, but keep it until the operation is completed, or timeout')
3940 """adds a K8s cluster to OSM
3942 NAME: name of the K8s cluster
3945 check_client_version(ctx
.obj
, ctx
.command
.name
)
3947 cluster
["name"] = name
3948 with
open(creds
, "r") as cf
:
3949 cluster
["credentials"] = yaml
.safe_load(cf
.read())
3950 cluster
["k8s_version"] = version
3951 cluster
["vim_account"] = vim
3952 cluster
["nets"] = yaml
.safe_load(k8s_nets
)
3953 if not (init_helm2
and init_jujubundle
and init_helm3
):
3954 cluster
["deployment_methods"] = {
3955 "helm-chart": init_helm2
,
3956 "juju-bundle": init_jujubundle
,
3957 "helm-chart-v3": init_helm3
,
3960 cluster
["description"] = description
3962 cluster
["namespace"] = namespace
3964 cluster
["cni"] = yaml
.safe_load(cni
)
3965 ctx
.obj
.k8scluster
.create(name
, cluster
, wait
)
3966 # except ClientException as e:
3971 @cli_osm.command(name
="k8scluster-update", short_help
="updates a K8s cluster")
3972 @click.argument("name")
3973 @click.option("--newname", help="New name for the K8s cluster")
3974 @click.option("--creds", help="credentials file, i.e. a valid `.kube/config` file")
3975 @click.option("--version", help="Kubernetes version")
3976 @click.option("--vim", help="VIM target, the VIM where the cluster resides")
3979 help='''list of VIM networks, in JSON inline format, where the cluster is accessible
3980 via L3 routing, e.g. "{(k8s_net1:vim_network1) [,(k8s_net2:vim_network2) ...]}"''',
3982 @click.option("--description", help="human readable description")
3985 help="namespace to be used for its operation, defaults to `kube-system`",
3992 help="do not return the control immediately, but keep it "
3993 "until the operation is completed, or timeout",
3996 "--cni", help="list of CNI plugins, in JSON inline format, used in the cluster"
3999 def k8scluster_update(
4000 ctx
, name
, newname
, creds
, version
, vim
, k8s_nets
, description
, namespace
, wait
, cni
4002 """updates a K8s cluster
4004 NAME: name or ID of the K8s cluster
4007 check_client_version(ctx
.obj
, ctx
.command
.name
)
4010 cluster
["name"] = newname
4012 with
open(creds
, "r") as cf
:
4013 cluster
["credentials"] = yaml
.safe_load(cf
.read())
4015 cluster
["k8s_version"] = version
4017 cluster
["vim_account"] = vim
4019 cluster
["nets"] = yaml
.safe_load(k8s_nets
)
4021 cluster
["description"] = description
4023 cluster
["namespace"] = namespace
4025 cluster
["cni"] = yaml
.safe_load(cni
)
4026 ctx
.obj
.k8scluster
.update(name
, cluster
, wait
)
4027 # except ClientException as e:
4032 @cli_osm.command(name
="k8scluster-delete", short_help
="deletes a K8s cluster")
4033 @click.argument("name")
4035 "--force", is_flag
=True, help="forces the deletion from the DB (not recommended)"
4042 help="do not return the control immediately, but keep it "
4043 "until the operation is completed, or timeout",
4046 def k8scluster_delete(ctx
, name
, force
, wait
):
4047 """deletes a K8s cluster
4049 NAME: name or ID of the K8s cluster to be deleted
4052 check_client_version(ctx
.obj
, ctx
.command
.name
)
4053 ctx
.obj
.k8scluster
.delete(name
, force
, wait
)
4054 # except ClientException as e:
4059 @cli_osm.command(name
="k8scluster-list")
4064 help="restricts the list to the K8s clusters matching the filter",
4066 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
4067 @click.option("--long", is_flag
=True, help="get more details")
4069 def k8scluster_list(ctx
, filter, literal
, long):
4070 """list all K8s clusters"""
4072 check_client_version(ctx
.obj
, ctx
.command
.name
)
4074 filter = "&".join(filter)
4075 resp
= ctx
.obj
.k8scluster
.list(filter)
4077 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
4080 table
= PrettyTable(
4088 "Deployment methods",
4089 "Operational State",
4090 "Op. state (details)",
4095 project_list
= ctx
.obj
.project
.list()
4097 table
= PrettyTable(
4098 ["Name", "Id", "VIM", "Operational State", "Op. state details"]
4101 vim_list
= ctx
.obj
.vim
.list()
4104 for cluster
in resp
:
4105 logger
.debug("Cluster details: {}".format(yaml
.safe_dump(cluster
)))
4106 vim_name
= get_vim_name(vim_list
, cluster
["vim_account"])
4107 # vim_info = '{} ({})'.format(vim_name,cluster['vim_account'])
4109 op_state_details
= "Helm: {}\nJuju: {}".format(
4110 cluster
["_admin"].get("helm-chart", {}).get("operationalState", "-"),
4111 cluster
["_admin"].get("juju-bundle", {}).get("operationalState", "-"),
4114 project_id
, project_name
= get_project(project_list
, cluster
)
4115 # project_info = '{} ({})'.format(project_name, project_id)
4116 project_info
= project_name
4117 detailed_status
= cluster
["_admin"].get("detailed-status", "-")
4123 cluster
["k8s_version"],
4125 json
.dumps(cluster
["nets"]),
4126 json
.dumps(cluster
["deployment_methods"]),
4127 cluster
["_admin"]["operationalState"],
4129 trunc_text(cluster
.get("description") or "", 40),
4130 wrap_text(text
=detailed_status
, width
=40),
4139 cluster
["_admin"]["operationalState"],
4145 # except ClientException as e:
4151 name
="k8scluster-show", short_help
="shows the details of a K8s cluster"
4153 @click.argument("name")
4154 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
4156 def k8scluster_show(ctx
, name
, literal
):
4157 """shows the details of a K8s cluster
4159 NAME: name or ID of the K8s cluster
4162 resp
= ctx
.obj
.k8scluster
.get(name
)
4164 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
4166 table
= PrettyTable(["key", "attribute"])
4167 for k
, v
in list(resp
.items()):
4168 table
.add_row([k
, wrap_text(text
=json
.dumps(v
, indent
=2), width
=100)])
4171 # except ClientException as e:
4176 ###########################
4178 ###########################
4181 @cli_osm.command(name
="vca-add", short_help
="adds a VCA (Juju controller) to OSM")
4182 @click.argument("name")
4186 help="Comma-separated list of IP or hostnames of the Juju controller",
4188 @click.option("--user", prompt
=True, help="Username with admin priviledges")
4189 @click.option("--secret", prompt
=True, help="Password of the specified username")
4190 @click.option("--cacert", prompt
=True, help="CA certificate")
4194 help="Name of the cloud that will be used for LXD containers (LXD proxy charms)",
4197 "--lxd-credentials",
4199 help="Name of the cloud credentialsto be used for the LXD cloud",
4204 help="Name of the cloud that will be used for K8s containers (K8s proxy charms)",
4207 "--k8s-credentials",
4209 help="Name of the cloud credentialsto be used for the K8s cloud",
4214 help="Configuration options for the models",
4216 @click.option("--description", default
=None, help="human readable description")
4232 """adds a VCA to OSM
4234 NAME: name of the VCA
4236 check_client_version(ctx
.obj
, ctx
.command
.name
)
4239 vca
["endpoints"] = endpoints
.split(",")
4241 vca
["secret"] = secret
4242 vca
["cacert"] = cacert
4243 vca
["lxd-cloud"] = lxd_cloud
4244 vca
["lxd-credentials"] = lxd_credentials
4245 vca
["k8s-cloud"] = k8s_cloud
4246 vca
["k8s-credentials"] = k8s_credentials
4248 vca
["description"] = description
4250 model_config
= load(model_config
)
4251 vca
["model-config"] = model_config
4252 ctx
.obj
.vca
.create(name
, vca
)
4255 def load(data
: Any
):
4256 if os
.path
.isfile(data
):
4257 return load_file(data
)
4260 return json
.loads(data
)
4261 except ValueError as e
:
4262 raise ClientException(e
)
4265 def load_file(file_path
: str) -> Dict
:
4267 with
open(file_path
, "r") as f
:
4270 return yaml
.safe_load(content
)
4271 except yaml
.scanner
.ScannerError
:
4274 return json
.loads(content
)
4277 raise ClientException(f
"{file_path} must be a valid yaml or json file")
4280 @cli_osm.command(name
="vca-update", short_help
="updates a K8s cluster")
4281 @click.argument("name")
4283 "--endpoints", help="Comma-separated list of IP or hostnames of the Juju controller"
4285 @click.option("--user", help="Username with admin priviledges")
4286 @click.option("--secret", help="Password of the specified username")
4287 @click.option("--cacert", help="CA certificate")
4290 help="Name of the cloud that will be used for LXD containers (LXD proxy charms)",
4293 "--lxd-credentials",
4294 help="Name of the cloud credentialsto be used for the LXD cloud",
4298 help="Name of the cloud that will be used for K8s containers (K8s proxy charms)",
4301 "--k8s-credentials",
4302 help="Name of the cloud credentialsto be used for the K8s cloud",
4306 help="Configuration options for the models",
4308 @click.option("--description", default
=None, help="human readable description")
4324 """updates a K8s cluster
4326 NAME: name or ID of the K8s cluster
4328 check_client_version(ctx
.obj
, ctx
.command
.name
)
4332 vca
["endpoints"] = endpoints
.split(",")
4336 vca
["secret"] = secret
4338 vca
["cacert"] = cacert
4340 vca
["lxd-cloud"] = lxd_cloud
4342 vca
["lxd-credentials"] = lxd_credentials
4344 vca
["k8s-cloud"] = k8s_cloud
4346 vca
["k8s-credentials"] = k8s_credentials
4348 vca
["description"] = description
4350 model_config
= load(model_config
)
4351 vca
["model-config"] = model_config
4352 ctx
.obj
.vca
.update(name
, vca
)
4355 @cli_osm.command(name
="vca-delete", short_help
="deletes a K8s cluster")
4356 @click.argument("name")
4358 "--force", is_flag
=True, help="forces the deletion from the DB (not recommended)"
4361 def vca_delete(ctx
, name
, force
):
4362 """deletes a K8s cluster
4364 NAME: name or ID of the K8s cluster to be deleted
4366 check_client_version(ctx
.obj
, ctx
.command
.name
)
4367 ctx
.obj
.vca
.delete(name
, force
=force
)
4370 @cli_osm.command(name
="vca-list")
4375 help="restricts the list to the VCAs matching the filter",
4377 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
4378 @click.option("--long", is_flag
=True, help="get more details")
4380 def vca_list(ctx
, filter, literal
, long):
4382 check_client_version(ctx
.obj
, ctx
.command
.name
)
4384 filter = "&".join(filter)
4385 resp
= ctx
.obj
.vca
.list(filter)
4387 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
4390 table
= PrettyTable(
4391 ["Name", "Id", "Project", "Operational State", "Detailed Status"]
4393 project_list
= ctx
.obj
.project
.list()
4395 table
= PrettyTable(["Name", "Id", "Operational State"])
4397 logger
.debug("VCA details: {}".format(yaml
.safe_dump(vca
)))
4399 project_id
, project_name
= get_project(project_list
, vca
)
4400 detailed_status
= vca
.get("_admin", {}).get("detailed-status", "-")
4406 vca
.get("_admin", {}).get("operationalState", "-"),
4407 wrap_text(text
=detailed_status
, width
=40),
4415 vca
.get("_admin", {}).get("operationalState", "-"),
4422 @cli_osm.command(name
="vca-show", short_help
="shows the details of a K8s cluster")
4423 @click.argument("name")
4424 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
4426 def vca_show(ctx
, name
, literal
):
4427 """shows the details of a K8s cluster
4429 NAME: name or ID of the K8s cluster
4432 resp
= ctx
.obj
.vca
.get(name
)
4434 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
4436 table
= PrettyTable(["key", "attribute"])
4437 for k
, v
in list(resp
.items()):
4438 table
.add_row([k
, wrap_text(text
=json
.dumps(v
, indent
=2), width
=100)])
4443 ###########################
4445 ###########################
4448 @cli_osm.command(name
="repo-add", short_help
="adds a repo to OSM")
4449 @click.argument("name")
4450 @click.argument("uri")
4453 type=click
.Choice(["helm-chart", "juju-bundle", "osm"]),
4455 help="type of repo (helm-chart for Helm Charts, juju-bundle for Juju Bundles, osm for OSM Repositories)",
4457 @click.option("--description", default
=None, help="human readable description")
4459 "--user", default
=None, help="OSM repository: The username of the OSM repository"
4464 help="OSM repository: The password of the OSM repository",
4466 # @click.option('--wait',
4468 # help='do not return the control immediately, but keep it until the operation is completed, or timeout')
4470 def repo_add(ctx
, **kwargs
):
4471 """adds a repo to OSM
4473 NAME: name of the repo
4474 URI: URI of the repo
4477 kwargs
= {k
: v
for k
, v
in kwargs
.items() if v
is not None}
4479 repo
["url"] = repo
.pop("uri")
4480 if repo
["type"] in ["helm-chart", "juju-bundle"]:
4481 ctx
.obj
.repo
.create(repo
["name"], repo
)
4483 ctx
.obj
.osmrepo
.create(repo
["name"], repo
)
4484 # except ClientException as e:
4489 @cli_osm.command(name
="repo-update", short_help
="updates a repo in OSM")
4490 @click.argument("name")
4491 @click.option("--newname", help="New name for the repo")
4492 @click.option("--uri", help="URI of the repo")
4493 @click.option("--description", help="human readable description")
4494 # @click.option('--wait',
4496 # help='do not return the control immediately, but keep it until the operation is completed, or timeout')
4498 def repo_update(ctx
, name
, newname
, uri
, description
):
4499 """updates a repo in OSM
4501 NAME: name of the repo
4504 check_client_version(ctx
.obj
, ctx
.command
.name
)
4507 repo
["name"] = newname
4511 repo
["description"] = description
4513 ctx
.obj
.repo
.update(name
, repo
)
4515 ctx
.obj
.osmrepo
.update(name
, repo
)
4517 # except ClientException as e:
4523 name
="repo-index", short_help
="Index a repository from a folder with artifacts"
4526 "--origin", default
=".", help="origin path where the artifacts are located"
4529 "--destination", default
=".", help="destination path where the index is deployed"
4532 def repo_index(ctx
, origin
, destination
):
4533 """Index a repository
4535 NAME: name or ID of the repo to be deleted
4537 check_client_version(ctx
.obj
, ctx
.command
.name
)
4538 ctx
.obj
.osmrepo
.repo_index(origin
, destination
)
4541 @cli_osm.command(name
="repo-delete", short_help
="deletes a repo")
4542 @click.argument("name")
4544 "--force", is_flag
=True, help="forces the deletion from the DB (not recommended)"
4546 # @click.option('--wait',
4548 # help='do not return the control immediately, but keep it until the operation is completed, or timeout')
4550 def repo_delete(ctx
, name
, force
):
4553 NAME: name or ID of the repo to be deleted
4557 ctx
.obj
.repo
.delete(name
, force
=force
)
4559 ctx
.obj
.osmrepo
.delete(name
, force
=force
)
4560 # except ClientException as e:
4565 @cli_osm.command(name
="repo-list")
4570 help="restricts the list to the repos matching the filter",
4572 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
4574 def repo_list(ctx
, filter, literal
):
4575 """list all repos"""
4578 check_client_version(ctx
.obj
, ctx
.command
.name
)
4580 filter = "&".join(filter)
4581 resp
= ctx
.obj
.repo
.list(filter)
4582 resp
+= ctx
.obj
.osmrepo
.list(filter)
4584 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
4586 table
= PrettyTable(["Name", "Id", "Type", "URI", "Description"])
4588 # cluster['k8s-nets'] = json.dumps(yaml.safe_load(cluster['k8s-nets']))
4595 trunc_text(repo
.get("description") or "", 40),
4601 # except ClientException as e:
4606 @cli_osm.command(name
="repo-show", short_help
="shows the details of a repo")
4607 @click.argument("name")
4608 @click.option("--literal", is_flag
=True, help="print literally, no pretty table")
4610 def repo_show(ctx
, name
, literal
):
4611 """shows the details of a repo
4613 NAME: name or ID of the repo
4616 resp
= ctx
.obj
.repo
.get(name
)
4618 resp
= ctx
.obj
.osmrepo
.get(name
)
4622 print(yaml
.safe_dump(resp
, indent
=4, default_flow_style
=False))
4624 table
= PrettyTable(["key", "attribute"])
4626 for k
, v
in list(resp
.items()):
4627 table
.add_row([k
, json
.dumps(v
, indent
=2)])
4631 # except ClientException as e:
4636 ####################
4637 # Project mgmt operations
4638 ####################
4641 @cli_osm.command(name
="project-create", short_help
="creates a new project")
4642 @click.argument("name")
4643 # @click.option('--description',
4644 # default='no description',
4645 # help='human readable description')
4646 @click.option("--domain-name", "domain_name", default
=None, help="assign to a domain")
4652 help="provide quotas. Can be used several times: 'quota1=number[,quota2=number,...]'. Quotas can be one "
4653 "of vnfds, nsds, nsts, pdus, nsrs, nsis, vim_accounts, wim_accounts, sdns, k8sclusters, k8srepos",
4656 def project_create(ctx
, name
, domain_name
, quotas
):
4657 """Creates a new project
4659 NAME: name of the project
4660 DOMAIN_NAME: optional domain name for the project when keystone authentication is used
4661 QUOTAS: set quotas for the project
4664 project
= {"name": name
}
4666 project
["domain_name"] = domain_name
4667 quotas_dict
= _process_project_quotas(quotas
)
4669 project
["quotas"] = quotas_dict
4672 check_client_version(ctx
.obj
, ctx
.command
.name
)
4673 ctx
.obj
.project
.create(name
, project
)
4674 # except ClientException as e:
4679 def _process_project_quotas(quota_list
):
4684 for quota
in quota_list
:
4685 for single_quota
in quota
.split(","):
4686 k
, v
= single_quota
.split("=")
4687 quotas_dict
[k
] = None if v
in ("None", "null", "") else int(v
)
4688 except (ValueError, TypeError):
4689 raise ClientException(
4690 "invalid format for 'quotas'. Use 'k1=v1,v1=v2'. v must be a integer or null"
4695 @cli_osm.command(name
="project-delete", short_help
="deletes a project")
4696 @click.argument("name")
4697 # @click.option('--force', is_flag=True, help='forces the deletion bypassing pre-conditions')
4699 def project_delete(ctx
, name
):
4700 """deletes a project
4702 NAME: name or ID of the project to be deleted
4706 check_client_version(ctx
.obj
, ctx
.command
.name
)
4707 ctx
.obj
.project
.delete(name
)
4708 # except ClientException as e:
4713 @cli_osm.command(name
="project-list", short_help
="list all projects")
4718 help="restricts the list to the projects matching the filter",
4721 def project_list(ctx
, filter):
4722 """list all projects"""
4725 check_client_version(ctx
.obj
, ctx
.command
.name
)
4727 filter = "&".join(filter)
4728 resp
= ctx
.obj
.project
.list(filter)
4729 # except ClientException as e:
4732 table
= PrettyTable(["name", "id"])
4734 table
.add_row([proj
["name"], proj
["_id"]])
4739 @cli_osm.command(name
="project-show", short_help
="shows the details of a project")
4740 @click.argument("name")
4742 def project_show(ctx
, name
):
4743 """shows the details of a project
4745 NAME: name or ID of the project
4749 check_client_version(ctx
.obj
, ctx
.command
.name
)
4750 resp
= ctx
.obj
.project
.get(name
)
4751 # except ClientException as e:
4755 table
= PrettyTable(["key", "attribute"])
4756 for k
, v
in resp
.items():
4757 table
.add_row([k
, json
.dumps(v
, indent
=2)])
4763 name
="project-update", short_help
="updates a project (only the name can be updated)"
4765 @click.argument("project")
4766 @click.option("--name", default
=None, help="new name for the project")
4772 help="change quotas. Can be used several times: 'quota1=number|empty[,quota2=...]' "
4773 "(use empty to reset quota to default",
4776 def project_update(ctx
, project
, name
, quotas
):
4778 Update a project name
4781 :param project: id or name of the project to modify
4782 :param name: new name for the project
4783 :param quotas: change quotas of the project
4787 project_changes
= {}
4789 project_changes
["name"] = name
4790 quotas_dict
= _process_project_quotas(quotas
)
4792 project_changes
["quotas"] = quotas_dict
4795 check_client_version(ctx
.obj
, ctx
.command
.name
)
4796 ctx
.obj
.project
.update(project
, project_changes
)
4797 # except ClientException as e:
4801 ####################
4802 # User mgmt operations
4803 ####################
4806 @cli_osm.command(name
="user-create", short_help
="creates a new user")
4807 @click.argument("username")
4812 confirmation_prompt
=True,
4813 help="user password",
4817 # prompt="Comma separate list of projects",
4819 callback
=lambda ctx
, param
, value
: "".join(value
).split(",")
4820 if all(len(x
) == 1 for x
in value
)
4822 help="list of project ids that the user belongs to",
4825 "--project-role-mappings",
4826 "project_role_mappings",
4829 help="assign role(s) in a project. Can be used several times: 'project,role1[,role2,...]'",
4831 @click.option("--domain-name", "domain_name", default
=None, help="assign to a domain")
4833 def user_create(ctx
, username
, password
, projects
, project_role_mappings
, domain_name
):
4834 """Creates a new user
4837 USERNAME: name of the user
4838 PASSWORD: password of the user
4839 PROJECTS: projects assigned to user (internal only)
4840 PROJECT_ROLE_MAPPING: roles in projects assigned to user (keystone)
4841 DOMAIN_NAME: optional domain name for the user when keystone authentication is used
4845 user
["username"] = username
4846 user
["password"] = password
4847 user
["projects"] = projects
4848 user
["project_role_mappings"] = project_role_mappings
4850 user
["domain_name"] = domain_name
4853 check_client_version(ctx
.obj
, ctx
.command
.name
)
4854 ctx
.obj
.user
.create(username
, user
)
4855 # except ClientException as e:
4860 @cli_osm.command(name
="user-update", short_help
="updates user information")
4861 @click.argument("username")
4866 # confirmation_prompt=True,
4867 help="user password",
4869 @click.option("--set-username", "set_username", default
=None, help="change username")
4875 help="create/replace the roles for this project: 'project,role1[,role2,...]'",
4882 help="removes project from user: 'project'",
4885 "--add-project-role",
4889 help="assign role(s) in a project. Can be used several times: 'project,role1[,role2,...]'",
4892 "--remove-project-role",
4893 "remove_project_role",
4896 help="remove role(s) in a project. Can be used several times: 'project,role1[,role2,...]'",
4898 @click.option("--change_password", "change_password", help="user's current password")
4902 help="user's new password to update in expiry condition",
4913 remove_project_role
,
4917 """Update a user information
4920 USERNAME: name of the user
4921 PASSWORD: new password
4922 SET_USERNAME: new username
4923 SET_PROJECT: creating mappings for project/role(s)
4924 REMOVE_PROJECT: deleting mappings for project/role(s)
4925 ADD_PROJECT_ROLE: adding mappings for project/role(s)
4926 REMOVE_PROJECT_ROLE: removing mappings for project/role(s)
4927 CHANGE_PASSWORD: user's current password to change
4928 NEW_PASSWORD: user's new password to update in expiry condition
4932 user
["password"] = password
4933 user
["username"] = set_username
4934 user
["set-project"] = set_project
4935 user
["remove-project"] = remove_project
4936 user
["add-project-role"] = add_project_role
4937 user
["remove-project-role"] = remove_project_role
4938 user
["change_password"] = change_password
4939 user
["new_password"] = new_password
4942 check_client_version(ctx
.obj
, ctx
.command
.name
)
4943 if not user
.get("change_password"):
4944 ctx
.obj
.user
.update(username
, user
)
4946 ctx
.obj
.user
.update(username
, user
, pwd_change
=True)
4947 # except ClientException as e:
4952 @cli_osm.command(name
="user-delete", short_help
="deletes a user")
4953 @click.argument("name")
4954 # @click.option('--force', is_flag=True, help='forces the deletion bypassing pre-conditions')
4956 def user_delete(ctx
, name
):
4960 NAME: name or ID of the user to be deleted
4964 check_client_version(ctx
.obj
, ctx
.command
.name
)
4965 ctx
.obj
.user
.delete(name
)
4966 # except ClientException as e:
4971 @cli_osm.command(name
="user-list", short_help
="list all users")
4976 help="restricts the list to the users matching the filter",
4979 def user_list(ctx
, filter):
4980 """list all users"""
4982 check_client_version(ctx
.obj
, ctx
.command
.name
)
4984 filter = "&".join(filter)
4985 resp
= ctx
.obj
.user
.list(filter)
4986 # except ClientException as e:
4989 table
= PrettyTable(["name", "id"])
4991 table
.add_row([user
["username"], user
["_id"]])
4996 @cli_osm.command(name
="user-show", short_help
="shows the details of a user")
4997 @click.argument("name")
4999 def user_show(ctx
, name
):
5000 """shows the details of a user
5002 NAME: name or ID of the user
5006 check_client_version(ctx
.obj
, ctx
.command
.name
)
5007 resp
= ctx
.obj
.user
.get(name
)
5008 if "password" in resp
:
5009 resp
["password"] = "********"
5010 # except ClientException as e:
5014 table
= PrettyTable(["key", "attribute"])
5015 for k
, v
in resp
.items():
5016 table
.add_row([k
, json
.dumps(v
, indent
=2)])
5021 ####################
5022 # Fault Management operations
5023 ####################
5026 @cli_osm.command(name
="ns-alarm-create")
5027 @click.argument("name")
5028 @click.option("--ns", prompt
=True, help="NS instance id or name")
5030 "--vnf", prompt
=True, help="VNF name (VNF member index as declared in the NSD)"
5032 @click.option("--vdu", prompt
=True, help="VDU name (VDU name as declared in the VNFD)")
5033 @click.option("--metric", prompt
=True, help="Name of the metric (e.g. cpu_utilization)")
5037 help="severity of the alarm (WARNING, MINOR, MAJOR, CRITICAL, INDETERMINATE)",
5040 "--threshold_value",
5042 help="threshold value that, when crossed, an alarm is triggered",
5045 "--threshold_operator",
5047 help="threshold operator describing the comparison (GE, LE, GT, LT, EQ)",
5052 help="statistic (AVERAGE, MINIMUM, MAXIMUM, COUNT, SUM)",
5055 def ns_alarm_create(
5067 """creates a new alarm for a NS instance"""
5068 # TODO: Check how to validate threshold_value.
5069 # Should it be an integer (1-100), percentage, or decimal (0.01-1.00)?
5072 ns_instance
= ctx
.obj
.ns
.get(ns
)
5074 alarm
["alarm_name"] = name
5075 alarm
["ns_id"] = ns_instance
["_id"]
5076 alarm
["correlation_id"] = ns_instance
["_id"]
5077 alarm
["vnf_member_index"] = vnf
5078 alarm
["vdu_name"] = vdu
5079 alarm
["metric_name"] = metric
5080 alarm
["severity"] = severity
5081 alarm
["threshold_value"] = int(threshold_value
)
5082 alarm
["operation"] = threshold_operator
5083 alarm
["statistic"] = statistic
5084 check_client_version(ctx
.obj
, ctx
.command
.name
)
5085 ctx
.obj
.ns
.create_alarm(alarm
)
5086 # except ClientException as e:
5091 # @cli_osm.command(name='ns-alarm-delete')
5092 # @click.argument('name')
5093 # @click.pass_context
5094 # def ns_alarm_delete(ctx, name):
5095 # """deletes an alarm
5097 # NAME: name of the alarm to be deleted
5100 # check_client_version(ctx.obj, ctx.command.name)
5101 # ctx.obj.ns.delete_alarm(name)
5102 # except ClientException as e:
5107 ####################
5108 # Performance Management operations
5109 ####################
5113 name
="ns-metric-export",
5114 short_help
="exports a metric to the internal OSM bus, which can be read by other apps",
5116 @click.option("--ns", prompt
=True, help="NS instance id or name")
5118 "--vnf", prompt
=True, help="VNF name (VNF member index as declared in the NSD)"
5120 @click.option("--vdu", prompt
=True, help="VDU name (VDU name as declared in the VNFD)")
5121 @click.option("--metric", prompt
=True, help="name of the metric (e.g. cpu_utilization)")
5122 # @click.option('--period', default='1w',
5123 # help='metric collection period (e.g. 20s, 30m, 2h, 3d, 1w)')
5125 "--interval", help="periodic interval (seconds) to export metrics continuously"
5128 def ns_metric_export(ctx
, ns
, vnf
, vdu
, metric
, interval
):
5129 """exports a metric to the internal OSM bus, which can be read by other apps"""
5130 # TODO: Check how to validate interval.
5131 # Should it be an integer (seconds), or should a suffix (s,m,h,d,w) also be permitted?
5134 ns_instance
= ctx
.obj
.ns
.get(ns
)
5136 metric_data
["ns_id"] = ns_instance
["_id"]
5137 metric_data
["correlation_id"] = ns_instance
["_id"]
5138 metric_data
["vnf_member_index"] = vnf
5139 metric_data
["vdu_name"] = vdu
5140 metric_data
["metric_name"] = metric
5141 metric_data
["collection_unit"] = "WEEK"
5142 metric_data
["collection_period"] = 1
5143 check_client_version(ctx
.obj
, ctx
.command
.name
)
5145 print("{}".format(ctx
.obj
.ns
.export_metric(metric_data
)))
5149 print("{} {}".format(ctx
.obj
.ns
.export_metric(metric_data
), i
))
5150 time
.sleep(int(interval
))
5152 # except ClientException as e:
5158 # Subscription operations
5163 name
="subscription-create",
5164 short_help
="creates a new subscription to a specific event",
5168 # type=click.Choice(['ns', 'nspkg', 'vnfpkg'], case_sensitive=False))
5169 type=click
.Choice(["ns"], case_sensitive
=False),
5170 help="event type to be subscribed (for the moment, only ns is supported)",
5172 @click.option("--event", default
=None, help="specific yaml configuration for the event")
5174 "--event_file", default
=None, help="specific yaml configuration file for the event"
5177 def subscription_create(ctx
, event_type
, event
, event_file
):
5178 """creates a new subscription to a specific event"""
5180 check_client_version(ctx
.obj
, ctx
.command
.name
)
5183 raise ClientException(
5184 '"--event" option is incompatible with "--event_file" option'
5186 with
open(event_file
, "r") as cf
:
5188 ctx
.obj
.subscription
.create(event_type
, event
)
5191 @cli_osm.command(name
="subscription-delete", short_help
="deletes a subscription")
5194 # type=click.Choice(['ns', 'nspkg', 'vnfpkg'], case_sensitive=False))
5195 type=click
.Choice(["ns"], case_sensitive
=False),
5196 help="event type to be subscribed (for the moment, only ns is supported)",
5198 @click.argument("subscription_id")
5200 "--force", is_flag
=True, help="forces the deletion bypassing pre-conditions"
5203 def subscription_delete(ctx
, event_type
, subscription_id
, force
):
5204 """deletes a subscription
5206 SUBSCRIPTION_ID: ID of the subscription to be deleted
5209 check_client_version(ctx
.obj
, ctx
.command
.name
)
5210 ctx
.obj
.subscription
.delete(event_type
, subscription_id
, force
)
5213 @cli_osm.command(name
="subscription-list", short_help
="list all subscriptions")
5216 # type=click.Choice(['ns', 'nspkg', 'vnfpkg'], case_sensitive=False))
5217 type=click
.Choice(["ns"], case_sensitive
=False),
5218 help="event type to be subscribed (for the moment, only ns is supported)",
5224 help="restricts the list to the subscriptions matching the filter",
5227 def subscription_list(ctx
, event_type
, filter):
5228 """list all subscriptions"""
5230 check_client_version(ctx
.obj
, ctx
.command
.name
)
5232 filter = "&".join(filter)
5233 resp
= ctx
.obj
.subscription
.list(event_type
, filter)
5234 table
= PrettyTable(["id", "filter", "CallbackUri"])
5239 wrap_text(text
=json
.dumps(sub
["filter"], indent
=2), width
=70),
5248 name
="subscription-show", short_help
="shows the details of a subscription"
5250 @click.argument("subscription_id")
5253 # type=click.Choice(['ns', 'nspkg', 'vnfpkg'], case_sensitive=False))
5254 type=click
.Choice(["ns"], case_sensitive
=False),
5255 help="event type to be subscribed (for the moment, only ns is supported)",
5260 help="restricts the information to the fields in the filter",
5263 def subscription_show(ctx
, event_type
, subscription_id
, filter):
5264 """shows the details of a subscription
5266 SUBSCRIPTION_ID: ID of the subscription
5270 resp
= ctx
.obj
.subscription
.get(subscription_id
)
5271 table
= PrettyTable(["key", "attribute"])
5272 for k
, v
in list(resp
.items()):
5273 if not filter or k
in filter:
5274 table
.add_row([k
, wrap_text(text
=json
.dumps(v
, indent
=2), width
=100)])
5279 ####################
5281 ####################
5284 @cli_osm.command(name
="version", short_help
="shows client and server versions")
5286 def get_version(ctx
):
5287 """shows client and server versions"""
5289 check_client_version(ctx
.obj
, "version")
5290 print("Server version: {}".format(ctx
.obj
.get_version()))
5292 "Client version: {}".format(pkg_resources
.get_distribution("osmclient").version
)
5294 # except ClientException as e:
5300 name
="upload-package", short_help
="uploads a VNF package or NS package"
5302 @click.argument("filename")
5304 "--skip-charm-build",
5307 help="the charm will not be compiled, it is assumed to already exist",
5310 def upload_package(ctx
, filename
, skip_charm_build
):
5311 """uploads a vnf package or ns package
5313 filename: vnf or ns package folder, or vnf or ns package file (tar.gz)
5317 ctx
.obj
.package
.upload(filename
, skip_charm_build
=skip_charm_build
)
5318 fullclassname
= ctx
.obj
.__module
__ + "." + ctx
.obj
.__class
__.__name
__
5319 if fullclassname
!= "osmclient.sol005.client.Client":
5320 ctx
.obj
.package
.wait_for_upload(filename
)
5321 # except ClientException as e:
5326 # @cli_osm.command(name='ns-scaling-show')
5327 # @click.argument('ns_name')
5328 # @click.pass_context
5329 # def show_ns_scaling(ctx, ns_name):
5330 # """shows the status of a NS scaling operation
5332 # NS_NAME: name of the NS instance being scaled
5335 # check_client_version(ctx.obj, ctx.command.name, 'v1')
5336 # resp = ctx.obj.ns.list()
5337 # except ClientException as e:
5341 # table = PrettyTable(
5344 # 'operational status',
5349 # if ns_name == ns['name']:
5350 # nsopdata = ctx.obj.ns.get_opdata(ns['id'])
5351 # scaling_records = nsopdata['nsr:nsr']['scaling-group-record']
5352 # for record in scaling_records:
5353 # if 'instance' in record:
5354 # instances = record['instance']
5355 # for inst in instances:
5357 # [record['scaling-group-name-ref'],
5358 # inst['instance-id'],
5359 # inst['op-status'],
5360 # time.strftime('%Y-%m-%d %H:%M:%S',
5362 # inst['create-time'])),
5368 # @cli_osm.command(name='ns-scale')
5369 # @click.argument('ns_name')
5370 # @click.option('--ns_scale_group', prompt=True)
5371 # @click.option('--index', prompt=True)
5372 # @click.option('--wait',
5376 # help='do not return the control immediately, but keep it \
5377 # until the operation is completed, or timeout')
5378 # @click.pass_context
5379 # def ns_scale(ctx, ns_name, ns_scale_group, index, wait):
5382 # NS_NAME: name of the NS instance to be scaled
5385 # check_client_version(ctx.obj, ctx.command.name, 'v1')
5386 # ctx.obj.ns.scale(ns_name, ns_scale_group, index, wait=wait)
5387 # except ClientException as e:
5392 # @cli_osm.command(name='config-agent-list')
5393 # @click.pass_context
5394 # def config_agent_list(ctx):
5395 # """list config agents"""
5397 # check_client_version(ctx.obj, ctx.command.name, 'v1')
5398 # except ClientException as e:
5401 # table = PrettyTable(['name', 'account-type', 'details'])
5402 # for account in ctx.obj.vca.list():
5405 # account['account-type'],
5411 # @cli_osm.command(name='config-agent-delete')
5412 # @click.argument('name')
5413 # @click.pass_context
5414 # def config_agent_delete(ctx, name):
5415 # """deletes a config agent
5417 # NAME: name of the config agent to be deleted
5420 # check_client_version(ctx.obj, ctx.command.name, 'v1')
5421 # ctx.obj.vca.delete(name)
5422 # except ClientException as e:
5427 # @cli_osm.command(name='config-agent-add')
5428 # @click.option('--name',
5430 # @click.option('--account_type',
5432 # @click.option('--server',
5434 # @click.option('--user',
5436 # @click.option('--secret',
5439 # confirmation_prompt=True)
5440 # @click.pass_context
5441 # def config_agent_add(ctx, name, account_type, server, user, secret):
5442 # """adds a config agent"""
5444 # check_client_version(ctx.obj, ctx.command.name, 'v1')
5445 # ctx.obj.vca.create(name, account_type, server, user, secret)
5446 # except ClientException as e:
5451 # @cli_osm.command(name='ro-dump')
5452 # @click.pass_context
5454 # """shows RO agent information"""
5455 # check_client_version(ctx.obj, ctx.command.name, 'v1')
5456 # resp = ctx.obj.vim.get_resource_orchestrator()
5457 # table = PrettyTable(['key', 'attribute'])
5458 # for k, v in list(resp.items()):
5459 # table.add_row([k, json.dumps(v, indent=2)])
5464 # @cli_osm.command(name='vcs-list')
5465 # @click.pass_context
5466 # def vcs_list(ctx):
5467 # check_client_version(ctx.obj, ctx.command.name, 'v1')
5468 # resp = ctx.obj.utils.get_vcs_info()
5469 # table = PrettyTable(['component name', 'state'])
5470 # for component in resp:
5471 # table.add_row([component['component_name'], component['state']])
5477 name
="ns-action", short_help
="executes an action/primitive over a NS instance"
5479 @click.argument("ns_name")
5483 help="member-vnf-index if the target is a vnf instead of a ns)",
5485 @click.option("--kdu_name", default
=None, help="kdu-name if the target is a kdu)")
5486 @click.option("--vdu_id", default
=None, help="vdu-id if the target is a vdu")
5488 "--vdu_count", default
=None, type=int, help="number of vdu instance of this vdu_id"
5490 @click.option("--action_name", prompt
=True, help="action name")
5491 @click.option("--params", default
=None, help="action params in YAML/JSON inline string")
5492 @click.option("--params_file", default
=None, help="YAML/JSON file with action params")
5494 "--timeout", required
=False, default
=None, type=int, help="timeout in seconds"
5501 help="do not return the control immediately, but keep it until the operation is completed, or timeout",
5517 """executes an action/primitive over a NS instance
5519 NS_NAME: name or ID of the NS instance
5523 check_client_version(ctx
.obj
, ctx
.command
.name
)
5526 op_data
["member_vnf_index"] = vnf_name
5528 op_data
["kdu_name"] = kdu_name
5530 op_data
["vdu_id"] = vdu_id
5531 if vdu_count
is not None:
5532 op_data
["vdu_count_index"] = vdu_count
5534 op_data
["timeout_ns_action"] = timeout
5535 op_data
["primitive"] = action_name
5537 with
open(params_file
, "r") as pf
:
5540 op_data
["primitive_params"] = yaml
.safe_load(params
)
5542 op_data
["primitive_params"] = {}
5543 print(ctx
.obj
.ns
.exec_op(ns_name
, op_name
="action", op_data
=op_data
, wait
=wait
))
5545 # except ClientException as e:
5551 name
="vnf-scale", short_help
="executes a VNF scale (adding/removing VDUs)"
5553 @click.argument("ns_name")
5554 @click.argument("vnf_name")
5556 "--scaling-group", prompt
=True, help="scaling-group-descriptor name to use"
5559 "--scale-in", default
=False, is_flag
=True, help="performs a scale in operation"
5565 help="performs a scale out operation (by default)",
5568 "--timeout", required
=False, default
=None, type=int, help="timeout in seconds"
5575 help="do not return the control immediately, but keep it until the operation is completed, or timeout",
5579 ctx
, ns_name
, vnf_name
, scaling_group
, scale_in
, scale_out
, timeout
, wait
5582 Executes a VNF scale (adding/removing VDUs)
5585 NS_NAME: name or ID of the NS instance.
5586 VNF_NAME: member-vnf-index in the NS to be scaled.
5590 check_client_version(ctx
.obj
, ctx
.command
.name
)
5591 if not scale_in
and not scale_out
:
5593 ctx
.obj
.ns
.scale_vnf(
5594 ns_name
, vnf_name
, scaling_group
, scale_in
, scale_out
, wait
, timeout
5596 # except ClientException as e:
5602 name
="ns-update", short_help
="executes an update of a Network Service."
5604 @click.argument("ns_name")
5606 "--updatetype", required
=True, type=str, help="available types: CHANGE_VNFPKG"
5612 help="extra information for update operation as YAML/JSON inline string as --config"
5613 " '{changeVnfPackageData:[{vnfInstanceId: xxx, vnfdId: yyy}]}'",
5616 "--timeout", required
=False, default
=None, type=int, help="timeout in seconds"
5623 help="do not return the control immediately, but keep it until the operation is completed, or timeout",
5626 def update(ctx
, ns_name
, updatetype
, config
, timeout
, wait
):
5627 """Executes an update of a Network Service.
5629 The update will check new revisions of the Network Functions that are part of the
5630 Network Service, and it will update them if needed.
5631 Sample update command: osm ns-update ns_instance_id --updatetype CHANGE_VNFPKG
5632 --config '{changeVnfPackageData: [{vnfInstanceId: id_x,vnfdId: id_y}]}' --timeout 300 --wait
5634 NS_NAME: Network service instance name or ID.
5639 "updateType": updatetype
,
5642 op_data
["config"] = yaml
.safe_load(config
)
5644 check_client_version(ctx
.obj
, ctx
.command
.name
)
5645 ctx
.obj
.ns
.update(ns_name
, op_data
, wait
=wait
)
5648 def iterator_split(iterator
, separators
):
5650 Splits a tuple or list into several lists whenever a separator is found
5651 For instance, the following tuple will be separated with the separator "--vnf" as follows.
5653 ("--vnf", "A", "--cause", "cause_A", "--vdu", "vdu_A1", "--vnf", "B", "--cause", "cause_B", ...
5654 "--vdu", "vdu_B1", "--count_index", "1", "--run-day1", "--vdu", "vdu_B1", "--count_index", "2")
5657 ("--vnf", "A", "--cause", "cause_A", "--vdu", "vdu_A1"),
5658 ("--vnf", "B", "--cause", "cause_B", "--vdu", "vdu_B1", "--count_index", "1", "--run-day1", ...
5659 "--vdu", "vdu_B1", "--count_index", "2")
5662 Returns as many lists as separators are found
5665 if iterator
[0] not in separators
:
5666 raise ClientException(f
"Expected one of {separators}. Received: {iterator[0]}.")
5669 for i
in range(len(iterator
)):
5670 if iterator
[i
] in separators
:
5674 raise ClientException(
5675 f
"Expected at least one argument after separator (possible separators: {separators})."
5677 list_of_lists
.append(list(iterator
[first
:i
]))
5679 if (len(iterator
) - first
) < 2:
5680 raise ClientException(
5681 f
"Expected at least one argument after separator (possible separators: {separators})."
5684 list_of_lists
.append(list(iterator
[first
: len(iterator
)]))
5685 # logger.debug(f"List of lists: {list_of_lists}")
5686 return list_of_lists
5689 def process_common_heal_params(heal_vnf_dict
, args
):
5691 current_item
= "vnf"
5693 while i
< len(args
):
5694 if args
[i
] == "--cause":
5695 if (i
+ 1 >= len(args
)) or args
[i
+ 1].startswith("--"):
5696 raise ClientException("No cause was provided after --cause")
5697 heal_vnf_dict
["cause"] = args
[i
+ 1]
5700 if args
[i
] == "--run-day1":
5701 if current_item
== "vnf":
5702 if "additionalParams" not in heal_vnf_dict
:
5703 heal_vnf_dict
["additionalParams"] = {}
5704 heal_vnf_dict
["additionalParams"]["run-day1"] = True
5706 # if current_item == "vdu"
5707 heal_vnf_dict
["additionalParams"]["vdu"][-1]["run-day1"] = True
5710 if args
[i
] == "--vdu":
5711 if "additionalParams" not in heal_vnf_dict
:
5712 heal_vnf_dict
["additionalParams"] = {}
5713 heal_vnf_dict
["additionalParams"]["vdu"] = []
5714 if (i
+ 1 >= len(args
)) or args
[i
+ 1].startswith("--"):
5715 raise ClientException("No VDU ID was provided after --vdu")
5716 heal_vnf_dict
["additionalParams"]["vdu"].append({"vdu-id": args
[i
+ 1]})
5717 current_item
= "vdu"
5720 if args
[i
] == "--count-index":
5721 if current_item
== "vnf":
5722 raise ClientException(
5723 "Option --count-index only applies to VDU, not to VNF"
5725 if (i
+ 1 >= len(args
)) or args
[i
+ 1].startswith("--"):
5726 raise ClientException("No count index was provided after --count-index")
5727 heal_vnf_dict
["additionalParams"]["vdu"][-1]["count-index"] = int(
5736 def process_ns_heal_params(ctx
, param
, value
):
5738 Processes the params in the command ns-heal
5739 Click does not allow advanced patterns for positional options like this:
5740 --vnf volumes_vnf --cause "Heal several_volumes-VM of several_volumes_vnf"
5741 --vdu several_volumes-VM
5742 --vnf charm_vnf --cause "Heal two VMs of native_manual_scale_charm_vnf"
5743 --vdu mgmtVM --count-index 1 --run-day1
5744 --vdu mgmtVM --count-index 2
5746 It returns the dictionary with all the params stored in ctx.params["heal_params"]
5749 # logger.debug(f"Args: {value}")
5750 if param
.name
!= "args":
5751 raise ClientException(f
"Unexpected param: {param.name}")
5752 # Split the tuple "value" by "--vnf"
5753 vnfs
= iterator_split(value
, ["--vnf"])
5754 logger
.debug(f
"VNFs: {vnfs}")
5756 heal_dict
["healVnfData"] = []
5758 # logger.debug(f"VNF: {vnf}")
5760 if vnf
[1].startswith("--"):
5761 raise ClientException("Expected a VNF_ID after --vnf")
5762 heal_vnf
["vnfInstanceId"] = vnf
[1]
5763 process_common_heal_params(heal_vnf
, vnf
[2:])
5764 heal_dict
["healVnfData"].append(heal_vnf
)
5765 ctx
.params
["heal_params"] = heal_dict
5771 short_help
="heals (recreates) VNFs or VDUs of a NS instance",
5772 context_settings
=dict(
5773 ignore_unknown_options
=True,
5776 @click.argument("ns_name")
5780 type=click
.UNPROCESSED
,
5781 callback
=process_ns_heal_params
,
5783 @click.option("--timeout", type=int, default
=None, help="timeout in seconds")
5788 help="do not return the control immediately, but keep it until the operation is completed, or timeout",
5791 def ns_heal(ctx
, ns_name
, args
, heal_params
, timeout
, wait
):
5792 """heals (recreates) VNFs or VDUs of a NS instance
5794 NS_NAME: name or ID of the NS instance
5798 --vnf TEXT VNF instance ID or VNF id in the NS [required]
5799 --cause TEXT human readable cause of the healing
5800 --run-day1 indicates whether or not to run day1 primitives for the VNF/VDU
5802 --count-index INTEGER count-index
5806 osm ns-heal NS_NAME|NS_ID --vnf volumes_vnf --cause "Heal several_volumes-VM of several_volumes_vnf"
5807 --vdu several_volumes-VM
5808 --vnf charm_vnf --cause "Heal two VMs of native_manual_scale_charm_vnf"
5809 --vdu mgmtVM --count-index 1 --run-day1
5810 --vdu mgmtVM --count-index 2
5813 heal_dict
= ctx
.params
["heal_params"]
5814 logger
.debug(f
"Heal dict:\n{yaml.safe_dump(heal_dict)}")
5815 # replace VNF id in the NS by the VNF instance ID
5816 for vnf
in heal_dict
["healVnfData"]:
5817 vnf_id
= vnf
["vnfInstanceId"]
5818 if not validate_uuid4(vnf_id
):
5819 vnf_filter
= f
"member-vnf-index-ref={vnf_id}"
5820 vnf_list
= ctx
.obj
.vnf
.list(ns
=ns_name
, filter=vnf_filter
)
5821 if len(vnf_list
) == 0:
5822 raise ClientException(
5823 f
"No VNF found in NS {ns_name} with filter {vnf_filter}"
5825 elif len(vnf_list
) == 1:
5826 vnf
["vnfInstanceId"] = vnf_list
[0]["_id"]
5828 raise ClientException(
5829 f
"More than 1 VNF found in NS {ns_name} with filter {vnf_filter}"
5831 logger
.debug(f
"Heal dict:\n{yaml.safe_dump(heal_dict)}")
5832 check_client_version(ctx
.obj
, ctx
.command
.name
)
5833 ctx
.obj
.ns
.heal(ns_name
, heal_dict
, wait
, timeout
)
5837 def process_vnf_heal_params(ctx
, param
, value
):
5839 Processes the params in the command vnf-heal
5840 Click does not allow advanced patterns for positional options like this:
5841 --vdu mgmtVM --count-index 1 --run-day1 --vdu mgmtVM --count-index 2
5843 It returns the dictionary with all the params stored in ctx.params["heal_params"]
5846 # logger.debug(f"Args: {value}")
5847 if param
.name
!= "args":
5848 raise ClientException(f
"Unexpected param: {param.name}")
5849 # Split the tuple "value" by "--vnf"
5852 heal_dict
["healVnfData"] = []
5853 logger
.debug(f
"VNF: {vnf}")
5854 heal_vnf
= {"vnfInstanceId": "id_to_be_substituted"}
5855 process_common_heal_params(heal_vnf
, vnf
)
5856 heal_dict
["healVnfData"].append(heal_vnf
)
5857 ctx
.params
["heal_params"] = heal_dict
5863 short_help
="heals (recreates) a VNF instance or the VDUs of a VNF instance",
5864 context_settings
=dict(
5865 ignore_unknown_options
=True,
5868 @click.argument("vnf_name")
5872 type=click
.UNPROCESSED
,
5873 callback
=process_vnf_heal_params
,
5875 @click.option("--timeout", type=int, default
=None, help="timeout in seconds")
5880 help="do not return the control immediately, but keep it until the operation is completed, or timeout",
5891 """heals (recreates) a VNF instance or the VDUs of a VNF instance
5893 VNF_NAME: name or ID of the VNF instance
5897 --cause TEXT human readable cause of the healing of the VNF
5898 --run-day1 indicates whether or not to run day1 primitives for the VNF/VDU
5900 --count-index INTEGER count-index
5904 osm vnf-heal VNF_INSTANCE_ID --vdu mgmtVM --count-index 1 --run-day1
5905 --vdu mgmtVM --count-index 2
5908 heal_dict
= ctx
.params
["heal_params"]
5909 heal_dict
["healVnfData"][-1]["vnfInstanceId"] = vnf_name
5910 logger
.debug(f
"Heal dict:\n{yaml.safe_dump(heal_dict)}")
5911 check_client_version(ctx
.obj
, ctx
.command
.name
)
5912 vnfr
= ctx
.obj
.vnf
.get(vnf_name
)
5913 ns_id
= vnfr
["nsr-id-ref"]
5914 ctx
.obj
.ns
.heal(ns_id
, heal_dict
, wait
, timeout
)
5918 @cli_osm.command(name
="alarm-show", short_help
="show alarm details")
5919 @click.argument("uuid")
5921 def alarm_show(ctx
, uuid
):
5922 """Show alarm's detail information"""
5924 check_client_version(ctx
.obj
, ctx
.command
.name
)
5925 resp
= ctx
.obj
.ns
.get_alarm(uuid
=uuid
)
5939 table
= PrettyTable(["key", "attribute"])
5941 # Arrange and return the response data
5942 alarm
= resp
.replace("ObjectId", "")
5943 for key
in alarm_filter
:
5945 value
= alarm
.get(key
)
5948 value
= alarm
.get(key
)
5950 elif key
== "ns-id":
5951 value
= alarm
["tags"].get("ns_id")
5952 elif key
== "vdu_name":
5953 value
= alarm
["tags"].get("vdu_name")
5954 elif key
== "status":
5955 value
= alarm
["alarm_status"]
5958 table
.add_row([key
, wrap_text(text
=json
.dumps(value
, indent
=2), width
=100)])
5966 @cli_osm.command(name
="alarm-list", short_help
="list all alarms")
5968 "--ns_id", default
=None, required
=False, help="List out alarm for given ns id"
5971 def alarm_list(ctx
, ns_id
):
5972 """list all alarm"""
5974 check_client_version(ctx
.obj
, ctx
.command
.name
)
5975 project_name
= os
.getenv("OSM_PROJECT", "admin")
5976 resp
= ctx
.obj
.ns
.get_alarm(project_name
=project_name
, ns_id
=ns_id
)
5978 table
= PrettyTable(
5979 ["alarm-id", "metric", "threshold", "operation", "action", "status"]
5982 # return the response data in a table
5983 resp
= resp
.replace("ObjectId", "")
5987 wrap_text(text
=str(alarm
["uuid"]), width
=38),
5991 wrap_text(text
=alarm
["action"], width
=25),
5992 alarm
["alarm_status"],
6000 @cli_osm.command(name
="alarm-update", short_help
="Update a alarm")
6001 @click.argument("uuid")
6002 @click.option("--threshold", default
=None, help="Alarm threshold")
6003 @click.option("--is_enable", default
=None, type=bool, help="enable or disable alarm")
6005 def alarm_update(ctx
, uuid
, threshold
, is_enable
):
6010 if not threshold
and is_enable
is None:
6011 raise ClientException(
6012 "Please provide option to update i.e threshold or is_enable"
6014 ctx
.obj
.ns
.update_alarm(uuid
, threshold
, is_enable
)
6017 ##############################
6018 # Role Management Operations #
6019 ##############################
6022 @cli_osm.command(name
="role-create", short_help
="creates a new role")
6023 @click.argument("name")
6024 @click.option("--permissions", default
=None, help="role permissions using a dictionary")
6026 def role_create(ctx
, name
, permissions
):
6031 NAME: Name or ID of the role.
6032 DEFINITION: Definition of grant/denial of access to resources.
6036 check_client_version(ctx
.obj
, ctx
.command
.name
)
6037 ctx
.obj
.role
.create(name
, permissions
)
6038 # except ClientException as e:
6043 @cli_osm.command(name
="role-update", short_help
="updates a role")
6044 @click.argument("name")
6045 @click.option("--set-name", default
=None, help="change name of rle")
6046 # @click.option('--permissions',
6048 # help='provide a yaml format dictionary with incremental changes. Values can be bool or None to delete')
6052 help="yaml format dictionary with permission: True/False to access grant/denial",
6054 @click.option("--remove", default
=None, help="yaml format list to remove a permission")
6056 def role_update(ctx
, name
, set_name
, add
, remove
):
6061 NAME: Name or ID of the role.
6062 DEFINITION: Definition overwrites the old definition.
6063 ADD: Grant/denial of access to resource to add.
6064 REMOVE: Grant/denial of access to resource to remove.
6068 check_client_version(ctx
.obj
, ctx
.command
.name
)
6069 ctx
.obj
.role
.update(name
, set_name
, None, add
, remove
)
6070 # except ClientException as e:
6075 @cli_osm.command(name
="role-delete", short_help
="deletes a role")
6076 @click.argument("name")
6077 # @click.option('--force', is_flag=True, help='forces the deletion bypassing pre-conditions')
6079 def role_delete(ctx
, name
):
6084 NAME: Name or ID of the role.
6088 check_client_version(ctx
.obj
, ctx
.command
.name
)
6089 ctx
.obj
.role
.delete(name
)
6090 # except ClientException as e:
6095 @cli_osm.command(name
="role-list", short_help
="list all roles")
6100 help="restricts the list to the projects matching the filter",
6103 def role_list(ctx
, filter):
6109 check_client_version(ctx
.obj
, ctx
.command
.name
)
6111 filter = "&".join(filter)
6112 resp
= ctx
.obj
.role
.list(filter)
6113 # except ClientException as e:
6116 table
= PrettyTable(["name", "id"])
6118 table
.add_row([role
["name"], role
["_id"]])
6123 @cli_osm.command(name
="role-show", short_help
="show specific role")
6124 @click.argument("name")
6126 def role_show(ctx
, name
):
6128 Shows the details of a role.
6131 NAME: Name or ID of the role.
6135 check_client_version(ctx
.obj
, ctx
.command
.name
)
6136 resp
= ctx
.obj
.role
.get(name
)
6137 # except ClientException as e:
6141 table
= PrettyTable(["key", "attribute"])
6142 for k
, v
in resp
.items():
6143 table
.add_row([k
, json
.dumps(v
, indent
=2)])
6148 @cli_osm.command(name
="package-create", short_help
="Create empty NS package structure")
6149 @click.argument("package-type")
6150 @click.argument("package-name")
6154 help=('(NS/VNF/NST) Set the location for package creation. Default: "."'),
6158 default
="image-name",
6159 help='(VNF) Set the name of the vdu image. Default "image-name"',
6162 "--vdus", default
=1, help="(VNF) Set the number of vdus in a VNF. Default 1"
6165 "--vcpu", default
=1, help="(VNF) Set the number of virtual CPUs in a vdu. Default 1"
6170 help="(VNF) Set the memory size (MB) of the vdu. Default 1024",
6173 "--storage", default
=10, help="(VNF) Set the disk size (GB) of the vdu. Default 10"
6178 help="(VNF) Set the number of additional interfaces apart from the management interface. Default 0",
6181 "--vendor", default
="OSM", help='(NS/VNF) Set the descriptor vendor. Default "OSM"'
6187 help="(NS/VNF/NST) Flag for overriding the package if exists.",
6193 help="(NS/VNF/NST) Flag for generating descriptor .yaml with all possible commented options",
6196 "--netslice-subnets", default
=1, help="(NST) Number of netslice subnets. Default 1"
6199 "--netslice-vlds", default
=1, help="(NST) Number of netslice vlds. Default 1"
6205 help="Flag to create a descriptor using the previous OSM format (pre SOL006, OSM<9)",
6227 Creates an OSM NS, VNF, NST package
6230 PACKAGE_TYPE: Package to be created: NS, VNF or NST.
6231 PACKAGE_NAME: Name of the package to create the folder with the content.
6236 check_client_version(ctx
.obj
, ctx
.command
.name
)
6238 "Creating the {} structure: {}/{}".format(
6239 package_type
.upper(), base_directory
, package_name
6242 resp
= ctx
.obj
.package_tool
.create(
6252 interfaces
=interfaces
,
6255 netslice_subnets
=netslice_subnets
,
6256 netslice_vlds
=netslice_vlds
,
6260 # except ClientException as inst:
6261 # print("ERROR: {}".format(inst))
6266 name
="package-validate", short_help
="Validate descriptors given a base directory"
6268 @click.argument("base-directory", default
=".", required
=False)
6270 "--recursive/--no-recursive",
6272 help="The activated recursive option will validate the yaml files"
6273 " within the indicated directory and in its subdirectories",
6279 help="Validates also the descriptors using the previous OSM format (pre SOL006)",
6282 def package_validate(ctx
, base_directory
, recursive
, old
):
6284 Validate descriptors given a base directory.
6287 BASE_DIRECTORY: Base folder for NS, VNF or NST package.
6291 check_client_version(ctx
.obj
, ctx
.command
.name
)
6292 results
= ctx
.obj
.package_tool
.validate(base_directory
, recursive
, old
)
6293 table
= PrettyTable()
6294 table
.field_names
= ["TYPE", "PATH", "VALID", "ERROR"]
6295 # Print the dictionary generated by the validation function
6296 for result
in results
:
6298 [result
["type"], result
["path"], result
["valid"], result
["error"]]
6300 table
.sortby
= "VALID"
6301 table
.align
["PATH"] = "l"
6302 table
.align
["TYPE"] = "l"
6303 table
.align
["ERROR"] = "l"
6305 # except ClientException as inst:
6306 # print("ERROR: {}".format(inst))
6311 name
="package-translate", short_help
="Translate descriptors given a base directory"
6313 @click.argument("base-directory", default
=".", required
=False)
6315 "--recursive/--no-recursive",
6317 help="The activated recursive option will translate the yaml files"
6318 " within the indicated directory and in its subdirectories",
6324 help="Do not translate yet, only make a dry-run to test translation",
6327 def package_translate(ctx
, base_directory
, recursive
, dryrun
):
6329 Translate descriptors given a base directory.
6332 BASE_DIRECTORY: Stub folder for NS, VNF or NST package.
6335 check_client_version(ctx
.obj
, ctx
.command
.name
)
6336 results
= ctx
.obj
.package_tool
.translate(base_directory
, recursive
, dryrun
)
6337 table
= PrettyTable()
6338 table
.field_names
= [
6346 # Print the dictionary generated by the validation function
6347 for result
in results
:
6350 result
["current type"],
6354 result
["translated"],
6358 table
.sortby
= "TRANSLATED"
6359 table
.align
["PATH"] = "l"
6360 table
.align
["TYPE"] = "l"
6361 table
.align
["ERROR"] = "l"
6363 # except ClientException as inst:
6364 # print("ERROR: {}".format(inst))
6368 @cli_osm.command(name
="package-build", short_help
="Build the tar.gz of the package")
6369 @click.argument("package-folder")
6371 "--skip-validation", default
=False, is_flag
=True, help="skip package validation"
6374 "--skip-charm-build",
6377 help="the charm will not be compiled, it is assumed to already exist",
6380 def package_build(ctx
, package_folder
, skip_validation
, skip_charm_build
):
6382 Build the package NS, VNF given the package_folder.
6385 PACKAGE_FOLDER: Folder of the NS, VNF or NST to be packaged
6389 check_client_version(ctx
.obj
, ctx
.command
.name
)
6390 results
= ctx
.obj
.package_tool
.build(
6392 skip_validation
=skip_validation
,
6393 skip_charm_build
=skip_charm_build
,
6396 # except ClientException as inst:
6397 # print("ERROR: {}".format(inst))
6402 name
="descriptor-translate",
6403 short_help
="Translate input descriptor file from Rel EIGHT OSM descriptors to SOL006 and prints in standard output",
6405 @click.argument("descriptor-file", required
=True)
6407 def descriptor_translate(ctx
, descriptor_file
):
6409 Translate input descriptor.
6412 DESCRIPTOR_FILE: Descriptor file for NS, VNF or Network Slice.
6415 check_client_version(ctx
.obj
, ctx
.command
.name
)
6416 result
= ctx
.obj
.package_tool
.descriptor_translate(descriptor_file
)
6422 cli_osm() # pylint: disable=no-value-for-parameter
6424 except pycurl
.error
as exc
:
6427 'Maybe "--hostname" option or OSM_HOSTNAME environment variable needs to be specified'
6429 except ClientException
as exc
:
6430 print("ERROR: {}".format(exc
))
6431 except (FileNotFoundError
, PermissionError
) as exc
:
6432 print("Cannot open file: {}".format(exc
))
6433 except yaml
.YAMLError
as exc
:
6434 print("Invalid YAML format: {}".format(exc
))
6436 # TODO capture other controlled exceptions here
6437 # TODO remove the ClientException captures from all places, unless they do something different
6440 if __name__
== "__main__":