create base package 'osm_ro_plugin' for plugin
[osm/RO.git] / RO-plugin / osm_ro_plugin / vimconn.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U.
5 # This file is part of openmano
6 # All Rights Reserved.
7 #
8 # Licensed under the Apache License, Version 2.0 (the "License"); you may
9 # not use this file except in compliance with the License. You may obtain
10 # a copy of the License at
11 #
12 # http://www.apache.org/licenses/LICENSE-2.0
13 #
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 # License for the specific language governing permissions and limitations
18 # under the License.
19 #
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact with: nfvlabs@tid.es
22 ##
23
24 """
25 vimconn implement an Abstract class for the vim connector plugins
26 with the definition of the method to be implemented.
27 """
28
29 import logging
30 import paramiko
31 import socket
32 from io import StringIO
33 import yaml
34 import sys
35 from email.mime.multipart import MIMEMultipart
36 from email.mime.text import MIMEText
37 from http import HTTPStatus
38 import warnings
39
40 __author__ = "Alfonso Tierno, Igor D.C."
41 __date__ = "$14-aug-2017 23:59:59$"
42
43
44 def deprecated(message):
45 def deprecated_decorator(func):
46 def deprecated_func(*args, **kwargs):
47 warnings.warn("{} is a deprecated function. {}".format(func.__name__, message),
48 category=DeprecationWarning,
49 stacklevel=2)
50 warnings.simplefilter('default', DeprecationWarning)
51 return func(*args, **kwargs)
52 return deprecated_func
53 return deprecated_decorator
54
55
56 # Error variables
57 HTTP_Bad_Request = HTTPStatus.BAD_REQUEST.value
58 HTTP_Unauthorized = HTTPStatus.UNAUTHORIZED.value
59 HTTP_Not_Found = HTTPStatus.NOT_FOUND.value
60 HTTP_Method_Not_Allowed = HTTPStatus.METHOD_NOT_ALLOWED.value
61 HTTP_Request_Timeout = HTTPStatus.REQUEST_TIMEOUT.value
62 HTTP_Conflict = HTTPStatus.CONFLICT.value
63 HTTP_Not_Implemented = HTTPStatus.NOT_IMPLEMENTED.value
64 HTTP_Service_Unavailable = HTTPStatus.SERVICE_UNAVAILABLE.value
65 HTTP_Internal_Server_Error = HTTPStatus.INTERNAL_SERVER_ERROR.value
66
67
68 class VimConnException(Exception):
69 """Common and base class Exception for all VimConnector exceptions"""
70 def __init__(self, message, http_code=HTTP_Bad_Request):
71 Exception.__init__(self, message)
72 self.http_code = http_code
73
74
75 class VimConnConnectionException(VimConnException):
76 """Connectivity error with the VIM"""
77 def __init__(self, message, http_code=HTTP_Service_Unavailable):
78 VimConnException.__init__(self, message, http_code)
79
80
81 class VimConnUnexpectedResponse(VimConnException):
82 """Get an wrong response from VIM"""
83 def __init__(self, message, http_code=HTTP_Service_Unavailable):
84 VimConnException.__init__(self, message, http_code)
85
86
87 class VimConnAuthException(VimConnException):
88 """Invalid credentials or authorization to perform this action over the VIM"""
89 def __init__(self, message, http_code=HTTP_Unauthorized):
90 VimConnException.__init__(self, message, http_code)
91
92
93 class VimConnNotFoundException(VimConnException):
94 """The item is not found at VIM"""
95 def __init__(self, message, http_code=HTTP_Not_Found):
96 VimConnException.__init__(self, message, http_code)
97
98
99 class VimConnConflictException(VimConnException):
100 """There is a conflict, e.g. more item found than one"""
101 def __init__(self, message, http_code=HTTP_Conflict):
102 VimConnException.__init__(self, message, http_code)
103
104
105 class VimConnNotSupportedException(VimConnException):
106 """The request is not supported by connector"""
107 def __init__(self, message, http_code=HTTP_Service_Unavailable):
108 VimConnException.__init__(self, message, http_code)
109
110
111 class VimConnNotImplemented(VimConnException):
112 """The method is not implemented by the connected"""
113 def __init__(self, message, http_code=HTTP_Not_Implemented):
114 VimConnException.__init__(self, message, http_code)
115
116
117 class VimConnector():
118 """Abstract base class for all the VIM connector plugins
119 These plugins must implement a VimConnector class derived from this
120 and all these privated methods
121 """
122 def __init__(self, uuid, name, tenant_id, tenant_name, url, url_admin=None, user=None, passwd=None, log_level=None,
123 config={}, persistent_info={}):
124 """
125 Constructor of VIM. Raise an exception is some needed parameter is missing, but it must not do any connectivity
126 checking against the VIM
127 :param uuid: internal id of this VIM
128 :param name: name assigned to this VIM, can be used for logging
129 :param tenant_id: 'tenant_id': (only one of them is mandatory) VIM tenant to be used
130 :param tenant_name: 'tenant_name': (only one of them is mandatory) VIM tenant to be used
131 :param url: url used for normal operations
132 :param url_admin: (optional), url used for administrative tasks
133 :param user: user to access
134 :param passwd: password
135 :param log_level: provided if it should use a different log_level than the general one
136 :param config: dictionary with extra VIM information. This contains a consolidate version of VIM config
137 at VIM_ACCOUNT (attach)
138 :param persitent_info: dict where the class can store information that will be available among class
139 destroy/creation cycles. This info is unique per VIM/credential. At first call it will contain an
140 empty dict. Useful to store login/tokens information for speed up communication
141
142 """
143 self.id = uuid
144 self.name = name
145 self.url = url
146 self.url_admin = url_admin
147 self.tenant_id = tenant_id
148 self.tenant_name = tenant_name
149 self.user = user
150 self.passwd = passwd
151 self.config = config or {}
152 self.availability_zone = None
153 self.logger = logging.getLogger('openmano.vim')
154 if log_level:
155 self.logger.setLevel(getattr(logging, log_level))
156 if not self.url_admin: # try to use normal url
157 self.url_admin = self.url
158
159 def __getitem__(self, index):
160 if index == 'tenant_id':
161 return self.tenant_id
162 if index == 'tenant_name':
163 return self.tenant_name
164 elif index == 'id':
165 return self.id
166 elif index == 'name':
167 return self.name
168 elif index == 'user':
169 return self.user
170 elif index == 'passwd':
171 return self.passwd
172 elif index == 'url':
173 return self.url
174 elif index == 'url_admin':
175 return self.url_admin
176 elif index == "config":
177 return self.config
178 else:
179 raise KeyError("Invalid key '{}'".format(index))
180
181 def __setitem__(self, index, value):
182 if index == 'tenant_id':
183 self.tenant_id = value
184 if index == 'tenant_name':
185 self.tenant_name = value
186 elif index == 'id':
187 self.id = value
188 elif index == 'name':
189 self.name = value
190 elif index == 'user':
191 self.user = value
192 elif index == 'passwd':
193 self.passwd = value
194 elif index == 'url':
195 self.url = value
196 elif index == 'url_admin':
197 self.url_admin = value
198 else:
199 raise KeyError("Invalid key '{}'".format(index))
200
201 @staticmethod
202 def _create_mimemultipart(content_list):
203 """Creates a MIMEmultipart text combining the content_list
204 :param content_list: list of text scripts to be combined
205 :return: str of the created MIMEmultipart. If the list is empty returns None, if the list contains only one
206 element MIMEmultipart is not created and this content is returned
207 """
208 if not content_list:
209 return None
210 elif len(content_list) == 1:
211 return content_list[0]
212 combined_message = MIMEMultipart()
213 for content in content_list:
214 if content.startswith('#include'):
215 mime_format = 'text/x-include-url'
216 elif content.startswith('#include-once'):
217 mime_format = 'text/x-include-once-url'
218 elif content.startswith('#!'):
219 mime_format = 'text/x-shellscript'
220 elif content.startswith('#cloud-config'):
221 mime_format = 'text/cloud-config'
222 elif content.startswith('#cloud-config-archive'):
223 mime_format = 'text/cloud-config-archive'
224 elif content.startswith('#upstart-job'):
225 mime_format = 'text/upstart-job'
226 elif content.startswith('#part-handler'):
227 mime_format = 'text/part-handler'
228 elif content.startswith('#cloud-boothook'):
229 mime_format = 'text/cloud-boothook'
230 else: # by default
231 mime_format = 'text/x-shellscript'
232 sub_message = MIMEText(content, mime_format, sys.getdefaultencoding())
233 combined_message.attach(sub_message)
234 return combined_message.as_string()
235
236 def _create_user_data(self, cloud_config):
237 """
238 Creates a script user database on cloud_config info
239 :param cloud_config: dictionary with
240 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
241 'users': (optional) list of users to be inserted, each item is a dict with:
242 'name': (mandatory) user name,
243 'key-pairs': (optional) list of strings with the public key to be inserted to the user
244 'user-data': (optional) can be a string with the text script to be passed directly to cloud-init,
245 or a list of strings, each one contains a script to be passed, usually with a MIMEmultipart file
246 'config-files': (optional). List of files to be transferred. Each item is a dict with:
247 'dest': (mandatory) string with the destination absolute path
248 'encoding': (optional, by default text). Can be one of:
249 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
250 'content' (mandatory): string with the content of the file
251 'permissions': (optional) string with file permissions, typically octal notation '0644'
252 'owner': (optional) file owner, string with the format 'owner:group'
253 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
254 :return: config_drive, userdata. The first is a boolean or None, the second a string or None
255 """
256 config_drive = None
257 userdata = None
258 userdata_list = []
259 if isinstance(cloud_config, dict):
260 if cloud_config.get("user-data"):
261 if isinstance(cloud_config["user-data"], str):
262 userdata_list.append(cloud_config["user-data"])
263 else:
264 for u in cloud_config["user-data"]:
265 userdata_list.append(u)
266 if cloud_config.get("boot-data-drive") is not None:
267 config_drive = cloud_config["boot-data-drive"]
268 if cloud_config.get("config-files") or cloud_config.get("users") or cloud_config.get("key-pairs"):
269 userdata_dict = {}
270 # default user
271 if cloud_config.get("key-pairs"):
272 userdata_dict["ssh-authorized-keys"] = cloud_config["key-pairs"]
273 userdata_dict["users"] = [{"default": None, "ssh-authorized-keys": cloud_config["key-pairs"]}]
274 if cloud_config.get("users"):
275 if "users" not in userdata_dict:
276 userdata_dict["users"] = ["default"]
277 for user in cloud_config["users"]:
278 user_info = {
279 "name": user["name"],
280 "sudo": "ALL = (ALL)NOPASSWD:ALL"
281 }
282 if "user-info" in user:
283 user_info["gecos"] = user["user-info"]
284 if user.get("key-pairs"):
285 user_info["ssh-authorized-keys"] = user["key-pairs"]
286 userdata_dict["users"].append(user_info)
287
288 if cloud_config.get("config-files"):
289 userdata_dict["write_files"] = []
290 for file in cloud_config["config-files"]:
291 file_info = {
292 "path": file["dest"],
293 "content": file["content"]
294 }
295 if file.get("encoding"):
296 file_info["encoding"] = file["encoding"]
297 if file.get("permissions"):
298 file_info["permissions"] = file["permissions"]
299 if file.get("owner"):
300 file_info["owner"] = file["owner"]
301 userdata_dict["write_files"].append(file_info)
302 userdata_list.append("#cloud-config\n" + yaml.safe_dump(userdata_dict, indent=4,
303 default_flow_style=False))
304 userdata = self._create_mimemultipart(userdata_list)
305 self.logger.debug("userdata: %s", userdata)
306 elif isinstance(cloud_config, str):
307 userdata = cloud_config
308 return config_drive, userdata
309
310 def check_vim_connectivity(self):
311 """Checks VIM can be reached and user credentials are ok.
312 Returns None if success or raises VimConnConnectionException, VimConnAuthException, ...
313 """
314 # by default no checking until each connector implements it
315 return None
316
317 def get_tenant_list(self, filter_dict={}):
318 """Obtain tenants of VIM
319 filter_dict dictionary that can contain the following keys:
320 name: filter by tenant name
321 id: filter by tenant uuid/id
322 <other VIM specific>
323 Returns the tenant list of dictionaries, and empty list if no tenant match all the filers:
324 [{'name':'<name>, 'id':'<id>, ...}, ...]
325 """
326 raise VimConnNotImplemented("Should have implemented this")
327
328 def new_network(self, net_name, net_type, ip_profile=None, shared=False, provider_network_profile=None):
329 """Adds a tenant network to VIM
330 Params:
331 'net_name': name of the network
332 'net_type': one of:
333 'bridge': overlay isolated network
334 'data': underlay E-LAN network for Passthrough and SRIOV interfaces
335 'ptp': underlay E-LINE network for Passthrough and SRIOV interfaces.
336 'ip_profile': is a dict containing the IP parameters of the network
337 'ip_version': can be "IPv4" or "IPv6" (Currently only IPv4 is implemented)
338 'subnet_address': ip_prefix_schema, that is X.X.X.X/Y
339 'gateway_address': (Optional) ip_schema, that is X.X.X.X
340 'dns_address': (Optional) comma separated list of ip_schema, e.g. X.X.X.X[,X,X,X,X]
341 'dhcp_enabled': True or False
342 'dhcp_start_address': ip_schema, first IP to grant
343 'dhcp_count': number of IPs to grant.
344 'shared': if this network can be seen/use by other tenants/organization
345 'provider_network_profile': (optional) contains {segmentation-id: vlan, provider-network: vim_netowrk}
346 Returns a tuple with the network identifier and created_items, or raises an exception on error
347 created_items can be None or a dictionary where this method can include key-values that will be passed to
348 the method delete_network. Can be used to store created segments, created l2gw connections, etc.
349 Format is VimConnector dependent, but do not use nested dictionaries and a value of None should be the same
350 as not present.
351 """
352 raise VimConnNotImplemented("Should have implemented this")
353
354 def get_network_list(self, filter_dict={}):
355 """Obtain tenant networks of VIM
356 Params:
357 'filter_dict' (optional) contains entries to return only networks that matches ALL entries:
358 name: string => returns only networks with this name
359 id: string => returns networks with this VIM id, this imply returns one network at most
360 shared: boolean >= returns only networks that are (or are not) shared
361 tenant_id: sting => returns only networks that belong to this tenant/project
362 ,#(not used yet) admin_state_up: boolean => returns only networks that are (or are not) in admin state
363 active
364 #(not used yet) status: 'ACTIVE','ERROR',... => filter networks that are on this status
365 Returns the network list of dictionaries. each dictionary contains:
366 'id': (mandatory) VIM network id
367 'name': (mandatory) VIM network name
368 'status': (mandatory) can be 'ACTIVE', 'INACTIVE', 'DOWN', 'BUILD', 'ERROR', 'VIM_ERROR', 'OTHER'
369 'network_type': (optional) can be 'vxlan', 'vlan' or 'flat'
370 'segmentation_id': (optional) in case network_type is vlan or vxlan this field contains the segmentation id
371 'error_msg': (optional) text that explains the ERROR status
372 other VIM specific fields: (optional) whenever possible using the same naming of filter_dict param
373 List can be empty if no network map the filter_dict. Raise an exception only upon VIM connectivity,
374 authorization, or some other unspecific error
375 """
376 raise VimConnNotImplemented("Should have implemented this")
377
378 def get_network(self, net_id):
379 """Obtain network details from the 'net_id' VIM network
380 Return a dict that contains:
381 'id': (mandatory) VIM network id, that is, net_id
382 'name': (mandatory) VIM network name
383 'status': (mandatory) can be 'ACTIVE', 'INACTIVE', 'DOWN', 'BUILD', 'ERROR', 'VIM_ERROR', 'OTHER'
384 'error_msg': (optional) text that explains the ERROR status
385 other VIM specific fields: (optional) whenever possible using the same naming of filter_dict param
386 Raises an exception upon error or when network is not found
387 """
388 raise VimConnNotImplemented("Should have implemented this")
389
390 def delete_network(self, net_id, created_items=None):
391 """
392 Removes a tenant network from VIM and its associated elements
393 :param net_id: VIM identifier of the network, provided by method new_network
394 :param created_items: dictionary with extra items to be deleted. provided by method new_network
395 Returns the network identifier or raises an exception upon error or when network is not found
396 """
397 raise VimConnNotImplemented("Should have implemented this")
398
399 def refresh_nets_status(self, net_list):
400 """Get the status of the networks
401 Params:
402 'net_list': a list with the VIM network id to be get the status
403 Returns a dictionary with:
404 'net_id': #VIM id of this network
405 status: #Mandatory. Text with one of:
406 # DELETED (not found at vim)
407 # VIM_ERROR (Cannot connect to VIM, authentication problems, VIM response error, ...)
408 # OTHER (Vim reported other status not understood)
409 # ERROR (VIM indicates an ERROR status)
410 # ACTIVE, INACTIVE, DOWN (admin down),
411 # BUILD (on building process)
412 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
413 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
414 'net_id2': ...
415 """
416 raise VimConnNotImplemented("Should have implemented this")
417
418 def get_flavor(self, flavor_id):
419 """Obtain flavor details from the VIM
420 Returns the flavor dict details {'id':<>, 'name':<>, other vim specific }
421 Raises an exception upon error or if not found
422 """
423 raise VimConnNotImplemented("Should have implemented this")
424
425 def get_flavor_id_from_data(self, flavor_dict):
426 """Obtain flavor id that match the flavor description
427 Params:
428 'flavor_dict': dictionary that contains:
429 'disk': main hard disk in GB
430 'ram': meomry in MB
431 'vcpus': number of virtual cpus
432 #TODO: complete parameters for EPA
433 Returns the flavor_id or raises a VimConnNotFoundException
434 """
435 raise VimConnNotImplemented("Should have implemented this")
436
437 def new_flavor(self, flavor_data):
438 """Adds a tenant flavor to VIM
439 flavor_data contains a dictionary with information, keys:
440 name: flavor name
441 ram: memory (cloud type) in MBytes
442 vpcus: cpus (cloud type)
443 extended: EPA parameters
444 - numas: #items requested in same NUMA
445 memory: number of 1G huge pages memory
446 paired-threads|cores|threads: number of paired hyperthreads, complete cores OR individual
447 threads
448 interfaces: # passthrough(PT) or SRIOV interfaces attached to this numa
449 - name: interface name
450 dedicated: yes|no|yes:sriov; for PT, SRIOV or only one SRIOV for the physical NIC
451 bandwidth: X Gbps; requested guarantee bandwidth
452 vpci: requested virtual PCI address
453 disk: disk size
454 is_public:
455 #TODO to concrete
456 Returns the flavor identifier"""
457 raise VimConnNotImplemented("Should have implemented this")
458
459 def delete_flavor(self, flavor_id):
460 """Deletes a tenant flavor from VIM identify by its id
461 Returns the used id or raise an exception"""
462 raise VimConnNotImplemented("Should have implemented this")
463
464 def new_image(self, image_dict):
465 """ Adds a tenant image to VIM
466 Returns the image id or raises an exception if failed
467 """
468 raise VimConnNotImplemented("Should have implemented this")
469
470 def delete_image(self, image_id):
471 """Deletes a tenant image from VIM
472 Returns the image_id if image is deleted or raises an exception on error"""
473 raise VimConnNotImplemented("Should have implemented this")
474
475 def get_image_id_from_path(self, path):
476 """Get the image id from image path in the VIM database.
477 Returns the image_id or raises a VimConnNotFoundException
478 """
479 raise VimConnNotImplemented("Should have implemented this")
480
481 def get_image_list(self, filter_dict={}):
482 """Obtain tenant images from VIM
483 Filter_dict can be:
484 name: image name
485 id: image uuid
486 checksum: image checksum
487 location: image path
488 Returns the image list of dictionaries:
489 [{<the fields at Filter_dict plus some VIM specific>}, ...]
490 List can be empty
491 """
492 raise VimConnNotImplemented("Should have implemented this")
493
494 def new_vminstance(self, name, description, start, image_id, flavor_id, net_list, cloud_config=None, disk_list=None,
495 availability_zone_index=None, availability_zone_list=None):
496 """Adds a VM instance to VIM
497 Params:
498 'start': (boolean) indicates if VM must start or created in pause mode.
499 'image_id','flavor_id': image and flavor VIM id to use for the VM
500 'net_list': list of interfaces, each one is a dictionary with:
501 'name': (optional) name for the interface.
502 'net_id': VIM network id where this interface must be connect to. Mandatory for type==virtual
503 'vpci': (optional) virtual vPCI address to assign at the VM. Can be ignored depending on VIM
504 capabilities
505 'model': (optional and only have sense for type==virtual) interface model: virtio, e1000, ...
506 'mac_address': (optional) mac address to assign to this interface
507 'ip_address': (optional) IP address to assign to this interface
508 #TODO: CHECK if an optional 'vlan' parameter is needed for VIMs when type if VF and net_id is not
509 provided, the VLAN tag to be used. In case net_id is provided, the internal network vlan is used
510 for tagging VF
511 'type': (mandatory) can be one of:
512 'virtual', in this case always connected to a network of type 'net_type=bridge'
513 'PCI-PASSTHROUGH' or 'PF' (passthrough): depending on VIM capabilities it can be connected to a
514 data/ptp network ot it
515 can created unconnected
516 'SR-IOV' or 'VF' (SRIOV with VLAN tag): same as PF for network connectivity.
517 'VFnotShared'(SRIOV without VLAN tag) same as PF for network connectivity. VF where no other VFs
518 are allocated on the same physical NIC
519 'bw': (optional) only for PF/VF/VFnotShared. Minimal Bandwidth required for the interface in GBPS
520 'port_security': (optional) If False it must avoid any traffic filtering at this interface. If missing
521 or True, it must apply the default VIM behaviour
522 After execution the method will add the key:
523 'vim_id': must be filled/added by this method with the VIM identifier generated by the VIM for this
524 interface. 'net_list' is modified
525 'cloud_config': (optional) dictionary with:
526 'key-pairs': (optional) list of strings with the public key to be inserted to the default user
527 'users': (optional) list of users to be inserted, each item is a dict with:
528 'name': (mandatory) user name,
529 'key-pairs': (optional) list of strings with the public key to be inserted to the user
530 'user-data': (optional) can be a string with the text script to be passed directly to cloud-init,
531 or a list of strings, each one contains a script to be passed, usually with a MIMEmultipart file
532 'config-files': (optional). List of files to be transferred. Each item is a dict with:
533 'dest': (mandatory) string with the destination absolute path
534 'encoding': (optional, by default text). Can be one of:
535 'b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
536 'content' (mandatory): string with the content of the file
537 'permissions': (optional) string with file permissions, typically octal notation '0644'
538 'owner': (optional) file owner, string with the format 'owner:group'
539 'boot-data-drive': boolean to indicate if user-data must be passed using a boot drive (hard disk)
540 'disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
541 'image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
542 'size': (mandatory) string with the size of the disk in GB
543 availability_zone_index: Index of availability_zone_list to use for this this VM. None if not AV required
544 availability_zone_list: list of availability zones given by user in the VNFD descriptor. Ignore if
545 availability_zone_index is None
546 Returns a tuple with the instance identifier and created_items or raises an exception on error
547 created_items can be None or a dictionary where this method can include key-values that will be passed to
548 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
549 Format is VimConnector dependent, but do not use nested dictionaries and a value of None should be the same
550 as not present.
551 """
552 raise VimConnNotImplemented("Should have implemented this")
553
554 def get_vminstance(self, vm_id):
555 """Returns the VM instance information from VIM"""
556 raise VimConnNotImplemented("Should have implemented this")
557
558 def delete_vminstance(self, vm_id, created_items=None):
559 """
560 Removes a VM instance from VIM and its associated elements
561 :param vm_id: VIM identifier of the VM, provided by method new_vminstance
562 :param created_items: dictionary with extra items to be deleted. provided by method new_vminstance and/or method
563 action_vminstance
564 :return: None or the same vm_id. Raises an exception on fail
565 """
566 raise VimConnNotImplemented("Should have implemented this")
567
568 def refresh_vms_status(self, vm_list):
569 """Get the status of the virtual machines and their interfaces/ports
570 Params: the list of VM identifiers
571 Returns a dictionary with:
572 vm_id: #VIM id of this Virtual Machine
573 status: #Mandatory. Text with one of:
574 # DELETED (not found at vim)
575 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
576 # OTHER (Vim reported other status not understood)
577 # ERROR (VIM indicates an ERROR status)
578 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
579 # BUILD (on building process), ERROR
580 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
581 #
582 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
583 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
584 interfaces: list with interface info. Each item a dictionary with:
585 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
586 mac_address: #Text format XX:XX:XX:XX:XX:XX
587 vim_net_id: #network id where this interface is connected, if provided at creation
588 vim_interface_id: #interface/port VIM id
589 ip_address: #null, or text with IPv4, IPv6 address
590 compute_node: #identification of compute node where PF,VF interface is allocated
591 pci: #PCI address of the NIC that hosts the PF,VF
592 vlan: #physical VLAN used for VF
593 """
594 raise VimConnNotImplemented("Should have implemented this")
595
596 def action_vminstance(self, vm_id, action_dict, created_items={}):
597 """
598 Send and action over a VM instance. Returns created_items if the action was successfully sent to the VIM.
599 created_items is a dictionary with items that
600 :param vm_id: VIM identifier of the VM, provided by method new_vminstance
601 :param action_dict: dictionary with the action to perform
602 :param created_items: provided by method new_vminstance is a dictionary with key-values that will be passed to
603 the method delete_vminstance. Can be used to store created ports, volumes, etc. Format is VimConnector
604 dependent, but do not use nested dictionaries and a value of None should be the same as not present. This
605 method can modify this value
606 :return: None, or a console dict
607 """
608 raise VimConnNotImplemented("Should have implemented this")
609
610 def get_vminstance_console(self, vm_id, console_type="vnc"):
611 """
612 Get a console for the virtual machine
613 Params:
614 vm_id: uuid of the VM
615 console_type, can be:
616 "novnc" (by default), "xvpvnc" for VNC types,
617 "rdp-html5" for RDP types, "spice-html5" for SPICE types
618 Returns dict with the console parameters:
619 protocol: ssh, ftp, http, https, ...
620 server: usually ip address
621 port: the http, ssh, ... port
622 suffix: extra text, e.g. the http path and query string
623 """
624 raise VimConnNotImplemented("Should have implemented this")
625
626 def inject_user_key(self, ip_addr=None, user=None, key=None, ro_key=None, password=None):
627 """
628 Inject a ssh public key in a VM
629 Params:
630 ip_addr: ip address of the VM
631 user: username (default-user) to enter in the VM
632 key: public key to be injected in the VM
633 ro_key: private key of the RO, used to enter in the VM if the password is not provided
634 password: password of the user to enter in the VM
635 The function doesn't return a value:
636 """
637 if not ip_addr or not user:
638 raise VimConnNotSupportedException("All parameters should be different from 'None'")
639 elif not ro_key and not password:
640 raise VimConnNotSupportedException("All parameters should be different from 'None'")
641 else:
642 commands = {'mkdir -p ~/.ssh/', 'echo "{}" >> ~/.ssh/authorized_keys'.format(key),
643 'chmod 644 ~/.ssh/authorized_keys', 'chmod 700 ~/.ssh/'}
644 client = paramiko.SSHClient()
645 try:
646 if ro_key:
647 pkey = paramiko.RSAKey.from_private_key(StringIO(ro_key))
648 else:
649 pkey = None
650 client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
651 client.connect(ip_addr, username=user, password=password, pkey=pkey, timeout=10)
652 for command in commands:
653 (i, o, e) = client.exec_command(command, timeout=10)
654 returncode = o.channel.recv_exit_status()
655 outerror = e.read()
656 if returncode != 0:
657 text = "run_command='{}' Error='{}'".format(command, outerror)
658 raise VimConnUnexpectedResponse("Cannot inject ssh key in VM: '{}'".format(text))
659 return
660 except (socket.error, paramiko.AuthenticationException, paramiko.SSHException) as message:
661 raise VimConnUnexpectedResponse(
662 "Cannot inject ssh key in VM: '{}' - {}".format(ip_addr, str(message)))
663 return
664
665 # Optional methods
666
667 def new_tenant(self, tenant_name, tenant_description):
668 """Adds a new tenant to VIM with this name and description, this is done using admin_url if provided
669 "tenant_name": string max lenght 64
670 "tenant_description": string max length 256
671 returns the tenant identifier or raise exception
672 """
673 raise VimConnNotImplemented("Should have implemented this")
674
675 def delete_tenant(self, tenant_id,):
676 """Delete a tenant from VIM
677 tenant_id: returned VIM tenant_id on "new_tenant"
678 Returns None on success. Raises and exception of failure. If tenant is not found raises VimConnNotFoundException
679 """
680 raise VimConnNotImplemented("Should have implemented this")
681
682 def new_classification(self, name, ctype, definition):
683 """Creates a traffic classification in the VIM
684 Params:
685 'name': name of this classification
686 'ctype': type of this classification
687 'definition': definition of this classification (type-dependent free-form text)
688 Returns the VIM's classification ID on success or raises an exception on failure
689 """
690 raise VimConnNotImplemented("SFC support not implemented")
691
692 def get_classification(self, classification_id):
693 """Obtain classification details of the VIM's classification with ID='classification_id'
694 Return a dict that contains:
695 'id': VIM's classification ID (same as classification_id)
696 'name': VIM's classification name
697 'type': type of this classification
698 'definition': definition of the classification
699 'status': 'ACTIVE', 'INACTIVE', 'DOWN', 'BUILD', 'ERROR', 'VIM_ERROR', 'OTHER'
700 'error_msg': (optional) text that explains the ERROR status
701 other VIM specific fields: (optional) whenever possible
702 Raises an exception upon error or when classification is not found
703 """
704 raise VimConnNotImplemented("SFC support not implemented")
705
706 def get_classification_list(self, filter_dict={}):
707 """Obtain classifications from the VIM
708 Params:
709 'filter_dict' (optional): contains the entries to filter the classifications on and only return those that
710 match ALL:
711 id: string => returns classifications with this VIM's classification ID, which implies a return of one
712 classification at most
713 name: string => returns only classifications with this name
714 type: string => returns classifications of this type
715 definition: string => returns classifications that have this definition
716 tenant_id: string => returns only classifications that belong to this tenant/project
717 Returns a list of classification dictionaries, each dictionary contains:
718 'id': (mandatory) VIM's classification ID
719 'name': (mandatory) VIM's classification name
720 'type': type of this classification
721 'definition': definition of the classification
722 other VIM specific fields: (optional) whenever possible using the same naming of filter_dict param
723 List can be empty if no classification matches the filter_dict. Raise an exception only upon VIM connectivity,
724 authorization, or some other unspecific error
725 """
726 raise VimConnNotImplemented("SFC support not implemented")
727
728 def refresh_classifications_status(self, classification_list):
729 '''Get the status of the classifications
730 Params: the list of classification identifiers
731 Returns a dictionary with:
732 vm_id: #VIM id of this classifier
733 status: #Mandatory. Text with one of:
734 # DELETED (not found at vim)
735 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
736 # OTHER (Vim reported other status not understood)
737 # ERROR (VIM indicates an ERROR status)
738 # ACTIVE,
739 # CREATING (on building process)
740 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
741 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
742 '''
743 raise VimConnNotImplemented("Should have implemented this")
744
745 def delete_classification(self, classification_id):
746 """Deletes a classification from the VIM
747 Returns the classification ID (classification_id) or raises an exception upon error or when classification is
748 not found
749 """
750 raise VimConnNotImplemented("SFC support not implemented")
751
752 def new_sfi(self, name, ingress_ports, egress_ports, sfc_encap=True):
753 """Creates a service function instance in the VIM
754 Params:
755 'name': name of this service function instance
756 'ingress_ports': set of ingress ports (VIM's port IDs)
757 'egress_ports': set of egress ports (VIM's port IDs)
758 'sfc_encap': boolean stating whether this specific instance supports IETF SFC Encapsulation
759 Returns the VIM's service function instance ID on success or raises an exception on failure
760 """
761 raise VimConnNotImplemented("SFC support not implemented")
762
763 def get_sfi(self, sfi_id):
764 """Obtain service function instance details of the VIM's service function instance with ID='sfi_id'
765 Return a dict that contains:
766 'id': VIM's sfi ID (same as sfi_id)
767 'name': VIM's sfi name
768 'ingress_ports': set of ingress ports (VIM's port IDs)
769 'egress_ports': set of egress ports (VIM's port IDs)
770 'status': 'ACTIVE', 'INACTIVE', 'DOWN', 'BUILD', 'ERROR', 'VIM_ERROR', 'OTHER'
771 'error_msg': (optional) text that explains the ERROR status
772 other VIM specific fields: (optional) whenever possible
773 Raises an exception upon error or when service function instance is not found
774 """
775 raise VimConnNotImplemented("SFC support not implemented")
776
777 def get_sfi_list(self, filter_dict={}):
778 """Obtain service function instances from the VIM
779 Params:
780 'filter_dict' (optional): contains the entries to filter the sfis on and only return those that match ALL:
781 id: string => returns sfis with this VIM's sfi ID, which implies a return of one sfi at most
782 name: string => returns only service function instances with this name
783 tenant_id: string => returns only service function instances that belong to this tenant/project
784 Returns a list of service function instance dictionaries, each dictionary contains:
785 'id': (mandatory) VIM's sfi ID
786 'name': (mandatory) VIM's sfi name
787 'ingress_ports': set of ingress ports (VIM's port IDs)
788 'egress_ports': set of egress ports (VIM's port IDs)
789 other VIM specific fields: (optional) whenever possible using the same naming of filter_dict param
790 List can be empty if no sfi matches the filter_dict. Raise an exception only upon VIM connectivity,
791 authorization, or some other unspecific error
792 """
793 raise VimConnNotImplemented("SFC support not implemented")
794
795 def delete_sfi(self, sfi_id):
796 """Deletes a service function instance from the VIM
797 Returns the service function instance ID (sfi_id) or raises an exception upon error or when sfi is not found
798 """
799 raise VimConnNotImplemented("SFC support not implemented")
800
801 def refresh_sfis_status(self, sfi_list):
802 '''Get the status of the service function instances
803 Params: the list of sfi identifiers
804 Returns a dictionary with:
805 vm_id: #VIM id of this service function instance
806 status: #Mandatory. Text with one of:
807 # DELETED (not found at vim)
808 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
809 # OTHER (Vim reported other status not understood)
810 # ERROR (VIM indicates an ERROR status)
811 # ACTIVE,
812 # CREATING (on building process)
813 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
814 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
815 '''
816 raise VimConnNotImplemented("Should have implemented this")
817
818 def new_sf(self, name, sfis, sfc_encap=True):
819 """Creates (an abstract) service function in the VIM
820 Params:
821 'name': name of this service function
822 'sfis': set of service function instances of this (abstract) service function
823 'sfc_encap': boolean stating whether this service function supports IETF SFC Encapsulation
824 Returns the VIM's service function ID on success or raises an exception on failure
825 """
826 raise VimConnNotImplemented("SFC support not implemented")
827
828 def get_sf(self, sf_id):
829 """Obtain service function details of the VIM's service function with ID='sf_id'
830 Return a dict that contains:
831 'id': VIM's sf ID (same as sf_id)
832 'name': VIM's sf name
833 'sfis': VIM's sf's set of VIM's service function instance IDs
834 'sfc_encap': boolean stating whether this service function supports IETF SFC Encapsulation
835 'status': 'ACTIVE', 'INACTIVE', 'DOWN', 'BUILD', 'ERROR', 'VIM_ERROR', 'OTHER'
836 'error_msg': (optional) text that explains the ERROR status
837 other VIM specific fields: (optional) whenever possible
838 Raises an exception upon error or when sf is not found
839 """
840
841 def get_sf_list(self, filter_dict={}):
842 """Obtain service functions from the VIM
843 Params:
844 'filter_dict' (optional): contains the entries to filter the sfs on and only return those that match ALL:
845 id: string => returns sfs with this VIM's sf ID, which implies a return of one sf at most
846 name: string => returns only service functions with this name
847 tenant_id: string => returns only service functions that belong to this tenant/project
848 Returns a list of service function dictionaries, each dictionary contains:
849 'id': (mandatory) VIM's sf ID
850 'name': (mandatory) VIM's sf name
851 'sfis': VIM's sf's set of VIM's service function instance IDs
852 'sfc_encap': boolean stating whether this service function supports IETF SFC Encapsulation
853 other VIM specific fields: (optional) whenever possible using the same naming of filter_dict param
854 List can be empty if no sf matches the filter_dict. Raise an exception only upon VIM connectivity,
855 authorization, or some other unspecific error
856 """
857 raise VimConnNotImplemented("SFC support not implemented")
858
859 def delete_sf(self, sf_id):
860 """Deletes (an abstract) service function from the VIM
861 Returns the service function ID (sf_id) or raises an exception upon error or when sf is not found
862 """
863 raise VimConnNotImplemented("SFC support not implemented")
864
865 def refresh_sfs_status(self, sf_list):
866 '''Get the status of the service functions
867 Params: the list of sf identifiers
868 Returns a dictionary with:
869 vm_id: #VIM id of this service function
870 status: #Mandatory. Text with one of:
871 # DELETED (not found at vim)
872 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
873 # OTHER (Vim reported other status not understood)
874 # ERROR (VIM indicates an ERROR status)
875 # ACTIVE,
876 # CREATING (on building process)
877 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
878 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
879 '''
880 raise VimConnNotImplemented("Should have implemented this")
881
882 def new_sfp(self, name, classifications, sfs, sfc_encap=True, spi=None):
883 """Creates a service function path
884 Params:
885 'name': name of this service function path
886 'classifications': set of traffic classifications that should be matched on to get into this sfp
887 'sfs': list of every service function that constitutes this path , from first to last
888 'sfc_encap': whether this is an SFC-Encapsulated chain (i.e using NSH), True by default
889 'spi': (optional) the Service Function Path identifier (SPI: Service Path Identifier) for this path
890 Returns the VIM's sfp ID on success or raises an exception on failure
891 """
892 raise VimConnNotImplemented("SFC support not implemented")
893
894 def get_sfp(self, sfp_id):
895 """Obtain service function path details of the VIM's sfp with ID='sfp_id'
896 Return a dict that contains:
897 'id': VIM's sfp ID (same as sfp_id)
898 'name': VIM's sfp name
899 'classifications': VIM's sfp's list of VIM's classification IDs
900 'sfs': VIM's sfp's list of VIM's service function IDs
901 'status': 'ACTIVE', 'INACTIVE', 'DOWN', 'BUILD', 'ERROR', 'VIM_ERROR', 'OTHER'
902 'error_msg': (optional) text that explains the ERROR status
903 other VIM specific fields: (optional) whenever possible
904 Raises an exception upon error or when sfp is not found
905 """
906 raise VimConnNotImplemented("SFC support not implemented")
907
908 def get_sfp_list(self, filter_dict={}):
909 """Obtain service function paths from VIM
910 Params:
911 'filter_dict' (optional): contains the entries to filter the sfps on, and only return those that match ALL:
912 id: string => returns sfps with this VIM's sfp ID , which implies a return of one sfp at most
913 name: string => returns only sfps with this name
914 tenant_id: string => returns only sfps that belong to this tenant/project
915 Returns a list of service function path dictionaries, each dictionary contains:
916 'id': (mandatory) VIM's sfp ID
917 'name': (mandatory) VIM's sfp name
918 'classifications': VIM's sfp's list of VIM's classification IDs
919 'sfs': VIM's sfp's list of VIM's service function IDs
920 other VIM specific fields: (optional) whenever possible using the same naming of filter_dict param
921 List can be empty if no sfp matches the filter_dict. Raise an exception only upon VIM connectivity,
922 authorization, or some other unspecific error
923 """
924 raise VimConnNotImplemented("SFC support not implemented")
925
926 def refresh_sfps_status(self, sfp_list):
927 '''Get the status of the service function path
928 Params: the list of sfp identifiers
929 Returns a dictionary with:
930 vm_id: #VIM id of this service function path
931 status: #Mandatory. Text with one of:
932 # DELETED (not found at vim)
933 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
934 # OTHER (Vim reported other status not understood)
935 # ERROR (VIM indicates an ERROR status)
936 # ACTIVE,
937 # CREATING (on building process)
938 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
939 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)F
940 '''
941 raise VimConnNotImplemented("Should have implemented this")
942
943 def delete_sfp(self, sfp_id):
944 """Deletes a service function path from the VIM
945 Returns the sfp ID (sfp_id) or raises an exception upon error or when sf is not found
946 """
947 raise VimConnNotImplemented("SFC support not implemented")
948
949 # NOT USED METHODS in current version. Deprecated
950
951 @deprecated
952 def host_vim2gui(self, host, server_dict):
953 """Transform host dictionary from VIM format to GUI format,
954 and append to the server_dict
955 """
956 raise VimConnNotImplemented("Should have implemented this")
957
958 @deprecated
959 def get_hosts_info(self):
960 """Get the information of deployed hosts
961 Returns the hosts content"""
962 raise VimConnNotImplemented("Should have implemented this")
963
964 @deprecated
965 def get_hosts(self, vim_tenant):
966 """Get the hosts and deployed instances
967 Returns the hosts content"""
968 raise VimConnNotImplemented("Should have implemented this")
969
970 @deprecated
971 def get_processor_rankings(self):
972 """Get the processor rankings in the VIM database"""
973 raise VimConnNotImplemented("Should have implemented this")
974
975 @deprecated
976 def new_host(self, host_data):
977 """Adds a new host to VIM"""
978 """Returns status code of the VIM response"""
979 raise VimConnNotImplemented("Should have implemented this")
980
981 @deprecated
982 def new_external_port(self, port_data):
983 """Adds a external port to VIM"""
984 """Returns the port identifier"""
985 raise VimConnNotImplemented("Should have implemented this")
986
987 @deprecated
988 def new_external_network(self, net_name, net_type):
989 """Adds a external network to VIM (shared)"""
990 """Returns the network identifier"""
991 raise VimConnNotImplemented("Should have implemented this")
992
993 @deprecated
994 def connect_port_network(self, port_id, network_id, admin=False):
995 """Connects a external port to a network"""
996 """Returns status code of the VIM response"""
997 raise VimConnNotImplemented("Should have implemented this")
998
999 @deprecated
1000 def new_vminstancefromJSON(self, vm_data):
1001 """Adds a VM instance to VIM"""
1002 """Returns the instance identifier"""
1003 raise VimConnNotImplemented("Should have implemented this")