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