Changed pattern on how objects lookup themselves by name and project.
[snaps.git] / snaps / openstack / create_instance.py
1 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
2 #                    and others.  All rights reserved.
3 #
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:
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
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.
15 import logging
16 import time
17
18 from novaclient.exceptions import NotFound
19
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
28
29 __author__ = 'spisarski'
30
31 logger = logging.getLogger('create_instance')
32
33 POLL_INTERVAL = 3
34 STATUS_ACTIVE = 'ACTIVE'
35 STATUS_DELETED = 'DELETED'
36
37
38 class OpenStackVmInstance(OpenStackComputeObject):
39     """
40     Class responsible for managing a VM instance in OpenStack
41     """
42
43     def __init__(self, os_creds, instance_settings, image_settings,
44                  keypair_settings=None):
45         """
46         Constructor
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)
51         :raises Exception
52         """
53         super(self.__class__, self).__init__(os_creds)
54
55         self.__neutron = None
56
57         self.instance_settings = instance_settings
58         self.image_settings = image_settings
59         self.keypair_settings = keypair_settings
60
61         self.__floating_ip_dict = dict()
62
63         # Instantiated in self.create()
64         self.__ports = list()
65
66         # Note: this object does not change after the VM becomes active
67         self.__vm = None
68
69     def initialize(self):
70         """
71         Loads the existing VMInst, Port, FloatingIps
72         :return: VMInst domain object
73         """
74         super(self.__class__, self).initialize()
75
76         self.__neutron = neutron_utils.neutron_client(self._os_creds)
77         self.__keystone = keystone_utils.keystone_client(self._os_creds)
78
79         self.__ports = self.__query_ports(self.instance_settings.port_settings)
80         self.__lookup_existing_vm_by_name()
81
82     def create(self, block=False):
83         """
84         Creates a VM instance and associated objects unless they already exist
85         :param block: Thread will block until instance has either become
86                       active, error, or timeout waiting.
87                       Additionally, when True, floating IPs will not be applied
88                       until VM is active.
89         :return: VMInst domain object
90         """
91         self.initialize()
92
93         if len(self.__ports) == 0:
94             self.__ports = self.__create_ports(
95                 self.instance_settings.port_settings)
96         if not self.__vm:
97             self.__create_vm(block)
98
99         return self.__vm
100
101     def __lookup_existing_vm_by_name(self):
102         """
103         Populates the member variables 'self.vm' and 'self.floating_ips' if a
104         VM with the same name already exists
105         within the project
106         """
107         server = nova_utils.get_server(
108             self._nova, self.__neutron, self.__keystone,
109             vm_inst_settings=self.instance_settings)
110         if server:
111             if server.name == self.instance_settings.name:
112                 self.__vm = server
113                 logger.info(
114                     'Found existing machine with name - %s',
115                     self.instance_settings.name)
116
117                 fips = neutron_utils.get_port_floating_ips(
118                     self.__neutron, self.__ports)
119                 for port_id, fip in fips:
120                     settings = self.instance_settings.floating_ip_settings
121                     for fip_setting in settings:
122                         if port_id == fip_setting.port_id:
123                             self.__floating_ip_dict[fip_setting.name] = fip
124                         else:
125                             port = neutron_utils.get_port_by_id(
126                                 self.__neutron, port_id)
127                             if port and port.name == fip_setting.port_name:
128                                 self.__floating_ip_dict[fip_setting.name] = fip
129
130     def __create_vm(self, block=False):
131         """
132         Responsible for creating the VM instance
133         :param block: Thread will block until instance has either become
134                       active, error, or timeout waiting. Floating IPs will be
135                       assigned after active when block=True
136         """
137         glance = glance_utils.glance_client(self._os_creds)
138         self.__vm = nova_utils.create_server(
139             self._nova, self.__keystone, self.__neutron, glance,
140             self.instance_settings, self.image_settings,
141             self._os_creds.project_name, self.keypair_settings)
142         logger.info('Created instance with name - %s',
143                     self.instance_settings.name)
144
145         if block:
146             if not self.vm_active(block=True):
147                 raise VmInstanceCreationError(
148                     'Fatal error, VM did not become ACTIVE within the alloted '
149                     'time')
150
151         # Create server should do this but found it needed to occur here
152         for sec_grp_name in self.instance_settings.security_group_names:
153             if self.vm_active(block=True):
154                 nova_utils.add_security_group(self._nova, self.__vm,
155                                               sec_grp_name)
156             else:
157                 raise VmInstanceCreationError(
158                     'Cannot applying security group with name ' +
159                     sec_grp_name +
160                     ' to VM that did not activate with name - ' +
161                     self.instance_settings.name)
162
163         if self.instance_settings.volume_names:
164             for volume_name in self.instance_settings.volume_names:
165                 cinder = cinder_utils.cinder_client(self._os_creds)
166                 volume = cinder_utils.get_volume(
167                     cinder, volume_name=volume_name)
168
169                 if volume and self.vm_active(block=True):
170                     vm = nova_utils.attach_volume(
171                         self._nova, self.__neutron, self.__keystone, self.__vm,
172                         volume, self._os_creds.project_name)
173
174                     if vm:
175                         self.__vm = vm
176                     else:
177                         logger.warn(
178                             'Volume [%s] attachment timeout ', volume.name)
179                 else:
180                     logger.warn('Unable to attach volume named [%s]',
181                                 volume_name)
182
183         self.__apply_floating_ips()
184
185     def __apply_floating_ips(self):
186         """
187         Applies the configured floating IPs to the necessary ports
188         """
189         port_dict = dict()
190         for key, port in self.__ports:
191             port_dict[key] = port
192
193         # Apply floating IPs
194         for floating_ip_setting in self.instance_settings.floating_ip_settings:
195             self.add_floating_ip(floating_ip_setting)
196
197     def add_floating_ip(self, floating_ip_setting):
198         """
199         Adds a floating IP to a running instance
200         :param floating_ip_setting - the floating IP configuration
201         :return: the floating ip object
202         """
203         port_dict = dict()
204         for key, port in self.__ports:
205             port_dict[key] = port
206
207         # Apply floating IP
208         port = port_dict.get(floating_ip_setting.port_name)
209
210         if not port:
211             raise VmInstanceCreationError(
212                 'Cannot find port object with name - ' +
213                 floating_ip_setting.port_name)
214
215         # Setup Floating IP only if there is a router with an external
216         # gateway
217         ext_gateway = self.__ext_gateway_by_router(
218             floating_ip_setting.router_name)
219         if ext_gateway and self.vm_active(block=True):
220             floating_ip = neutron_utils.create_floating_ip(
221                 self.__neutron, self.__keystone, ext_gateway, port.id)
222             self.__floating_ip_dict[floating_ip_setting.name] = floating_ip
223
224             logger.info(
225                 'Created floating IP %s via router - %s', floating_ip.ip,
226                 floating_ip_setting.router_name)
227
228             return floating_ip
229         else:
230             raise VmInstanceCreationError(
231                 'Unable to add floating IP to port, cannot locate router '
232                 'with an external gateway ')
233
234     def __ext_gateway_by_router(self, router_name):
235         """
236         Returns network name for the external network attached to a router or
237         None if not found
238         :param router_name: The name of the router to lookup
239         :return: the external network name or None
240         """
241         router = neutron_utils.get_router(
242             self.__neutron, router_name=router_name)
243         if router and router.external_network_id:
244             network = neutron_utils.get_network_by_id(
245                 self.__neutron, router.external_network_id)
246             if network:
247                 return network.name
248         return None
249
250     def clean(self):
251         """
252         Destroys the VM instance
253         """
254
255         # Cleanup floating IPs
256         for name, floating_ip in self.__floating_ip_dict.items():
257             logger.info('Deleting Floating IP - ' + floating_ip.ip)
258             neutron_utils.delete_floating_ip(self.__neutron, floating_ip)
259
260         self.__floating_ip_dict = dict()
261
262         # Cleanup ports
263         for name, port in self.__ports:
264             logger.info('Deleting Port with ID - %s ', port.id)
265             neutron_utils.delete_port(self.__neutron, port)
266
267         self.__ports = list()
268
269         if self.__vm:
270             # Detach Volume
271             for volume_rec in self.__vm.volume_ids:
272                 cinder = cinder_utils.cinder_client(self._os_creds)
273                 volume = cinder_utils.get_volume_by_id(
274                     cinder, volume_rec['id'])
275                 if volume:
276                     vm = nova_utils.detach_volume(
277                         self._nova, self.__neutron, self.__keystone, self.__vm,
278                         volume, self._os_creds.project_name)
279                     if vm:
280                         self.__vm = vm
281                     else:
282                         logger.warn(
283                             'Timeout waiting to detach volume %s', volume.name)
284                 else:
285                     logger.warn('Unable to detach volume with ID - [%s]',
286                                 volume_rec['id'])
287
288             # Cleanup VM
289             logger.info(
290                 'Deleting VM instance - ' + self.instance_settings.name)
291
292             try:
293                 nova_utils.delete_vm_instance(self._nova, self.__vm)
294             except NotFound as e:
295                 logger.warn('Instance already deleted - %s', e)
296
297             # Block until instance cannot be found or returns the status of
298             # DELETED
299             logger.info('Checking deletion status')
300
301             if self.vm_deleted(block=True):
302                 logger.info(
303                     'VM has been properly deleted VM with name - %s',
304                     self.instance_settings.name)
305                 self.__vm = None
306             else:
307                 logger.error(
308                     'VM not deleted within the timeout period of %s '
309                     'seconds', self.instance_settings.vm_delete_timeout)
310
311     def __query_ports(self, port_settings):
312         """
313         Returns the previously configured ports or an empty list if none
314         exist
315         :param port_settings: A list of PortSetting objects
316         :return: a list of OpenStack port tuples where the first member is the
317                  port name and the second is the port object
318         """
319         ports = list()
320
321         for port_setting in port_settings:
322             port = neutron_utils.get_port(
323                 self.__neutron, self.__keystone, port_settings=port_setting,
324                 project_name=self._os_creds.project_name)
325             if port:
326                 ports.append((port_setting.name, port))
327
328         return ports
329
330     def __create_ports(self, port_settings):
331         """
332         Returns the previously configured ports or creates them if they do not
333         exist
334         :param port_settings: A list of PortSetting objects
335         :return: a list of OpenStack port tuples where the first member is the
336                  port name and the second is the port object
337         """
338         ports = list()
339
340         for port_setting in port_settings:
341             port = neutron_utils.get_port(
342                 self.__neutron, self.__keystone, port_settings=port_setting)
343             if not port:
344                 port = neutron_utils.create_port(
345                     self.__neutron, self._os_creds, port_setting)
346                 if port:
347                     ports.append((port_setting.name, port))
348
349         return ports
350
351     def get_os_creds(self):
352         """
353         Returns the OpenStack credentials used to create these objects
354         :return: the credentials
355         """
356         return self._os_creds
357
358     def get_vm_inst(self):
359         """
360         Returns the latest version of this server object from OpenStack
361         :return: Server object
362         """
363         return nova_utils.get_server_object_by_id(
364             self._nova, self.__neutron, self.__keystone, self.__vm.id,
365             self._os_creds.project_name)
366
367     def get_console_output(self):
368         """
369         Returns the vm console object for parsing logs
370         :return: the console output object
371         """
372         return nova_utils.get_server_console_output(self._nova, self.__vm)
373
374     def get_port_ip(self, port_name, subnet_name=None):
375         """
376         Returns the first IP for the port corresponding with the port_name
377         parameter when subnet_name is None else returns the IP address that
378         corresponds to the subnet_name parameter
379         :param port_name: the name of the port from which to return the IP
380         :param subnet_name: the name of the subnet attached to this IP
381         :return: the IP or None if not found
382         """
383         port = self.get_port_by_name(port_name)
384         if port:
385             if subnet_name:
386                 subnet = neutron_utils.get_subnet(
387                     self.__neutron, subnet_name=subnet_name)
388                 if not subnet:
389                     logger.warning('Cannot retrieve port IP as subnet could '
390                                    'not be located with name - %s',
391                                    subnet_name)
392                     return None
393                 for fixed_ip in port.ips:
394                     if fixed_ip['subnet_id'] == subnet.id:
395                         return fixed_ip['ip_address']
396             else:
397                 if port.ips and len(port.ips) > 0:
398                     return port.ips[0]['ip_address']
399         return None
400
401     def get_port_mac(self, port_name):
402         """
403         Returns the first IP for the port corresponding with the port_name
404         parameter
405         TODO - Add in the subnet as an additional parameter as a port may have
406         multiple fixed_ips
407         :param port_name: the name of the port from which to return the IP
408         :return: the IP or None if not found
409         """
410         port = self.get_port_by_name(port_name)
411         if port:
412             return port.mac_address
413         return None
414
415     def get_port_by_name(self, port_name):
416         """
417         Retrieves the OpenStack port object by its given name
418         :param port_name: the name of the port
419         :return: the OpenStack port object or None if not exists
420         """
421         for key, port in self.__ports:
422             if key == port_name:
423                 return port
424         logger.warning('Cannot find port with name - ' + port_name)
425         return None
426
427     def get_vm_info(self):
428         """
429         Returns a dictionary of a VMs info as returned by OpenStack
430         :return: a dict()
431         """
432         return nova_utils.get_server_info(self._nova, self.__vm)
433
434     def __get_first_provisioning_floating_ip(self):
435         """
436         Returns the first floating IP tagged with the Floating IP name if
437         exists else the first one found
438         :return:
439         """
440         for floating_ip_setting in self.instance_settings.floating_ip_settings:
441             if floating_ip_setting.provisioning:
442                 fip = self.__floating_ip_dict.get(floating_ip_setting.name)
443                 if fip:
444                     return fip
445                 elif len(self.__floating_ip_dict) > 0:
446                     for key, fip in self.__floating_ip_dict.items():
447                         return fip
448
449         # When cannot be found above
450         if len(self.__floating_ip_dict) > 0:
451             for key, fip in self.__floating_ip_dict.items():
452                 return fip
453
454     def apply_ansible_playbook(self, pb_file_loc, variables=None,
455                                fip_name=None):
456         """
457         Applies a playbook to a VM
458         :param pb_file_loc: the file location of the playbook to be applied
459         :param variables: a dict() of substitution values required by the
460                           playbook
461         :param fip_name: the name of the floating IP to use for applying the
462                          playbook (default - will take the first)
463         :return: the return value from ansible
464         """
465         return ansible_utils.apply_playbook(
466             pb_file_loc, [self.get_floating_ip(fip_name=fip_name).ip],
467             self.get_image_user(),
468             ssh_priv_key_file_path=self.keypair_settings.private_filepath,
469             variables=variables, proxy_setting=self._os_creds.proxy_settings)
470
471     def get_image_user(self):
472         """
473         Returns the instance sudo_user if it has been configured in the
474         instance_settings else it returns the image_settings.image_user value
475         """
476         if self.instance_settings.sudo_user:
477             return self.instance_settings.sudo_user
478         else:
479             return self.image_settings.image_user
480
481     def vm_deleted(self, block=False, poll_interval=POLL_INTERVAL):
482         """
483         Returns true when the VM status returns the value of
484         expected_status_code or instance retrieval throws a NotFound exception.
485         :param block: When true, thread will block until active or timeout
486                       value in seconds has been exceeded (False)
487         :param poll_interval: The polling interval in seconds
488         :return: T/F
489         """
490         try:
491             return self.__vm_status_check(
492                 STATUS_DELETED, block,
493                 self.instance_settings.vm_delete_timeout, poll_interval)
494         except NotFound as e:
495             logger.debug(
496                 "Instance not found when querying status for %s with message "
497                 "%s", STATUS_DELETED, e)
498             return True
499
500     def vm_active(self, block=False, poll_interval=POLL_INTERVAL):
501         """
502         Returns true when the VM status returns the value of the constant
503         STATUS_ACTIVE
504         :param block: When true, thread will block until active or timeout
505                       value in seconds has been exceeded (False)
506         :param poll_interval: The polling interval in seconds
507         :return: T/F
508         """
509         if self.__vm_status_check(
510                 STATUS_ACTIVE, block, self.instance_settings.vm_boot_timeout,
511                 poll_interval):
512             self.__vm = nova_utils.get_server_object_by_id(
513                 self._nova, self.__neutron, self.__keystone, self.__vm.id,
514                 self._os_creds.project_name)
515             return True
516         return False
517
518     def __vm_status_check(self, expected_status_code, block, timeout,
519                           poll_interval):
520         """
521         Returns true when the VM status returns the value of
522         expected_status_code
523         :param expected_status_code: instance status evaluated with this
524                                      string value
525         :param block: When true, thread will block until active or timeout
526                       value in seconds has been exceeded (False)
527         :param timeout: The timeout value
528         :param poll_interval: The polling interval in seconds
529         :return: T/F
530         """
531         # sleep and wait for VM status change
532         if block:
533             start = time.time()
534         else:
535             return self.__status(expected_status_code)
536
537         while timeout > time.time() - start:
538             status = self.__status(expected_status_code)
539             if status:
540                 logger.info('VM is - ' + expected_status_code)
541                 return True
542
543             logger.debug('Retry querying VM status in ' + str(
544                 poll_interval) + ' seconds')
545             time.sleep(poll_interval)
546             logger.debug('VM status query timeout in ' + str(
547                 timeout - (time.time() - start)))
548
549         logger.error(
550             'Timeout checking for VM status for ' + expected_status_code)
551         return False
552
553     def __status(self, expected_status_code):
554         """
555         Returns True when active else False
556         :param expected_status_code: instance status evaluated with this string
557                                      value
558         :return: T/F
559         """
560         if not self.__vm:
561             if expected_status_code == STATUS_DELETED:
562                 return True
563             else:
564                 return False
565
566         status = nova_utils.get_server_status(self._nova, self.__vm)
567         if not status:
568             logger.warning('Cannot find instance with id - ' + self.__vm.id)
569             return False
570
571         if status == 'ERROR':
572             raise VmInstanceCreationError(
573                 'Instance had an error during deployment')
574         logger.debug(
575             'Instance status [%s] is - %s', self.instance_settings.name,
576             status)
577         return status == expected_status_code
578
579     def vm_ssh_active(self, user_override=None, password=None, block=False,
580                       timeout=None, poll_interval=POLL_INTERVAL):
581         """
582         Returns true when the VM can be accessed via SSH
583         :param user_override: overrides the user with which to create the
584                               connection
585         :param password: overrides the use of a password instead of a private
586                          key with which to create the connection
587         :param block: When true, thread will block until active or timeout
588                       value in seconds has been exceeded (False)
589         :param timeout: the number of seconds to retry obtaining the connection
590                         and overrides the ssh_connect_timeout member of the
591                         self.instance_settings object
592         :param poll_interval: The polling interval
593         :return: T/F
594         """
595         # sleep and wait for VM status change
596         logger.info('Checking if VM is active')
597
598         if not timeout:
599             timeout = self.instance_settings.ssh_connect_timeout
600
601         if self.vm_active(block=True):
602             if block:
603                 start = time.time()
604             else:
605                 start = time.time() - timeout
606
607             while timeout > time.time() - start:
608                 status = self.__ssh_active(
609                     user_override=user_override, password=password)
610                 if status:
611                     logger.info('SSH is active for VM instance')
612                     return True
613
614                 logger.debug('Retry SSH connection in ' + str(
615                     poll_interval) + ' seconds')
616                 time.sleep(poll_interval)
617                 logger.debug('SSH connection timeout in ' + str(
618                     timeout - (time.time() - start)))
619
620         logger.error('Timeout attempting to connect with VM via SSH')
621         return False
622
623     def __ssh_active(self, user_override=None, password=None):
624         """
625         Returns True when can create a SSH session else False
626         :return: T/F
627         """
628         if len(self.__floating_ip_dict) > 0:
629             ssh = self.ssh_client(
630                 user_override=user_override, password=password)
631             if ssh:
632                 ssh.close()
633                 return True
634         return False
635
636     def cloud_init_complete(self, block=False, poll_interval=POLL_INTERVAL):
637         """
638         Returns true when the VM's cloud-init routine has completed.
639         Note: this is currently done via SSH, therefore, if this instance does
640               not have a Floating IP or a running SSH server, this routine
641               will always return False or raise an Exception
642         :param block: When true, thread will block until active or timeout
643                       value in seconds has been exceeded (False)
644         :param poll_interval: The polling interval
645         :return: T/F
646         """
647         # sleep and wait for VM status change
648         logger.info('Checking if cloud-init has completed')
649
650         timeout = self.instance_settings.cloud_init_timeout
651
652         if self.vm_active(block=True) and self.vm_ssh_active(block=True):
653             if block:
654                 start = time.time()
655             else:
656                 start = time.time() - timeout
657
658             while timeout > time.time() - start:
659                 status = self.__cloud_init_complete()
660                 if status:
661                     logger.info('cloud-init complete for VM instance')
662                     return True
663
664                 logger.debug('Retry cloud-init query in ' + str(
665                     poll_interval) + ' seconds')
666                 time.sleep(poll_interval)
667                 logger.debug('cloud-init complete timeout in ' + str(
668                     timeout - (time.time() - start)))
669
670         logger.error('Timeout waiting for cloud-init to complete')
671         return False
672
673     def __cloud_init_complete(self):
674         """
675         Returns True when can create a SSH session else False
676         :return: T/F
677         """
678         if len(self.__floating_ip_dict) > 0:
679             ssh = self.ssh_client()
680             if ssh:
681                 stdin1, stdout1, sterr1 = ssh.exec_command(
682                     'ls -l /var/lib/cloud/instance/boot-finished')
683                 return stdout1.channel.recv_exit_status() == 0
684         return False
685
686     def get_floating_ip(self, fip_name=None):
687         """
688         Returns the floating IP object byt name if found, else the first known,
689         else None
690         :param fip_name: the name of the floating IP to return
691         :return: the SSH client or None
692         """
693         if fip_name and self.__floating_ip_dict.get(fip_name):
694             return self.__floating_ip_dict.get(fip_name)
695         else:
696             return self.__get_first_provisioning_floating_ip()
697
698     def ssh_client(self, fip_name=None, user_override=None, password=None):
699         """
700         Returns an SSH client using the name or the first known floating IP if
701         exists, else None
702         :param fip_name: the name of the floating IP to return
703         :param user_override: the username to use instead of the default
704         :param password: the password to use instead of the private key
705         :return: the SSH client or None
706         """
707         fip = self.get_floating_ip(fip_name)
708
709         ansible_user = self.get_image_user()
710         if user_override:
711             ansible_user = user_override
712
713         if password:
714             private_key = None
715         else:
716             private_key = self.keypair_settings.private_filepath
717
718         if fip:
719             return ansible_utils.ssh_client(
720                 self.__get_first_provisioning_floating_ip().ip,
721                 ansible_user,
722                 private_key_filepath=private_key,
723                 password=password,
724                 proxy_settings=self._os_creds.proxy_settings)
725         else:
726             FloatingIPAllocationError(
727                 'Cannot return an SSH client. No Floating IP configured')
728
729     def add_security_group(self, security_group):
730         """
731         Adds a security group to this VM. Call will block until VM is active.
732         :param security_group: the SNAPS SecurityGroup domain object
733         :return True if successful else False
734         """
735         self.vm_active(block=True)
736
737         if not security_group:
738             logger.warning('Security group object is None, cannot add')
739             return False
740
741         try:
742             nova_utils.add_security_group(self._nova, self.get_vm_inst(),
743                                           security_group.name)
744             return True
745         except NotFound as e:
746             logger.warning('Security group not added - ' + str(e))
747             return False
748
749     def remove_security_group(self, security_group):
750         """
751         Removes a security group to this VM. Call will block until VM is active
752         :param security_group: the OpenStack security group object
753         :return True if successful else False
754         """
755         self.vm_active(block=True)
756
757         if not security_group:
758             logger.warning('Security group object is None, cannot remove')
759             return False
760
761         try:
762             nova_utils.remove_security_group(self._nova, self.get_vm_inst(),
763                                              security_group)
764             return True
765         except NotFound as e:
766             logger.warning('Security group not removed - ' + str(e))
767             return False
768
769     def reboot(self, reboot_type=RebootType.soft):
770         """
771         Issues a reboot call
772         :param reboot_type: instance of
773                             snaps.openstack.utils.nova_utils.RebootType
774                             enumeration
775         :return:
776         """
777         nova_utils.reboot_server(
778             self._nova, self.__vm, reboot_type=reboot_type)
779
780
781 def generate_creator(os_creds, vm_inst, image_config, project_name,
782                      keypair_config=None):
783     """
784     Initializes an OpenStackVmInstance object
785     :param os_creds: the OpenStack credentials
786     :param vm_inst: the SNAPS-OO VmInst domain object
787     :param image_config: the associated ImageConfig object
788     :param project_name: the associated project ID
789     :param keypair_config: the associated KeypairConfig object (optional)
790     :return: an initialized OpenStackVmInstance object
791     """
792     nova = nova_utils.nova_client(os_creds)
793     keystone = keystone_utils.keystone_client(os_creds)
794     neutron = neutron_utils.neutron_client(os_creds)
795     derived_inst_config = settings_utils.create_vm_inst_config(
796         nova, keystone, neutron, vm_inst, project_name)
797
798     derived_inst_creator = OpenStackVmInstance(
799         os_creds, derived_inst_config, image_config, keypair_config)
800     derived_inst_creator.initialize()
801     return derived_inst_creator
802
803
804 class VmInstanceSettings(VmInstanceConfig):
805     """
806     Deprecated, use snaps.config.vm_inst.VmInstanceConfig instead
807     """
808     def __init__(self, **kwargs):
809         from warnings import warn
810         warn('Use snaps.config.vm_inst.VmInstanceConfig instead',
811              DeprecationWarning)
812         super(self.__class__, self).__init__(**kwargs)
813
814
815 class FloatingIpSettings(FloatingIpConfig):
816     """
817     Deprecated, use snaps.config.vm_inst.FloatingIpConfig instead
818     """
819     def __init__(self, **kwargs):
820         from warnings import warn
821         warn('Use snaps.config.vm_inst.FloatingIpConfig instead',
822              DeprecationWarning)
823         super(self.__class__, self).__init__(**kwargs)
824
825
826 class VmInstanceCreationError(Exception):
827     """
828     Exception to be thrown when an VM instance cannot be created
829     """
830
831
832 class FloatingIPAllocationError(Exception):
833     """
834     Exception to be thrown when an VM instance cannot allocate a floating IP
835     """