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 glance_utils, cinder_utils, settings_utils
23 from snaps.openstack.utils import neutron_utils
24 from snaps.openstack.utils import nova_utils
25 from snaps.openstack.utils.nova_utils import RebootType
26 from snaps.provisioning import ansible_utils
28 __author__ = 'spisarski'
30 logger = logging.getLogger('create_instance')
33 VOL_DETACH_TIMEOUT = 120
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(self._os_creds)
78 self.__ports = self.__query_ports(self.instance_settings.port_settings)
79 self.__lookup_existing_vm_by_name()
81 def create(self, block=False):
83 Creates a VM instance and associated objects unless they already exist
84 :param block: Thread will block until instance has either become
85 active, error, or timeout waiting.
86 Additionally, when True, floating IPs will not be applied
88 :return: VMInst domain object
92 if len(self.__ports) == 0:
93 self.__ports = self.__create_ports(
94 self.instance_settings.port_settings)
96 self.__create_vm(block)
100 def __lookup_existing_vm_by_name(self):
102 Populates the member variables 'self.vm' and 'self.floating_ips' if a
103 VM with the same name already exists
106 server = nova_utils.get_server(
107 self._nova, self.__neutron,
108 vm_inst_settings=self.instance_settings)
110 if server.name == self.instance_settings.name:
113 'Found existing machine with name - %s',
114 self.instance_settings.name)
116 fips = neutron_utils.get_floating_ips(self.__neutron,
118 for port_id, fip in fips:
119 settings = self.instance_settings.floating_ip_settings
120 for fip_setting in settings:
121 if port_id == fip_setting.port_id:
122 self.__floating_ip_dict[fip_setting.name] = fip
124 port = neutron_utils.get_port_by_id(
125 self.__neutron, port_id)
126 if port and port.name == fip_setting.port_name:
127 self.__floating_ip_dict[fip_setting.name] = fip
129 def __create_vm(self, block=False):
131 Responsible for creating the VM instance
132 :param block: Thread will block until instance has either become
133 active, error, or timeout waiting. Floating IPs will be
134 assigned after active when block=True
136 glance = glance_utils.glance_client(self._os_creds)
137 self.__vm = nova_utils.create_server(
138 self._nova, self.__neutron, glance, self.instance_settings,
139 self.image_settings, self.keypair_settings)
140 logger.info('Created instance with name - %s',
141 self.instance_settings.name)
144 if not self.vm_active(block=True):
145 raise VmInstanceCreationError(
146 'Fatal error, VM did not become ACTIVE within the alloted '
149 # Create server should do this but found it needed to occur here
150 for sec_grp_name in self.instance_settings.security_group_names:
151 if self.vm_active(block=True):
152 nova_utils.add_security_group(self._nova, self.__vm,
155 raise VmInstanceCreationError(
156 'Cannot applying security group with name ' +
158 ' to VM that did not activate with name - ' +
159 self.instance_settings.name)
161 if self.instance_settings.volume_names:
162 for volume_name in self.instance_settings.volume_names:
163 cinder = cinder_utils.cinder_client(self._os_creds)
164 volume = cinder_utils.get_volume(
165 cinder, volume_name=volume_name)
167 if volume and self.vm_active(block=True):
168 vm = nova_utils.attach_volume(
169 self._nova, self.__neutron, self.__vm, volume,
175 logger.warn('Volume [%s] not attached within timeout '
176 'of [%s]', volume.name, VOL_DETACH_TIMEOUT)
178 logger.warn('Unable to attach volume named [%s]',
181 self.__apply_floating_ips()
183 def __apply_floating_ips(self):
185 Applies the configured floating IPs to the necessary ports
188 for key, port in self.__ports:
189 port_dict[key] = port
192 for floating_ip_setting in self.instance_settings.floating_ip_settings:
193 self.add_floating_ip(floating_ip_setting)
195 def add_floating_ip(self, floating_ip_setting):
197 Adds a floating IP to a running instance
198 :param floating_ip_setting - the floating IP configuration
199 :return: the floating ip object
202 for key, port in self.__ports:
203 port_dict[key] = port
206 port = port_dict.get(floating_ip_setting.port_name)
209 raise VmInstanceCreationError(
210 'Cannot find port object with name - ' +
211 floating_ip_setting.port_name)
213 # Setup Floating IP only if there is a router with an external
215 ext_gateway = self.__ext_gateway_by_router(
216 floating_ip_setting.router_name)
217 if ext_gateway and self.vm_active(block=True):
218 floating_ip = neutron_utils.create_floating_ip(
219 self.__neutron, ext_gateway, port.id)
220 self.__floating_ip_dict[floating_ip_setting.name] = floating_ip
223 'Created floating IP %s via router - %s', floating_ip.ip,
224 floating_ip_setting.router_name)
228 raise VmInstanceCreationError(
229 'Unable to add floating IP to port, cannot locate router '
230 'with an external gateway ')
232 def __ext_gateway_by_router(self, router_name):
234 Returns network name for the external network attached to a router or
236 :param router_name: The name of the router to lookup
237 :return: the external network name or None
239 router = neutron_utils.get_router(
240 self.__neutron, router_name=router_name)
241 if router and router.external_network_id:
242 network = neutron_utils.get_network_by_id(
243 self.__neutron, router.external_network_id)
250 Destroys the VM instance
253 # Cleanup floating IPs
254 for name, floating_ip in self.__floating_ip_dict.items():
255 logger.info('Deleting Floating IP - ' + floating_ip.ip)
256 neutron_utils.delete_floating_ip(self.__neutron, floating_ip)
258 self.__floating_ip_dict = dict()
261 for name, port in self.__ports:
262 logger.info('Deleting Port with ID - %s ', port.id)
263 neutron_utils.delete_port(self.__neutron, port)
265 self.__ports = list()
269 for volume_rec in self.__vm.volume_ids:
270 cinder = cinder_utils.cinder_client(self._os_creds)
271 volume = cinder_utils.get_volume_by_id(
272 cinder, volume_rec['id'])
274 vm = nova_utils.detach_volume(
275 self._nova, self.__neutron, self.__vm, volume,
281 'Timeout waiting to detach volume %s', volume.name)
283 logger.warn('Unable to detach volume with ID - [%s]',
288 'Deleting VM instance - ' + self.instance_settings.name)
291 nova_utils.delete_vm_instance(self._nova, self.__vm)
292 except NotFound as e:
293 logger.warn('Instance already deleted - %s', e)
295 # Block until instance cannot be found or returns the status of
297 logger.info('Checking deletion status')
299 if self.vm_deleted(block=True):
301 'VM has been properly deleted VM with name - %s',
302 self.instance_settings.name)
306 'VM not deleted within the timeout period of %s '
307 'seconds', self.instance_settings.vm_delete_timeout)
309 def __query_ports(self, port_settings):
311 Returns the previously configured ports or an empty list if none
313 :param port_settings: A list of PortSetting objects
314 :return: a list of OpenStack port tuples where the first member is the
315 port name and the second is the port object
319 for port_setting in port_settings:
320 port = neutron_utils.get_port(
321 self.__neutron, port_settings=port_setting)
323 ports.append((port_setting.name, port))
327 def __create_ports(self, port_settings):
329 Returns the previously configured ports or creates them if they do not
331 :param port_settings: A list of PortSetting objects
332 :return: a list of OpenStack port tuples where the first member is the
333 port name and the second is the port object
337 for port_setting in port_settings:
338 port = neutron_utils.get_port(
339 self.__neutron, port_settings=port_setting)
341 port = neutron_utils.create_port(
342 self.__neutron, self._os_creds, port_setting)
344 ports.append((port_setting.name, port))
348 def get_os_creds(self):
350 Returns the OpenStack credentials used to create these objects
351 :return: the credentials
353 return self._os_creds
355 def get_vm_inst(self):
357 Returns the latest version of this server object from OpenStack
358 :return: Server object
360 return nova_utils.get_server_object_by_id(
361 self._nova, self.__neutron, self.__vm.id)
363 def get_console_output(self):
365 Returns the vm console object for parsing logs
366 :return: the console output object
368 return nova_utils.get_server_console_output(self._nova, self.__vm)
370 def get_port_ip(self, port_name, subnet_name=None):
372 Returns the first IP for the port corresponding with the port_name
373 parameter when subnet_name is None else returns the IP address that
374 corresponds to the subnet_name parameter
375 :param port_name: the name of the port from which to return the IP
376 :param subnet_name: the name of the subnet attached to this IP
377 :return: the IP or None if not found
379 port = self.get_port_by_name(port_name)
382 subnet = neutron_utils.get_subnet(
383 self.__neutron, subnet_name=subnet_name)
385 logger.warning('Cannot retrieve port IP as subnet could '
386 'not be located with name - %s',
389 for fixed_ip in port.ips:
390 if fixed_ip['subnet_id'] == subnet.id:
391 return fixed_ip['ip_address']
393 if port.ips and len(port.ips) > 0:
394 return port.ips[0]['ip_address']
397 def get_port_mac(self, port_name):
399 Returns the first IP for the port corresponding with the port_name
401 TODO - Add in the subnet as an additional parameter as a port may have
403 :param port_name: the name of the port from which to return the IP
404 :return: the IP or None if not found
406 port = self.get_port_by_name(port_name)
408 return port.mac_address
411 def get_port_by_name(self, port_name):
413 Retrieves the OpenStack port object by its given name
414 :param port_name: the name of the port
415 :return: the OpenStack port object or None if not exists
417 for key, port in self.__ports:
420 logger.warning('Cannot find port with name - ' + port_name)
423 def get_vm_info(self):
425 Returns a dictionary of a VMs info as returned by OpenStack
428 return nova_utils.get_server_info(self._nova, self.__vm)
430 def __get_first_provisioning_floating_ip(self):
432 Returns the first floating IP tagged with the Floating IP name if
433 exists else the first one found
436 for floating_ip_setting in self.instance_settings.floating_ip_settings:
437 if floating_ip_setting.provisioning:
438 fip = self.__floating_ip_dict.get(floating_ip_setting.name)
441 elif len(self.__floating_ip_dict) > 0:
442 for key, fip in self.__floating_ip_dict.items():
445 # When cannot be found above
446 if len(self.__floating_ip_dict) > 0:
447 for key, fip in self.__floating_ip_dict.items():
450 def apply_ansible_playbook(self, pb_file_loc, variables=None,
453 Applies a playbook to a VM
454 :param pb_file_loc: the file location of the playbook to be applied
455 :param variables: a dict() of substitution values required by the
457 :param fip_name: the name of the floating IP to use for applying the
458 playbook (default - will take the first)
459 :return: the return value from ansible
461 return ansible_utils.apply_playbook(
462 pb_file_loc, [self.get_floating_ip(fip_name=fip_name).ip],
463 self.get_image_user(),
464 ssh_priv_key_file_path=self.keypair_settings.private_filepath,
465 variables=variables, proxy_setting=self._os_creds.proxy_settings)
467 def get_image_user(self):
469 Returns the instance sudo_user if it has been configured in the
470 instance_settings else it returns the image_settings.image_user value
472 if self.instance_settings.sudo_user:
473 return self.instance_settings.sudo_user
475 return self.image_settings.image_user
477 def vm_deleted(self, block=False, poll_interval=POLL_INTERVAL):
479 Returns true when the VM status returns the value of
480 expected_status_code or instance retrieval throws a NotFound exception.
481 :param block: When true, thread will block until active or timeout
482 value in seconds has been exceeded (False)
483 :param poll_interval: The polling interval in seconds
487 return self.__vm_status_check(
488 STATUS_DELETED, block,
489 self.instance_settings.vm_delete_timeout, poll_interval)
490 except NotFound as e:
492 "Instance not found when querying status for %s with message "
493 "%s", STATUS_DELETED, e)
496 def vm_active(self, block=False, poll_interval=POLL_INTERVAL):
498 Returns true when the VM status returns the value of the constant
500 :param block: When true, thread will block until active or timeout
501 value in seconds has been exceeded (False)
502 :param poll_interval: The polling interval in seconds
505 if self.__vm_status_check(
506 STATUS_ACTIVE, block, self.instance_settings.vm_boot_timeout,
508 self.__vm = nova_utils.get_server_object_by_id(
509 self._nova, self.__neutron, self.__vm.id)
513 def __vm_status_check(self, expected_status_code, block, timeout,
516 Returns true when the VM status returns the value of
518 :param expected_status_code: instance status evaluated with this
520 :param block: When true, thread will block until active or timeout
521 value in seconds has been exceeded (False)
522 :param timeout: The timeout value
523 :param poll_interval: The polling interval in seconds
526 # sleep and wait for VM status change
530 return self.__status(expected_status_code)
532 while timeout > time.time() - start:
533 status = self.__status(expected_status_code)
535 logger.info('VM is - ' + expected_status_code)
538 logger.debug('Retry querying VM status in ' + str(
539 poll_interval) + ' seconds')
540 time.sleep(poll_interval)
541 logger.debug('VM status query timeout in ' + str(
542 timeout - (time.time() - start)))
545 'Timeout checking for VM status for ' + expected_status_code)
548 def __status(self, expected_status_code):
550 Returns True when active else False
551 :param expected_status_code: instance status evaluated with this string
556 if expected_status_code == STATUS_DELETED:
561 status = nova_utils.get_server_status(self._nova, self.__vm)
563 logger.warning('Cannot find instance with id - ' + self.__vm.id)
566 if status == 'ERROR':
567 raise VmInstanceCreationError(
568 'Instance had an error during deployment')
570 'Instance status [%s] is - %s', self.instance_settings.name,
572 return status == expected_status_code
574 def vm_ssh_active(self, user_override=None, password=None, block=False,
575 timeout=None, poll_interval=POLL_INTERVAL):
577 Returns true when the VM can be accessed via SSH
578 :param user_override: overrides the user with which to create the
580 :param password: overrides the use of a password instead of a private
581 key with which to create the connection
582 :param block: When true, thread will block until active or timeout
583 value in seconds has been exceeded (False)
584 :param timeout: the number of seconds to retry obtaining the connection
585 and overrides the ssh_connect_timeout member of the
586 self.instance_settings object
587 :param poll_interval: The polling interval
590 # sleep and wait for VM status change
591 logger.info('Checking if VM is active')
594 timeout = self.instance_settings.ssh_connect_timeout
596 if self.vm_active(block=True):
600 start = time.time() - timeout
602 while timeout > time.time() - start:
603 status = self.__ssh_active(
604 user_override=user_override, password=password)
606 logger.info('SSH is active for VM instance')
609 logger.debug('Retry SSH connection in ' + str(
610 poll_interval) + ' seconds')
611 time.sleep(poll_interval)
612 logger.debug('SSH connection timeout in ' + str(
613 timeout - (time.time() - start)))
615 logger.error('Timeout attempting to connect with VM via SSH')
618 def __ssh_active(self, user_override=None, password=None):
620 Returns True when can create a SSH session else False
623 if len(self.__floating_ip_dict) > 0:
624 ssh = self.ssh_client(
625 user_override=user_override, password=password)
631 def cloud_init_complete(self, block=False, poll_interval=POLL_INTERVAL):
633 Returns true when the VM's cloud-init routine has completed.
634 Note: this is currently done via SSH, therefore, if this instance does
635 not have a Floating IP or a running SSH server, this routine
636 will always return False or raise an Exception
637 :param block: When true, thread will block until active or timeout
638 value in seconds has been exceeded (False)
639 :param poll_interval: The polling interval
642 # sleep and wait for VM status change
643 logger.info('Checking if cloud-init has completed')
645 timeout = self.instance_settings.cloud_init_timeout
647 if self.vm_active(block=True) and self.vm_ssh_active(block=True):
651 start = time.time() - timeout
653 while timeout > time.time() - start:
654 status = self.__cloud_init_complete()
656 logger.info('cloud-init complete for VM instance')
659 logger.debug('Retry cloud-init query in ' + str(
660 poll_interval) + ' seconds')
661 time.sleep(poll_interval)
662 logger.debug('cloud-init complete timeout in ' + str(
663 timeout - (time.time() - start)))
665 logger.error('Timeout waiting for cloud-init to complete')
668 def __cloud_init_complete(self):
670 Returns True when can create a SSH session else False
673 if len(self.__floating_ip_dict) > 0:
674 ssh = self.ssh_client()
676 stdin1, stdout1, sterr1 = ssh.exec_command(
677 'ls -l /var/lib/cloud/instance/boot-finished')
678 return stdout1.channel.recv_exit_status() == 0
681 def get_floating_ip(self, fip_name=None):
683 Returns the floating IP object byt name if found, else the first known,
685 :param fip_name: the name of the floating IP to return
686 :return: the SSH client or None
688 if fip_name and self.__floating_ip_dict.get(fip_name):
689 return self.__floating_ip_dict.get(fip_name)
691 return self.__get_first_provisioning_floating_ip()
693 def ssh_client(self, fip_name=None, user_override=None, password=None):
695 Returns an SSH client using the name or the first known floating IP if
697 :param fip_name: the name of the floating IP to return
698 :param user_override: the username to use instead of the default
699 :param password: the password to use instead of the private key
700 :return: the SSH client or None
702 fip = self.get_floating_ip(fip_name)
704 ansible_user = self.get_image_user()
706 ansible_user = user_override
711 private_key = self.keypair_settings.private_filepath
714 return ansible_utils.ssh_client(
715 self.__get_first_provisioning_floating_ip().ip,
717 private_key_filepath=private_key,
719 proxy_settings=self._os_creds.proxy_settings)
721 FloatingIPAllocationError(
722 'Cannot return an SSH client. No Floating IP configured')
724 def add_security_group(self, security_group):
726 Adds a security group to this VM. Call will block until VM is active.
727 :param security_group: the SNAPS SecurityGroup domain object
728 :return True if successful else False
730 self.vm_active(block=True)
732 if not security_group:
733 logger.warning('Security group object is None, cannot add')
737 nova_utils.add_security_group(self._nova, self.get_vm_inst(),
740 except NotFound as e:
741 logger.warning('Security group not added - ' + str(e))
744 def remove_security_group(self, security_group):
746 Removes a security group to this VM. Call will block until VM is active
747 :param security_group: the OpenStack security group object
748 :return True if successful else False
750 self.vm_active(block=True)
752 if not security_group:
753 logger.warning('Security group object is None, cannot remove')
757 nova_utils.remove_security_group(self._nova, self.get_vm_inst(),
760 except NotFound as e:
761 logger.warning('Security group not removed - ' + str(e))
764 def reboot(self, reboot_type=RebootType.soft):
767 :param reboot_type: instance of
768 snaps.openstack.utils.nova_utils.RebootType
772 nova_utils.reboot_server(
773 self._nova, self.__vm, reboot_type=reboot_type)
776 def generate_creator(os_creds, vm_inst, image_config, keypair_config=None):
778 Initializes an OpenStackVmInstance object
779 :param os_creds: the OpenStack credentials
780 :param vm_inst: the SNAPS-OO VmInst domain object
781 :param image_config: the associated ImageConfig object
782 :param keypair_config: the associated KeypairConfig object (optional)
783 :return: an initialized OpenStackVmInstance object
785 nova = nova_utils.nova_client(os_creds)
786 neutron = neutron_utils.neutron_client(os_creds)
787 derived_inst_config = settings_utils.create_vm_inst_config(
788 nova, neutron, vm_inst)
790 derived_inst_creator = OpenStackVmInstance(
791 os_creds, derived_inst_config, image_config, keypair_config)
792 derived_inst_creator.initialize()
793 return derived_inst_creator
796 class VmInstanceSettings(VmInstanceConfig):
798 Deprecated, use snaps.config.vm_inst.VmInstanceConfig instead
800 def __init__(self, **kwargs):
801 from warnings import warn
802 warn('Use snaps.config.vm_inst.VmInstanceConfig instead',
804 super(self.__class__, self).__init__(**kwargs)
807 class FloatingIpSettings(FloatingIpConfig):
809 Deprecated, use snaps.config.vm_inst.FloatingIpConfig instead
811 def __init__(self, **kwargs):
812 from warnings import warn
813 warn('Use snaps.config.vm_inst.FloatingIpConfig instead',
815 super(self.__class__, self).__init__(**kwargs)
818 class VmInstanceCreationError(Exception):
820 Exception to be thrown when an VM instance cannot be created
824 class FloatingIPAllocationError(Exception):
826 Exception to be thrown when an VM instance cannot allocate a floating IP