Remove unnecessary references to fullclassname after removal of v1 client
[osm/osmclient.git] / osmclient / cli_commands / vnf.py
1 # Copyright ETSI Contributors and Others.
2 # All Rights Reserved.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 import click
17 from osmclient.common.exceptions import ClientException
18 from osmclient.common import print_output
19 from osmclient.cli_commands import utils
20 from prettytable import PrettyTable
21 import yaml
22 import json
23 import time
24 from datetime import datetime
25 import logging
26
27 logger = logging.getLogger("osmclient")
28
29
30 def vnf_list(ctx, ns, filter, long, output):
31 logger.debug("")
32 if ns or filter:
33 if ns:
34 utils.check_client_version(ctx.obj, "--ns")
35 if filter:
36 filter = "&".join(filter)
37 utils.check_client_version(ctx.obj, "--filter")
38 resp = ctx.obj.vnf.list(ns, filter)
39 else:
40 resp = ctx.obj.vnf.list()
41 field_names = [
42 "vnf id",
43 "name",
44 "ns id",
45 "vnf member index",
46 "vnfd name",
47 "vim account id",
48 "ip address",
49 ]
50 if long:
51 field_names = [
52 "vnf id",
53 "name",
54 "ns id",
55 "vnf member index",
56 "vnfd name",
57 "vim account id",
58 "ip address",
59 "date",
60 "last update",
61 ]
62 table = PrettyTable(field_names)
63 for vnfr in resp:
64 name = vnfr["name"] if "name" in vnfr else "-"
65 new_row = [
66 vnfr["_id"],
67 name,
68 vnfr["nsr-id-ref"],
69 vnfr["member-vnf-index-ref"],
70 vnfr["vnfd-ref"],
71 vnfr["vim-account-id"],
72 vnfr["ip-address"],
73 ]
74 if long:
75 date = datetime.fromtimestamp(vnfr["_admin"]["created"]).strftime(
76 "%Y-%m-%dT%H:%M:%S"
77 )
78 last_update = datetime.fromtimestamp(vnfr["_admin"]["modified"]).strftime(
79 "%Y-%m-%dT%H:%M:%S"
80 )
81 new_row.extend([date, last_update])
82 table.add_row(new_row)
83 print_output.print_output(output, table.field_names, table._rows)
84
85
86 @click.command(name="vnf-list", short_help="list all NF instances")
87 @click.option(
88 "--ns", default=None, help="NS instance id or name to restrict the NF list"
89 )
90 @click.option(
91 "--filter",
92 default=None,
93 multiple=True,
94 help="restricts the list to the NF instances matching the filter.",
95 )
96 @click.option("--long", is_flag=True, help="get more details")
97 @print_output.output_option
98 @click.pass_context
99 def vnf_list1(ctx, ns, filter, long, output):
100 """list all NF instances"""
101 logger.debug("")
102 vnf_list(ctx, ns, filter, long, output)
103
104
105 @click.command(name="nf-list", short_help="list all NF instances")
106 @click.option(
107 "--ns", default=None, help="NS instance id or name to restrict the NF list"
108 )
109 @click.option(
110 "--filter",
111 default=None,
112 multiple=True,
113 help="restricts the list to the NF instances matching the filter.",
114 )
115 @click.option("--long", is_flag=True, help="get more details")
116 @print_output.output_option
117 @click.pass_context
118 def nf_list(ctx, ns, filter, long, output):
119 """list all NF instances
120
121 \b
122 Options:
123 --ns TEXT NS instance id or name to restrict the VNF list
124 --filter filterExpr Restricts the list to the VNF instances matching the filter
125
126 \b
127 filterExpr consists of one or more strings formatted according to "simpleFilterExpr",
128 concatenated using the "&" character:
129
130 \b
131 filterExpr := <simpleFilterExpr>["&"<simpleFilterExpr>]*
132 simpleFilterExpr := <attrName>["."<attrName>]*["."<op>]"="<value>[","<value>]*
133 op := "eq" | "neq" | "gt" | "lt" | "gte" | "lte" | "cont" | "ncont"
134 attrName := string
135 value := scalar value
136
137 \b
138 where:
139 * zero or more occurrences
140 ? zero or one occurrence
141 [] grouping of expressions to be used with ? and *
142 "" quotation marks for marking string constants
143 <> name separator
144
145 \b
146 "AttrName" is the name of one attribute in the data type that defines the representation
147 of the resource. The dot (".") character in "simpleFilterExpr" allows concatenation of
148 <attrName> entries to filter by attributes deeper in the hierarchy of a structured document.
149 "Op" stands for the comparison operator. If the expression has concatenated <attrName>
150 entries, it means that the operator "op" is applied to the attribute addressed by the last
151 <attrName> entry included in the concatenation. All simple filter expressions are combined
152 by the "AND" logical operator. In a concatenation of <attrName> entries in a <simpleFilterExpr>,
153 the rightmost "attrName" entry in a "simpleFilterExpr" is called "leaf attribute". The
154 concatenation of all "attrName" entries except the leaf attribute is called the "attribute
155 prefix". If an attribute referenced in an expression is an array, an object that contains a
156 corresponding array shall be considered to match the expression if any of the elements in the
157 array matches all expressions that have the same attribute prefix.
158
159 \b
160 Filter examples:
161 --filter vim-account-id=<VIM_ACCOUNT_ID>
162 --filter vnfd-ref=<VNFD_NAME>
163 --filter vdur.ip-address=<IP_ADDRESS>
164 --filter vnfd-ref=<VNFD_NAME>,vdur.ip-address=<IP_ADDRESS>
165 """
166 logger.debug("")
167 vnf_list(ctx, ns, filter, long, output)
168
169
170 @click.command(name="vnf-show", short_help="shows the info of a VNF instance")
171 @click.argument("name")
172 @click.option("--literal", is_flag=True, help="print literally, no pretty table")
173 @click.option(
174 "--filter",
175 multiple=True,
176 help="restricts the information to the fields in the filter",
177 )
178 @click.option("--kdu", default=None, help="KDU name (whose status will be shown)")
179 @print_output.output_option
180 @click.pass_context
181 def vnf_show(ctx, name, literal, filter, kdu, output):
182 """shows the info of a VNF instance
183
184 NAME: name or ID of the VNF instance
185 """
186
187 def print_kdu_status(op_info_status):
188 """print KDU status properly formatted"""
189 try:
190 op_status = yaml.safe_load(op_info_status)
191 if (
192 "namespace" in op_status
193 and "info" in op_status
194 and "last_deployed" in op_status["info"]
195 and "status" in op_status["info"]
196 and "code" in op_status["info"]["status"]
197 and "resources" in op_status["info"]["status"]
198 and "seconds" in op_status["info"]["last_deployed"]
199 ):
200 last_deployed_time = datetime.fromtimestamp(
201 op_status["info"]["last_deployed"]["seconds"]
202 ).strftime("%a %b %d %I:%M:%S %Y")
203 print("LAST DEPLOYED: {}".format(last_deployed_time))
204 print("NAMESPACE: {}".format(op_status["namespace"]))
205 status_code = "UNKNOWN"
206 if op_status["info"]["status"]["code"] == 1:
207 status_code = "DEPLOYED"
208 print("STATUS: {}".format(status_code))
209 print()
210 print("RESOURCES:")
211 print(op_status["info"]["status"]["resources"])
212 if "notes" in op_status["info"]["status"]:
213 print("NOTES:")
214 print(op_status["info"]["status"]["notes"])
215 else:
216 print(op_info_status)
217 except Exception:
218 print(op_info_status)
219
220 logger.debug("")
221 if kdu:
222 if literal:
223 raise ClientException(
224 '"--literal" option is incompatible with "--kdu" option'
225 )
226 if filter:
227 raise ClientException(
228 '"--filter" option is incompatible with "--kdu" option'
229 )
230
231 utils.check_client_version(ctx.obj, ctx.command.name)
232 resp = ctx.obj.vnf.get(name)
233
234 if kdu:
235 ns_id = resp["nsr-id-ref"]
236 op_data = {}
237 op_data["member_vnf_index"] = resp["member-vnf-index-ref"]
238 op_data["kdu_name"] = kdu
239 op_data["primitive"] = "status"
240 op_data["primitive_params"] = {}
241 op_id = ctx.obj.ns.exec_op(ns_id, op_name="action", op_data=op_data, wait=False)
242 t = 0
243 while t < 30:
244 op_info = ctx.obj.ns.get_op(op_id)
245 if op_info["operationState"] == "COMPLETED":
246 print_kdu_status(op_info["detailed-status"])
247 return
248 time.sleep(5)
249 t += 5
250 print("Could not determine KDU status")
251 return
252
253 if literal:
254 print(yaml.safe_dump(resp, indent=4, default_flow_style=False))
255 return
256
257 table = PrettyTable(["field", "value"])
258 for k, v in list(resp.items()):
259 if not filter or k in filter:
260 table.add_row([k, utils.wrap_text(text=json.dumps(v, indent=2), width=100)])
261 print_output.print_output(output, table.field_names, table._rows)