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