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