1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 # and others. All rights reserved.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
18 from novaclient.exceptions import NotFound
20 from snaps.config.vm_inst import VmInstanceConfig, FloatingIpConfig
21 from snaps.openstack.openstack_creator import OpenStackComputeObject
22 from snaps.openstack.utils import (
23 glance_utils, cinder_utils, settings_utils, keystone_utils)
24 from snaps.openstack.utils import neutron_utils
25 from snaps.openstack.utils import nova_utils
26 from snaps.openstack.utils.nova_utils import RebootType
27 from snaps.provisioning import ansible_utils
29 __author__ = 'spisarski'
31 logger = logging.getLogger('create_instance')
34 STATUS_ACTIVE = 'ACTIVE'
35 STATUS_DELETED = 'DELETED'
38 class OpenStackVmInstance(OpenStackComputeObject):
40 Class responsible for managing a VM instance in OpenStack
43 def __init__(self, os_creds, instance_settings, image_settings,
44 keypair_settings=None):
47 :param os_creds: The connection credentials to the OpenStack API
48 :param instance_settings: Contains the settings for this VM
49 :param image_settings: The OpenStack image object settings
50 :param keypair_settings: The keypair metadata (Optional)
53 super(self.__class__, self).__init__(os_creds)
57 self.instance_settings = instance_settings
58 self.image_settings = image_settings
59 self.keypair_settings = keypair_settings
61 self.__floating_ip_dict = dict()
63 # Instantiated in self.create()
66 # Note: this object does not change after the VM becomes active
71 Loads the existing VMInst, Port, FloatingIps
72 :return: VMInst domain object
74 super(self.__class__, self).initialize()
76 self.__neutron = neutron_utils.neutron_client(
77 self._os_creds, self._os_session)
78 self.__keystone = keystone_utils.keystone_client(
79 self._os_creds, self._os_session)
80 self.__cinder = cinder_utils.cinder_client(
81 self._os_creds, self._os_session)
82 self.__glance = glance_utils.glance_client(
83 self._os_creds, self._os_session)
85 self.__ports = self.__query_ports(self.instance_settings.port_settings)
86 self.__lookup_existing_vm_by_name()
88 def create(self, block=False):
90 Creates a VM instance and associated objects unless they already exist
91 :param block: Thread will block until instance has either become
92 active, error, or timeout waiting.
93 Additionally, when True, floating IPs will not be applied
95 :return: VMInst domain object
99 if len(self.__ports) == 0:
100 self.__ports = self.__create_ports(
101 self.instance_settings.port_settings)
103 self.__create_vm(block)
107 def __lookup_existing_vm_by_name(self):
109 Populates the member variables 'self.vm' and 'self.floating_ips' if a
110 VM with the same name already exists
113 server = nova_utils.get_server(
114 self._nova, self.__neutron, self.__keystone,
115 vm_inst_settings=self.instance_settings)
117 if server.name == self.instance_settings.name:
120 'Found existing machine with name - %s',
121 self.instance_settings.name)
123 fips = neutron_utils.get_port_floating_ips(
124 self.__neutron, self.__ports)
125 for port_id, fip in fips:
126 settings = self.instance_settings.floating_ip_settings
127 for fip_setting in settings:
128 if port_id == fip_setting.port_id:
129 self.__floating_ip_dict[fip_setting.name] = fip
131 port = neutron_utils.get_port_by_id(
132 self.__neutron, port_id)
133 if port and port.name == fip_setting.port_name:
134 self.__floating_ip_dict[fip_setting.name] = fip
136 def __create_vm(self, block=False):
138 Responsible for creating the VM instance
139 :param block: Thread will block until instance has either become
140 active, error, or timeout waiting. Floating IPs will be
141 assigned after active when block=True
143 self.__vm = nova_utils.create_server(
144 self._nova, self.__keystone, self.__neutron, self.__glance,
145 self.instance_settings, self.image_settings,
146 self._os_creds.project_name, self.keypair_settings)
147 logger.info('Created instance with name - %s',
148 self.instance_settings.name)
151 if not self.vm_active(block=True):
152 raise VmInstanceCreationError(
153 'Fatal error, VM did not become ACTIVE within the alloted '
156 # Create server should do this but found it needed to occur here
157 for sec_grp_name in self.instance_settings.security_group_names:
158 if self.vm_active(block=True):
159 nova_utils.add_security_group(self._nova, self.__vm,
162 raise VmInstanceCreationError(
163 'Cannot applying security group with name ' +
165 ' to VM that did not activate with name - ' +
166 self.instance_settings.name)
168 if self.instance_settings.volume_names:
169 for volume_name in self.instance_settings.volume_names:
170 volume = cinder_utils.get_volume(
171 self.__cinder, self.__keystone, volume_name=volume_name,
172 project_name=self._os_creds.project_name)
174 if volume and self.vm_active(block=True):
175 vm = nova_utils.attach_volume(
176 self._nova, self.__neutron, self.__keystone, self.__vm,
177 volume, self._os_creds.project_name)
183 'Volume [%s] attachment timeout ', volume.name)
185 logger.warn('Unable to attach volume named [%s]',
188 self.__apply_floating_ips()
190 def __apply_floating_ips(self):
192 Applies the configured floating IPs to the necessary ports
195 for key, port in self.__ports:
196 port_dict[key] = port
199 for floating_ip_setting in self.instance_settings.floating_ip_settings:
200 self.add_floating_ip(floating_ip_setting)
202 def add_floating_ip(self, floating_ip_setting):
204 Adds a floating IP to a running instance
205 :param floating_ip_setting - the floating IP configuration
206 :return: the floating ip object
209 for key, port in self.__ports:
210 port_dict[key] = port
213 port = port_dict.get(floating_ip_setting.port_name)
216 raise VmInstanceCreationError(
217 'Cannot find port object with name - ' +
218 floating_ip_setting.port_name)
220 # Setup Floating IP only if there is a router with an external
222 ext_gateway = self.__ext_gateway_by_router(
223 floating_ip_setting.router_name)
224 if ext_gateway and self.vm_active(block=True):
225 floating_ip = neutron_utils.create_floating_ip(
226 self.__neutron, self.__keystone, ext_gateway, port.id)
227 self.__floating_ip_dict[floating_ip_setting.name] = floating_ip
230 'Created floating IP %s via router - %s', floating_ip.ip,
231 floating_ip_setting.router_name)
235 raise VmInstanceCreationError(
236 'Unable to add floating IP to port, cannot locate router '
237 'with an external gateway ')
239 def __ext_gateway_by_router(self, router_name):
241 Returns network name for the external network attached to a router or
243 :param router_name: The name of the router to lookup
244 :return: the external network name or None
246 router = neutron_utils.get_router(
247 self.__neutron, self.__keystone, router_name=router_name,
248 project_name=self._os_creds.project_name)
249 if router and router.external_network_id:
250 network = neutron_utils.get_network_by_id(
251 self.__neutron, router.external_network_id)
258 Destroys the VM instance
261 # Cleanup floating IPs
262 for name, floating_ip in self.__floating_ip_dict.items():
263 logger.info('Deleting Floating IP - ' + floating_ip.ip)
264 neutron_utils.delete_floating_ip(self.__neutron, floating_ip)
266 self.__floating_ip_dict = dict()
269 for name, port in self.__ports:
270 logger.info('Deleting Port with ID - %s ', port.id)
271 neutron_utils.delete_port(self.__neutron, port)
273 self.__ports = list()
277 for volume_rec in self.__vm.volume_ids:
278 volume = cinder_utils.get_volume_by_id(
279 self.__cinder, volume_rec['id'])
281 vm = nova_utils.detach_volume(
282 self._nova, self.__neutron, self.__keystone, self.__vm,
283 volume, self._os_creds.project_name)
288 'Timeout waiting to detach volume %s', volume.name)
290 logger.warn('Unable to detach volume with ID - [%s]',
295 'Deleting VM instance - ' + self.instance_settings.name)
298 nova_utils.delete_vm_instance(self._nova, self.__vm)
299 except NotFound as e:
300 logger.warn('Instance already deleted - %s', e)
302 # Block until instance cannot be found or returns the status of
304 logger.info('Checking deletion status')
306 if self.vm_deleted(block=True):
308 'VM has been properly deleted VM with name - %s',
309 self.instance_settings.name)
313 'VM not deleted within the timeout period of %s '
314 'seconds', self.instance_settings.vm_delete_timeout)
316 super(self.__class__, self).clean()
318 def __query_ports(self, port_settings):
320 Returns the previously configured ports or an empty list if none
322 :param port_settings: A list of PortSetting objects
323 :return: a list of OpenStack port tuples where the first member is the
324 port name and the second is the port object
328 for port_setting in port_settings:
329 port = neutron_utils.get_port(
330 self.__neutron, self.__keystone, port_settings=port_setting,
331 project_name=self._os_creds.project_name)
333 ports.append((port_setting.name, port))
337 def __create_ports(self, port_settings):
339 Returns the previously configured ports or creates them if they do not
341 :param port_settings: A list of PortSetting objects
342 :return: a list of OpenStack port tuples where the first member is the
343 port name and the second is the port object
347 for port_setting in port_settings:
348 port = neutron_utils.get_port(
349 self.__neutron, self.__keystone, port_settings=port_setting)
351 port = neutron_utils.create_port(
352 self.__neutron, self._os_creds, port_setting)
354 ports.append((port_setting.name, port))
358 def get_os_creds(self):
360 Returns the OpenStack credentials used to create these objects
361 :return: the credentials
363 return self._os_creds
365 def get_vm_inst(self):
367 Returns the latest version of this server object from OpenStack
368 :return: Server object
370 return nova_utils.get_server_object_by_id(
371 self._nova, self.__neutron, self.__keystone, self.__vm.id,
372 self._os_creds.project_name)
374 def get_console_output(self):
376 Returns the vm console object for parsing logs
377 :return: the console output object
379 return nova_utils.get_server_console_output(self._nova, self.__vm)
381 def get_port_ip(self, port_name, subnet_name=None):
383 Returns the first IP for the port corresponding with the port_name
384 parameter when subnet_name is None else returns the IP address that
385 corresponds to the subnet_name parameter
386 :param port_name: the name of the port from which to return the IP
387 :param subnet_name: the name of the subnet attached to this IP
388 :return: the IP or None if not found
390 port = self.get_port_by_name(port_name)
393 subnet = neutron_utils.get_subnet(
394 self.__neutron, subnet_name=subnet_name)
396 logger.warning('Cannot retrieve port IP as subnet could '
397 'not be located with name - %s',
400 for fixed_ip in port.ips:
401 if fixed_ip['subnet_id'] == subnet.id:
402 return fixed_ip['ip_address']
404 if port.ips and len(port.ips) > 0:
405 return port.ips[0]['ip_address']
408 def get_port_mac(self, port_name):
410 Returns the first IP for the port corresponding with the port_name
412 TODO - Add in the subnet as an additional parameter as a port may have
414 :param port_name: the name of the port from which to return the IP
415 :return: the IP or None if not found
417 port = self.get_port_by_name(port_name)
419 return port.mac_address
422 def get_port_by_name(self, port_name):
424 Retrieves the OpenStack port object by its given name
425 :param port_name: the name of the port
426 :return: the OpenStack port object or None if not exists
428 for key, port in self.__ports:
431 logger.warning('Cannot find port with name - ' + port_name)
434 def get_vm_info(self):
436 Returns a dictionary of a VMs info as returned by OpenStack
439 from warnings import warn
440 warn('Do not use the returned dict() structure',
443 return nova_utils.get_server_info(self._nova, self.__vm)
445 def __get_first_provisioning_floating_ip(self):
447 Returns the first floating IP tagged with the Floating IP name if
448 exists else the first one found
451 for floating_ip_setting in self.instance_settings.floating_ip_settings:
452 if floating_ip_setting.provisioning:
453 fip = self.__floating_ip_dict.get(floating_ip_setting.name)
456 elif len(self.__floating_ip_dict) > 0:
457 for key, fip in self.__floating_ip_dict.items():
460 # When cannot be found above
461 if len(self.__floating_ip_dict) > 0:
462 for key, fip in self.__floating_ip_dict.items():
465 def apply_ansible_playbook(self, pb_file_loc, variables=None,
468 Applies a playbook to a VM
469 :param pb_file_loc: the file location of the playbook to be applied
470 :param variables: a dict() of substitution values required by the
472 :param fip_name: the name of the floating IP to use for applying the
473 playbook (default - will take the first)
474 :return: the return value from ansible
476 return ansible_utils.apply_playbook(
477 pb_file_loc, [self.get_floating_ip(fip_name=fip_name).ip],
478 self.get_image_user(),
479 ssh_priv_key_file_path=self.keypair_settings.private_filepath,
480 variables=variables, proxy_setting=self._os_creds.proxy_settings)
482 def get_image_user(self):
484 Returns the instance sudo_user if it has been configured in the
485 instance_settings else it returns the image_settings.image_user value
487 if self.instance_settings.sudo_user:
488 return self.instance_settings.sudo_user
490 return self.image_settings.image_user
492 def vm_deleted(self, block=False, poll_interval=POLL_INTERVAL):
494 Returns true when the VM status returns the value of
495 expected_status_code or instance retrieval throws a NotFound exception.
496 :param block: When true, thread will block until active or timeout
497 value in seconds has been exceeded (False)
498 :param poll_interval: The polling interval in seconds
502 return self.__vm_status_check(
503 STATUS_DELETED, block,
504 self.instance_settings.vm_delete_timeout, poll_interval)
505 except NotFound as e:
507 "Instance not found when querying status for %s with message "
508 "%s", STATUS_DELETED, e)
511 def vm_active(self, block=False, poll_interval=POLL_INTERVAL):
513 Returns true when the VM status returns the value of the constant
515 :param block: When true, thread will block until active or timeout
516 value in seconds has been exceeded (False)
517 :param poll_interval: The polling interval in seconds
520 if self.__vm_status_check(
521 STATUS_ACTIVE, block, self.instance_settings.vm_boot_timeout,
523 self.__vm = nova_utils.get_server_object_by_id(
524 self._nova, self.__neutron, self.__keystone, self.__vm.id,
525 self._os_creds.project_name)
529 def __vm_status_check(self, expected_status_code, block, timeout,
532 Returns true when the VM status returns the value of
534 :param expected_status_code: instance status evaluated with this
536 :param block: When true, thread will block until active or timeout
537 value in seconds has been exceeded (False)
538 :param timeout: The timeout value
539 :param poll_interval: The polling interval in seconds
542 # sleep and wait for VM status change
546 return self.__status(expected_status_code)
548 while timeout > time.time() - start:
549 status = self.__status(expected_status_code)
551 logger.info('VM is - ' + expected_status_code)
554 logger.debug('Retry querying VM status in ' + str(
555 poll_interval) + ' seconds')
556 time.sleep(poll_interval)
557 logger.debug('VM status query timeout in ' + str(
558 timeout - (time.time() - start)))
561 'Timeout checking for VM status for ' + expected_status_code)
564 def __status(self, expected_status_code):
566 Returns True when active else False
567 :param expected_status_code: instance status evaluated with this string
572 if expected_status_code == STATUS_DELETED:
577 status = nova_utils.get_server_status(self._nova, self.__vm)
579 logger.warning('Cannot find instance with id - ' + self.__vm.id)
582 if status == 'ERROR':
583 raise VmInstanceCreationError(
584 'Instance had an error during deployment')
586 'Instance status [%s] is - %s', self.instance_settings.name,
588 return status == expected_status_code
590 def vm_ssh_active(self, user_override=None, password=None, block=False,
591 timeout=None, poll_interval=POLL_INTERVAL):
593 Returns true when the VM can be accessed via SSH
594 :param user_override: overrides the user with which to create the
596 :param password: overrides the use of a password instead of a private
597 key with which to create the connection
598 :param block: When true, thread will block until active or timeout
599 value in seconds has been exceeded (False)
600 :param timeout: the number of seconds to retry obtaining the connection
601 and overrides the ssh_connect_timeout member of the
602 self.instance_settings object
603 :param poll_interval: The polling interval
606 # sleep and wait for VM status change
607 logger.info('Checking if VM is active')
610 timeout = self.instance_settings.ssh_connect_timeout
612 if self.vm_active(block=True):
616 start = time.time() - timeout
618 while timeout > time.time() - start:
619 status = self.__ssh_active(
620 user_override=user_override, password=password)
622 logger.info('SSH is active for VM instance')
625 logger.debug('Retry SSH connection in ' + str(
626 poll_interval) + ' seconds')
627 time.sleep(poll_interval)
628 logger.debug('SSH connection timeout in ' + str(
629 timeout - (time.time() - start)))
631 logger.error('Timeout attempting to connect with VM via SSH')
634 def __ssh_active(self, user_override=None, password=None):
636 Returns True when can create a SSH session else False
639 if len(self.__floating_ip_dict) > 0:
640 ssh = self.ssh_client(
641 user_override=user_override, password=password)
647 def cloud_init_complete(self, block=False, poll_interval=POLL_INTERVAL):
649 Returns true when the VM's cloud-init routine has completed.
650 Note: this is currently done via SSH, therefore, if this instance does
651 not have a Floating IP or a running SSH server, this routine
652 will always return False or raise an Exception
653 :param block: When true, thread will block until active or timeout
654 value in seconds has been exceeded (False)
655 :param poll_interval: The polling interval
658 # sleep and wait for VM status change
659 logger.info('Checking if cloud-init has completed')
661 timeout = self.instance_settings.cloud_init_timeout
663 if self.vm_active(block=True) and self.vm_ssh_active(block=True):
667 start = time.time() - timeout
669 while timeout > time.time() - start:
670 status = self.__cloud_init_complete()
672 logger.info('cloud-init complete for VM instance')
675 logger.debug('Retry cloud-init query in ' + str(
676 poll_interval) + ' seconds')
677 time.sleep(poll_interval)
678 logger.debug('cloud-init complete timeout in ' + str(
679 timeout - (time.time() - start)))
681 logger.error('Timeout waiting for cloud-init to complete')
684 def __cloud_init_complete(self):
686 Returns True when can create a SSH session else False
689 if len(self.__floating_ip_dict) > 0:
690 ssh = self.ssh_client()
692 stdin1, stdout1, sterr1 = ssh.exec_command(
693 'ls -l /var/lib/cloud/instance/boot-finished')
694 return stdout1.channel.recv_exit_status() == 0
697 def get_floating_ip(self, fip_name=None):
699 Returns the floating IP object byt name if found, else the first known,
701 :param fip_name: the name of the floating IP to return
702 :return: the SSH client or None
704 if fip_name and self.__floating_ip_dict.get(fip_name):
705 return self.__floating_ip_dict.get(fip_name)
707 return self.__get_first_provisioning_floating_ip()
709 def ssh_client(self, fip_name=None, user_override=None, password=None):
711 Returns an SSH client using the name or the first known floating IP if
713 :param fip_name: the name of the floating IP to return
714 :param user_override: the username to use instead of the default
715 :param password: the password to use instead of the private key
716 :return: the SSH client or None
718 fip = self.get_floating_ip(fip_name)
720 ansible_user = self.get_image_user()
722 ansible_user = user_override
727 private_key = self.keypair_settings.private_filepath
730 return ansible_utils.ssh_client(
731 self.__get_first_provisioning_floating_ip().ip,
733 private_key_filepath=private_key,
735 proxy_settings=self._os_creds.proxy_settings)
737 FloatingIPAllocationError(
738 'Cannot return an SSH client. No Floating IP configured')
740 def add_security_group(self, security_group):
742 Adds a security group to this VM. Call will block until VM is active.
743 :param security_group: the SNAPS SecurityGroup domain object
744 :return True if successful else False
746 self.vm_active(block=True)
748 if not security_group:
749 logger.warning('Security group object is None, cannot add')
753 nova_utils.add_security_group(self._nova, self.get_vm_inst(),
756 except NotFound as e:
757 logger.warning('Security group not added - ' + str(e))
760 def remove_security_group(self, security_group):
762 Removes a security group to this VM. Call will block until VM is active
763 :param security_group: the OpenStack security group object
764 :return True if successful else False
766 self.vm_active(block=True)
768 if not security_group:
769 logger.warning('Security group object is None, cannot remove')
773 nova_utils.remove_security_group(self._nova, self.get_vm_inst(),
776 except NotFound as e:
777 logger.warning('Security group not removed - ' + str(e))
780 def reboot(self, reboot_type=RebootType.soft):
783 :param reboot_type: instance of
784 snaps.openstack.utils.nova_utils.RebootType
788 nova_utils.reboot_server(
789 self._nova, self.__vm, reboot_type=reboot_type)
792 def generate_creator(os_creds, vm_inst, image_config, project_name,
793 keypair_config=None):
795 Initializes an OpenStackVmInstance object
796 :param os_creds: the OpenStack credentials
797 :param vm_inst: the SNAPS-OO VmInst domain object
798 :param image_config: the associated ImageConfig object
799 :param project_name: the associated project ID
800 :param keypair_config: the associated KeypairConfig object (optional)
801 :return: an initialized OpenStackVmInstance object
803 session = keystone_utils.keystone_session(os_creds)
804 nova = nova_utils.nova_client(os_creds, session)
805 keystone = keystone_utils.keystone_client(os_creds, session)
806 neutron = neutron_utils.neutron_client(os_creds, session)
809 derived_inst_config = settings_utils.create_vm_inst_config(
810 nova, keystone, neutron, vm_inst, project_name)
812 derived_inst_creator = OpenStackVmInstance(
813 os_creds, derived_inst_config, image_config, keypair_config)
814 derived_inst_creator.initialize()
815 return derived_inst_creator
817 keystone_utils.close_session(session)
820 class VmInstanceSettings(VmInstanceConfig):
822 Deprecated, use snaps.config.vm_inst.VmInstanceConfig instead
824 def __init__(self, **kwargs):
825 from warnings import warn
826 warn('Use snaps.config.vm_inst.VmInstanceConfig instead',
828 super(self.__class__, self).__init__(**kwargs)
831 class FloatingIpSettings(FloatingIpConfig):
833 Deprecated, use snaps.config.vm_inst.FloatingIpConfig instead
835 def __init__(self, **kwargs):
836 from warnings import warn
837 warn('Use snaps.config.vm_inst.FloatingIpConfig instead',
839 super(self.__class__, self).__init__(**kwargs)
842 class VmInstanceCreationError(Exception):
844 Exception to be thrown when an VM instance cannot be created
848 class FloatingIPAllocationError(Exception):
850 Exception to be thrown when an VM instance cannot allocate a floating IP