eb4ade37908dd212fd74f6d42ad109656e6bb895
[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, self.__keystone, router_name=router_name,
243             project_name=self._os_creds.project_name)
244         if router and router.external_network_id:
245             network = neutron_utils.get_network_by_id(
246                 self.__neutron, router.external_network_id)
247             if network:
248                 return network.name
249         return None
250
251     def clean(self):
252         """
253         Destroys the VM instance
254         """
255
256         # Cleanup floating IPs
257         for name, floating_ip in self.__floating_ip_dict.items():
258             logger.info('Deleting Floating IP - ' + floating_ip.ip)
259             neutron_utils.delete_floating_ip(self.__neutron, floating_ip)
260
261         self.__floating_ip_dict = dict()
262
263         # Cleanup ports
264         for name, port in self.__ports:
265             logger.info('Deleting Port with ID - %s ', port.id)
266             neutron_utils.delete_port(self.__neutron, port)
267
268         self.__ports = list()
269
270         if self.__vm:
271             # Detach Volume
272             for volume_rec in self.__vm.volume_ids:
273                 cinder = cinder_utils.cinder_client(self._os_creds)
274                 volume = cinder_utils.get_volume_by_id(
275                     cinder, volume_rec['id'])
276                 if volume:
277                     vm = nova_utils.detach_volume(
278                         self._nova, self.__neutron, self.__keystone, self.__vm,
279                         volume, self._os_creds.project_name)
280                     if vm:
281                         self.__vm = vm
282                     else:
283                         logger.warn(
284                             'Timeout waiting to detach volume %s', volume.name)
285                 else:
286                     logger.warn('Unable to detach volume with ID - [%s]',
287                                 volume_rec['id'])
288
289             # Cleanup VM
290             logger.info(
291                 'Deleting VM instance - ' + self.instance_settings.name)
292
293             try:
294                 nova_utils.delete_vm_instance(self._nova, self.__vm)
295             except NotFound as e:
296                 logger.warn('Instance already deleted - %s', e)
297
298             # Block until instance cannot be found or returns the status of
299             # DELETED
300             logger.info('Checking deletion status')
301
302             if self.vm_deleted(block=True):
303                 logger.info(
304                     'VM has been properly deleted VM with name - %s',
305                     self.instance_settings.name)
306                 self.__vm = None
307             else:
308                 logger.error(
309                     'VM not deleted within the timeout period of %s '
310                     'seconds', self.instance_settings.vm_delete_timeout)
311
312     def __query_ports(self, port_settings):
313         """
314         Returns the previously configured ports or an empty list if none
315         exist
316         :param port_settings: A list of PortSetting objects
317         :return: a list of OpenStack port tuples where the first member is the
318                  port name and the second is the port object
319         """
320         ports = list()
321
322         for port_setting in port_settings:
323             port = neutron_utils.get_port(
324                 self.__neutron, self.__keystone, port_settings=port_setting,
325                 project_name=self._os_creds.project_name)
326             if port:
327                 ports.append((port_setting.name, port))
328
329         return ports
330
331     def __create_ports(self, port_settings):
332         """
333         Returns the previously configured ports or creates them if they do not
334         exist
335         :param port_settings: A list of PortSetting objects
336         :return: a list of OpenStack port tuples where the first member is the
337                  port name and the second is the port object
338         """
339         ports = list()
340
341         for port_setting in port_settings:
342             port = neutron_utils.get_port(
343                 self.__neutron, self.__keystone, port_settings=port_setting)
344             if not port:
345                 port = neutron_utils.create_port(
346                     self.__neutron, self._os_creds, port_setting)
347                 if port:
348                     ports.append((port_setting.name, port))
349
350         return ports
351
352     def get_os_creds(self):
353         """
354         Returns the OpenStack credentials used to create these objects
355         :return: the credentials
356         """
357         return self._os_creds
358
359     def get_vm_inst(self):
360         """
361         Returns the latest version of this server object from OpenStack
362         :return: Server object
363         """
364         return nova_utils.get_server_object_by_id(
365             self._nova, self.__neutron, self.__keystone, self.__vm.id,
366             self._os_creds.project_name)
367
368     def get_console_output(self):
369         """
370         Returns the vm console object for parsing logs
371         :return: the console output object
372         """
373         return nova_utils.get_server_console_output(self._nova, self.__vm)
374
375     def get_port_ip(self, port_name, subnet_name=None):
376         """
377         Returns the first IP for the port corresponding with the port_name
378         parameter when subnet_name is None else returns the IP address that
379         corresponds to the subnet_name parameter
380         :param port_name: the name of the port from which to return the IP
381         :param subnet_name: the name of the subnet attached to this IP
382         :return: the IP or None if not found
383         """
384         port = self.get_port_by_name(port_name)
385         if port:
386             if subnet_name:
387                 subnet = neutron_utils.get_subnet(
388                     self.__neutron, subnet_name=subnet_name)
389                 if not subnet:
390                     logger.warning('Cannot retrieve port IP as subnet could '
391                                    'not be located with name - %s',
392                                    subnet_name)
393                     return None
394                 for fixed_ip in port.ips:
395                     if fixed_ip['subnet_id'] == subnet.id:
396                         return fixed_ip['ip_address']
397             else:
398                 if port.ips and len(port.ips) > 0:
399                     return port.ips[0]['ip_address']
400         return None
401
402     def get_port_mac(self, port_name):
403         """
404         Returns the first IP for the port corresponding with the port_name
405         parameter
406         TODO - Add in the subnet as an additional parameter as a port may have
407         multiple fixed_ips
408         :param port_name: the name of the port from which to return the IP
409         :return: the IP or None if not found
410         """
411         port = self.get_port_by_name(port_name)
412         if port:
413             return port.mac_address
414         return None
415
416     def get_port_by_name(self, port_name):
417         """
418         Retrieves the OpenStack port object by its given name
419         :param port_name: the name of the port
420         :return: the OpenStack port object or None if not exists
421         """
422         for key, port in self.__ports:
423             if key == port_name:
424                 return port
425         logger.warning('Cannot find port with name - ' + port_name)
426         return None
427
428     def get_vm_info(self):
429         """
430         Returns a dictionary of a VMs info as returned by OpenStack
431         :return: a dict()
432         """
433         return nova_utils.get_server_info(self._nova, self.__vm)
434
435     def __get_first_provisioning_floating_ip(self):
436         """
437         Returns the first floating IP tagged with the Floating IP name if
438         exists else the first one found
439         :return:
440         """
441         for floating_ip_setting in self.instance_settings.floating_ip_settings:
442             if floating_ip_setting.provisioning:
443                 fip = self.__floating_ip_dict.get(floating_ip_setting.name)
444                 if fip:
445                     return fip
446                 elif len(self.__floating_ip_dict) > 0:
447                     for key, fip in self.__floating_ip_dict.items():
448                         return fip
449
450         # When cannot be found above
451         if len(self.__floating_ip_dict) > 0:
452             for key, fip in self.__floating_ip_dict.items():
453                 return fip
454
455     def apply_ansible_playbook(self, pb_file_loc, variables=None,
456                                fip_name=None):
457         """
458         Applies a playbook to a VM
459         :param pb_file_loc: the file location of the playbook to be applied
460         :param variables: a dict() of substitution values required by the
461                           playbook
462         :param fip_name: the name of the floating IP to use for applying the
463                          playbook (default - will take the first)
464         :return: the return value from ansible
465         """
466         return ansible_utils.apply_playbook(
467             pb_file_loc, [self.get_floating_ip(fip_name=fip_name).ip],
468             self.get_image_user(),
469             ssh_priv_key_file_path=self.keypair_settings.private_filepath,
470             variables=variables, proxy_setting=self._os_creds.proxy_settings)
471
472     def get_image_user(self):
473         """
474         Returns the instance sudo_user if it has been configured in the
475         instance_settings else it returns the image_settings.image_user value
476         """
477         if self.instance_settings.sudo_user:
478             return self.instance_settings.sudo_user
479         else:
480             return self.image_settings.image_user
481
482     def vm_deleted(self, block=False, poll_interval=POLL_INTERVAL):
483         """
484         Returns true when the VM status returns the value of
485         expected_status_code or instance retrieval throws a NotFound exception.
486         :param block: When true, thread will block until active or timeout
487                       value in seconds has been exceeded (False)
488         :param poll_interval: The polling interval in seconds
489         :return: T/F
490         """
491         try:
492             return self.__vm_status_check(
493                 STATUS_DELETED, block,
494                 self.instance_settings.vm_delete_timeout, poll_interval)
495         except NotFound as e:
496             logger.debug(
497                 "Instance not found when querying status for %s with message "
498                 "%s", STATUS_DELETED, e)
499             return True
500
501     def vm_active(self, block=False, poll_interval=POLL_INTERVAL):
502         """
503         Returns true when the VM status returns the value of the constant
504         STATUS_ACTIVE
505         :param block: When true, thread will block until active or timeout
506                       value in seconds has been exceeded (False)
507         :param poll_interval: The polling interval in seconds
508         :return: T/F
509         """
510         if self.__vm_status_check(
511                 STATUS_ACTIVE, block, self.instance_settings.vm_boot_timeout,
512                 poll_interval):
513             self.__vm = nova_utils.get_server_object_by_id(
514                 self._nova, self.__neutron, self.__keystone, self.__vm.id,
515                 self._os_creds.project_name)
516             return True
517         return False
518
519     def __vm_status_check(self, expected_status_code, block, timeout,
520                           poll_interval):
521         """
522         Returns true when the VM status returns the value of
523         expected_status_code
524         :param expected_status_code: instance status evaluated with this
525                                      string value
526         :param block: When true, thread will block until active or timeout
527                       value in seconds has been exceeded (False)
528         :param timeout: The timeout value
529         :param poll_interval: The polling interval in seconds
530         :return: T/F
531         """
532         # sleep and wait for VM status change
533         if block:
534             start = time.time()
535         else:
536             return self.__status(expected_status_code)
537
538         while timeout > time.time() - start:
539             status = self.__status(expected_status_code)
540             if status:
541                 logger.info('VM is - ' + expected_status_code)
542                 return True
543
544             logger.debug('Retry querying VM status in ' + str(
545                 poll_interval) + ' seconds')
546             time.sleep(poll_interval)
547             logger.debug('VM status query timeout in ' + str(
548                 timeout - (time.time() - start)))
549
550         logger.error(
551             'Timeout checking for VM status for ' + expected_status_code)
552         return False
553
554     def __status(self, expected_status_code):
555         """
556         Returns True when active else False
557         :param expected_status_code: instance status evaluated with this string
558                                      value
559         :return: T/F
560         """
561         if not self.__vm:
562             if expected_status_code == STATUS_DELETED:
563                 return True
564             else:
565                 return False
566
567         status = nova_utils.get_server_status(self._nova, self.__vm)
568         if not status:
569             logger.warning('Cannot find instance with id - ' + self.__vm.id)
570             return False
571
572         if status == 'ERROR':
573             raise VmInstanceCreationError(
574                 'Instance had an error during deployment')
575         logger.debug(
576             'Instance status [%s] is - %s', self.instance_settings.name,
577             status)
578         return status == expected_status_code
579
580     def vm_ssh_active(self, user_override=None, password=None, block=False,
581                       timeout=None, poll_interval=POLL_INTERVAL):
582         """
583         Returns true when the VM can be accessed via SSH
584         :param user_override: overrides the user with which to create the
585                               connection
586         :param password: overrides the use of a password instead of a private
587                          key with which to create the connection
588         :param block: When true, thread will block until active or timeout
589                       value in seconds has been exceeded (False)
590         :param timeout: the number of seconds to retry obtaining the connection
591                         and overrides the ssh_connect_timeout member of the
592                         self.instance_settings object
593         :param poll_interval: The polling interval
594         :return: T/F
595         """
596         # sleep and wait for VM status change
597         logger.info('Checking if VM is active')
598
599         if not timeout:
600             timeout = self.instance_settings.ssh_connect_timeout
601
602         if self.vm_active(block=True):
603             if block:
604                 start = time.time()
605             else:
606                 start = time.time() - timeout
607
608             while timeout > time.time() - start:
609                 status = self.__ssh_active(
610                     user_override=user_override, password=password)
611                 if status:
612                     logger.info('SSH is active for VM instance')
613                     return True
614
615                 logger.debug('Retry SSH connection in ' + str(
616                     poll_interval) + ' seconds')
617                 time.sleep(poll_interval)
618                 logger.debug('SSH connection timeout in ' + str(
619                     timeout - (time.time() - start)))
620
621         logger.error('Timeout attempting to connect with VM via SSH')
622         return False
623
624     def __ssh_active(self, user_override=None, password=None):
625         """
626         Returns True when can create a SSH session else False
627         :return: T/F
628         """
629         if len(self.__floating_ip_dict) > 0:
630             ssh = self.ssh_client(
631                 user_override=user_override, password=password)
632             if ssh:
633                 ssh.close()
634                 return True
635         return False
636
637     def cloud_init_complete(self, block=False, poll_interval=POLL_INTERVAL):
638         """
639         Returns true when the VM's cloud-init routine has completed.
640         Note: this is currently done via SSH, therefore, if this instance does
641               not have a Floating IP or a running SSH server, this routine
642               will always return False or raise an Exception
643         :param block: When true, thread will block until active or timeout
644                       value in seconds has been exceeded (False)
645         :param poll_interval: The polling interval
646         :return: T/F
647         """
648         # sleep and wait for VM status change
649         logger.info('Checking if cloud-init has completed')
650
651         timeout = self.instance_settings.cloud_init_timeout
652
653         if self.vm_active(block=True) and self.vm_ssh_active(block=True):
654             if block:
655                 start = time.time()
656             else:
657                 start = time.time() - timeout
658
659             while timeout > time.time() - start:
660                 status = self.__cloud_init_complete()
661                 if status:
662                     logger.info('cloud-init complete for VM instance')
663                     return True
664
665                 logger.debug('Retry cloud-init query in ' + str(
666                     poll_interval) + ' seconds')
667                 time.sleep(poll_interval)
668                 logger.debug('cloud-init complete timeout in ' + str(
669                     timeout - (time.time() - start)))
670
671         logger.error('Timeout waiting for cloud-init to complete')
672         return False
673
674     def __cloud_init_complete(self):
675         """
676         Returns True when can create a SSH session else False
677         :return: T/F
678         """
679         if len(self.__floating_ip_dict) > 0:
680             ssh = self.ssh_client()
681             if ssh:
682                 stdin1, stdout1, sterr1 = ssh.exec_command(
683                     'ls -l /var/lib/cloud/instance/boot-finished')
684                 return stdout1.channel.recv_exit_status() == 0
685         return False
686
687     def get_floating_ip(self, fip_name=None):
688         """
689         Returns the floating IP object byt name if found, else the first known,
690         else None
691         :param fip_name: the name of the floating IP to return
692         :return: the SSH client or None
693         """
694         if fip_name and self.__floating_ip_dict.get(fip_name):
695             return self.__floating_ip_dict.get(fip_name)
696         else:
697             return self.__get_first_provisioning_floating_ip()
698
699     def ssh_client(self, fip_name=None, user_override=None, password=None):
700         """
701         Returns an SSH client using the name or the first known floating IP if
702         exists, else None
703         :param fip_name: the name of the floating IP to return
704         :param user_override: the username to use instead of the default
705         :param password: the password to use instead of the private key
706         :return: the SSH client or None
707         """
708         fip = self.get_floating_ip(fip_name)
709
710         ansible_user = self.get_image_user()
711         if user_override:
712             ansible_user = user_override
713
714         if password:
715             private_key = None
716         else:
717             private_key = self.keypair_settings.private_filepath
718
719         if fip:
720             return ansible_utils.ssh_client(
721                 self.__get_first_provisioning_floating_ip().ip,
722                 ansible_user,
723                 private_key_filepath=private_key,
724                 password=password,
725                 proxy_settings=self._os_creds.proxy_settings)
726         else:
727             FloatingIPAllocationError(
728                 'Cannot return an SSH client. No Floating IP configured')
729
730     def add_security_group(self, security_group):
731         """
732         Adds a security group to this VM. Call will block until VM is active.
733         :param security_group: the SNAPS SecurityGroup domain object
734         :return True if successful else False
735         """
736         self.vm_active(block=True)
737
738         if not security_group:
739             logger.warning('Security group object is None, cannot add')
740             return False
741
742         try:
743             nova_utils.add_security_group(self._nova, self.get_vm_inst(),
744                                           security_group.name)
745             return True
746         except NotFound as e:
747             logger.warning('Security group not added - ' + str(e))
748             return False
749
750     def remove_security_group(self, security_group):
751         """
752         Removes a security group to this VM. Call will block until VM is active
753         :param security_group: the OpenStack security group object
754         :return True if successful else False
755         """
756         self.vm_active(block=True)
757
758         if not security_group:
759             logger.warning('Security group object is None, cannot remove')
760             return False
761
762         try:
763             nova_utils.remove_security_group(self._nova, self.get_vm_inst(),
764                                              security_group)
765             return True
766         except NotFound as e:
767             logger.warning('Security group not removed - ' + str(e))
768             return False
769
770     def reboot(self, reboot_type=RebootType.soft):
771         """
772         Issues a reboot call
773         :param reboot_type: instance of
774                             snaps.openstack.utils.nova_utils.RebootType
775                             enumeration
776         :return:
777         """
778         nova_utils.reboot_server(
779             self._nova, self.__vm, reboot_type=reboot_type)
780
781
782 def generate_creator(os_creds, vm_inst, image_config, project_name,
783                      keypair_config=None):
784     """
785     Initializes an OpenStackVmInstance object
786     :param os_creds: the OpenStack credentials
787     :param vm_inst: the SNAPS-OO VmInst domain object
788     :param image_config: the associated ImageConfig object
789     :param project_name: the associated project ID
790     :param keypair_config: the associated KeypairConfig object (optional)
791     :return: an initialized OpenStackVmInstance object
792     """
793     nova = nova_utils.nova_client(os_creds)
794     keystone = keystone_utils.keystone_client(os_creds)
795     neutron = neutron_utils.neutron_client(os_creds)
796     derived_inst_config = settings_utils.create_vm_inst_config(
797         nova, keystone, neutron, vm_inst, project_name)
798
799     derived_inst_creator = OpenStackVmInstance(
800         os_creds, derived_inst_config, image_config, keypair_config)
801     derived_inst_creator.initialize()
802     return derived_inst_creator
803
804
805 class VmInstanceSettings(VmInstanceConfig):
806     """
807     Deprecated, use snaps.config.vm_inst.VmInstanceConfig instead
808     """
809     def __init__(self, **kwargs):
810         from warnings import warn
811         warn('Use snaps.config.vm_inst.VmInstanceConfig instead',
812              DeprecationWarning)
813         super(self.__class__, self).__init__(**kwargs)
814
815
816 class FloatingIpSettings(FloatingIpConfig):
817     """
818     Deprecated, use snaps.config.vm_inst.FloatingIpConfig instead
819     """
820     def __init__(self, **kwargs):
821         from warnings import warn
822         warn('Use snaps.config.vm_inst.FloatingIpConfig instead',
823              DeprecationWarning)
824         super(self.__class__, self).__init__(**kwargs)
825
826
827 class VmInstanceCreationError(Exception):
828     """
829     Exception to be thrown when an VM instance cannot be created
830     """
831
832
833 class FloatingIPAllocationError(Exception):
834     """
835     Exception to be thrown when an VM instance cannot allocate a floating IP
836     """