Closing keystone sessions after done with them.
[snaps.git] / snaps / openstack / utils / nova_utils.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
16 import logging
17
18 import enum
19 import os
20 import time
21 from cryptography.hazmat.backends import default_backend
22 from cryptography.hazmat.primitives import serialization
23 from cryptography.hazmat.primitives.asymmetric import rsa
24 from novaclient.client import Client
25 from novaclient.exceptions import NotFound, ClientException
26
27 from snaps import file_utils
28 from snaps.domain.flavor import Flavor
29 from snaps.domain.keypair import Keypair
30 from snaps.domain.project import ComputeQuotas
31 from snaps.domain.vm_inst import VmInst
32 from snaps.openstack.utils import keystone_utils, glance_utils, neutron_utils
33
34 __author__ = 'spisarski'
35
36 logger = logging.getLogger('nova_utils')
37
38 POLL_INTERVAL = 3
39
40 """
41 Utilities for basic OpenStack Nova API calls
42 """
43
44
45 def nova_client(os_creds, session=None):
46     """
47     Instantiates and returns a client for communications with OpenStack's Nova
48     server
49     :param os_creds: The connection credentials to the OpenStack API
50     :param session: the keystone session object (optional)
51     :return: the client object
52     """
53     logger.debug('Retrieving Nova Client')
54     if not session:
55         session = keystone_utils.keystone_session(os_creds)
56
57     return Client(os_creds.compute_api_version,
58                   session=session,
59                   region_name=os_creds.region_name)
60
61
62 def create_server(nova, keystone, neutron, glance, instance_config,
63                   image_config, project_name, keypair_config=None):
64     """
65     Creates a VM instance
66     :param nova: the nova client (required)
67     :param keystone: the keystone client for retrieving projects (required)
68     :param neutron: the neutron client for retrieving ports (required)
69     :param glance: the glance client (required)
70     :param instance_config: the VMInstConfig object (required)
71     :param image_config: the VM's ImageConfig object (required)
72     :param project_name: the associated project name (required)
73     :param keypair_config: the VM's KeypairConfig object (optional)
74     :return: a snaps.domain.VmInst object
75     """
76
77     ports = list()
78
79     for port_setting in instance_config.port_settings:
80         port = neutron_utils.get_port(
81             neutron, keystone, port_settings=port_setting,
82             project_name=project_name)
83         if port:
84             ports.append(port)
85         else:
86             raise Exception('Cannot find port named - ' + port_setting.name)
87     nics = []
88     for port in ports:
89         kv = dict()
90         kv['port-id'] = port.id
91         nics.append(kv)
92
93     logger.info('Creating VM with name - ' + instance_config.name)
94     keypair_name = None
95     if keypair_config:
96         keypair_name = keypair_config.name
97
98     flavor = get_flavor_by_name(nova, instance_config.flavor)
99     if not flavor:
100         raise NovaException(
101             'Flavor not found with name - %s', instance_config.flavor)
102
103     image = glance_utils.get_image(glance, image_settings=image_config)
104     if image:
105         userdata = None
106         if instance_config.userdata:
107             if isinstance(instance_config.userdata, str):
108                 userdata = instance_config.userdata + '\n'
109             elif (isinstance(instance_config.userdata, dict) and
110                   'script_file' in instance_config.userdata):
111                 try:
112                     userdata = file_utils.read_file(
113                         instance_config.userdata['script_file'])
114                 except Exception as e:
115                     logger.warn('error reading userdata file %s - %s',
116                                 instance_config.userdata, e)
117         args = {'name': instance_config.name,
118                 'flavor': flavor,
119                 'image': image,
120                 'nics': nics,
121                 'key_name': keypair_name,
122                 'security_groups':
123                     instance_config.security_group_names,
124                 'userdata': userdata}
125
126         if instance_config.availability_zone:
127             args['availability_zone'] = instance_config.availability_zone
128
129         server = nova.servers.create(**args)
130
131         return __map_os_server_obj_to_vm_inst(
132             neutron, keystone, server, project_name)
133     else:
134         raise NovaException(
135             'Cannot create instance, image cannot be located with name %s',
136             image_config.name)
137
138
139 def get_server(nova, neutron, keystone, vm_inst_settings=None,
140                server_name=None, project_id=None):
141     """
142     Returns a VmInst object for the first server instance found.
143     :param nova: the Nova client
144     :param neutron: the Neutron client
145     :param keystone: the Keystone client
146     :param vm_inst_settings: the VmInstanceConfig object from which to build
147                              the query if not None
148     :param server_name: the server with this name to return if vm_inst_settings
149                         is not None
150     :param project_id: the assocaited project ID
151     :return: a snaps.domain.VmInst object or None if not found
152     """
153     search_opts = dict()
154     if vm_inst_settings:
155         search_opts['name'] = vm_inst_settings.name
156     elif server_name:
157         search_opts['name'] = server_name
158
159     servers = nova.servers.list(search_opts=search_opts)
160     for server in servers:
161         return __map_os_server_obj_to_vm_inst(
162             neutron, keystone, server, project_id)
163
164
165 def get_server_connection(nova, vm_inst_settings=None, server_name=None):
166     """
167     Returns a VmInst object for the first server instance found.
168     :param nova: the Nova client
169     :param vm_inst_settings: the VmInstanceConfig object from which to build
170                              the query if not None
171     :param server_name: the server with this name to return if vm_inst_settings
172                         is not None
173     :return: a snaps.domain.VmInst object or None if not found
174     """
175     search_opts = dict()
176     if vm_inst_settings:
177         search_opts['name'] = vm_inst_settings.name
178     elif server_name:
179         search_opts['name'] = server_name
180
181     servers = nova.servers.list(search_opts=search_opts)
182     for server in servers:
183         return server.links[0]
184
185
186 def __map_os_server_obj_to_vm_inst(neutron, keystone, os_server,
187                                    project_name=None):
188     """
189     Returns a VmInst object for an OpenStack Server object
190     :param neutron: the Neutron client
191     :param keystone: the Keystone client
192     :param os_server: the OpenStack server object
193     :param project_name: the associated project name
194     :return: an equivalent SNAPS-OO VmInst domain object
195     """
196     sec_grp_names = list()
197     # VM must be active for 'security_groups' attr to be initialized
198     if hasattr(os_server, 'security_groups'):
199         for sec_group in os_server.security_groups:
200             if sec_group.get('name'):
201                 sec_grp_names.append(sec_group.get('name'))
202
203     out_ports = list()
204     if len(os_server.networks) > 0:
205         for net_name, ips in os_server.networks.items():
206             network = neutron_utils.get_network(
207                 neutron, keystone, network_name=net_name,
208                 project_name=project_name)
209             ports = neutron_utils.get_ports(neutron, network, ips)
210             for port in ports:
211                 out_ports.append(port)
212
213     volumes = None
214     if hasattr(os_server, 'os-extended-volumes:volumes_attached'):
215         volumes = getattr(os_server, 'os-extended-volumes:volumes_attached')
216
217     return VmInst(
218         name=os_server.name, inst_id=os_server.id,
219         image_id=os_server.image['id'], flavor_id=os_server.flavor['id'],
220         ports=out_ports, keypair_name=os_server.key_name,
221         sec_grp_names=sec_grp_names, volume_ids=volumes,
222         compute_host=os_server._info.get('OS-EXT-SRV-ATTR:host'),
223         availability_zone=os_server._info.get('OS-EXT-AZ:availability_zone'))
224
225
226 def __get_latest_server_os_object(nova, server):
227     """
228     Returns a server with a given id
229     :param nova: the Nova client
230     :param server: the domain VmInst object
231     :return: the list of servers or None if not found
232     """
233     return __get_latest_server_os_object_by_id(nova, server.id)
234
235
236 def __get_latest_server_os_object_by_id(nova, server_id):
237     """
238     Returns a server with a given id
239     :param nova: the Nova client
240     :param server_id: the server's ID
241     :return: the list of servers or None if not found
242     """
243     return nova.servers.get(server_id)
244
245
246 def get_server_status(nova, server):
247     """
248     Returns the a VM instance's status from OpenStack
249     :param nova: the Nova client
250     :param server: the domain VmInst object
251     :return: the VM's string status or None if not founc
252     """
253     server = __get_latest_server_os_object(nova, server)
254     if server:
255         return server.status
256     return None
257
258
259 def get_server_console_output(nova, server):
260     """
261     Returns the console object for parsing VM activity
262     :param nova: the Nova client
263     :param server: the domain VmInst object
264     :return: the console output object or None if server object is not found
265     """
266     server = __get_latest_server_os_object(nova, server)
267     if server:
268         return server.get_console_output()
269     return None
270
271
272 def get_latest_server_object(nova, neutron, keystone, server, project_name):
273     """
274     Returns a server with a given id
275     :param nova: the Nova client
276     :param neutron: the Neutron client
277     :param keystone: the Keystone client
278     :param server: the old server object
279     :param project_name: the associated project name
280     :return: the list of servers or None if not found
281     """
282     server = __get_latest_server_os_object(nova, server)
283     return __map_os_server_obj_to_vm_inst(
284         neutron, keystone, server, project_name)
285
286
287 def get_server_object_by_id(nova, neutron, keystone, server_id,
288                             project_name=None):
289     """
290     Returns a server with a given id
291     :param nova: the Nova client
292     :param neutron: the Neutron client
293     :param keystone: the Keystone client
294     :param server_id: the server's id
295     :param project_name: the associated project name
296     :return: an SNAPS-OO VmInst object or None if not found
297     """
298     server = __get_latest_server_os_object_by_id(nova, server_id)
299     return __map_os_server_obj_to_vm_inst(
300         neutron, keystone, server, project_name)
301
302
303 def get_server_security_group_names(nova, server):
304     """
305     Returns a server with a given id
306     :param nova: the Nova client
307     :param server: the old server object
308     :return: the list of security groups associated with a VM
309     """
310     out = list()
311     os_vm_inst = __get_latest_server_os_object(nova, server)
312     for sec_grp_dict in os_vm_inst.security_groups:
313         out.append(sec_grp_dict['name'])
314     return out
315
316
317 def get_server_info(nova, server):
318     """
319     Returns a dictionary of a VMs info as returned by OpenStack
320     :param nova: the Nova client
321     :param server: the old server object
322     :return: a dict of the info if VM exists else None
323     """
324     vm = __get_latest_server_os_object(nova, server)
325     if vm:
326         return vm._info
327     return None
328
329
330 def reboot_server(nova, server, reboot_type=None):
331     """
332     Returns a dictionary of a VMs info as returned by OpenStack
333     :param nova: the Nova client
334     :param server: the old server object
335     :param reboot_type: Acceptable values 'SOFT', 'HARD'
336                         (api uses SOFT as the default)
337     :return: a dict of the info if VM exists else None
338     """
339     vm = __get_latest_server_os_object(nova, server)
340     if vm:
341         vm.reboot(reboot_type=reboot_type.value)
342     else:
343         raise ServerNotFoundError('Cannot locate server')
344
345
346 def create_keys(key_size=2048):
347     """
348     Generates public and private keys
349     :param key_size: the number of bytes for the key size
350     :return: the cryptography keys
351     """
352     return rsa.generate_private_key(backend=default_backend(),
353                                     public_exponent=65537,
354                                     key_size=key_size)
355
356
357 def public_key_openssh(keys):
358     """
359     Returns the public key for OpenSSH
360     :param keys: the keys generated by create_keys() from cryptography
361     :return: the OpenSSH public key
362     """
363     return keys.public_key().public_bytes(serialization.Encoding.OpenSSH,
364                                           serialization.PublicFormat.OpenSSH)
365
366
367 def save_keys_to_files(keys=None, pub_file_path=None, priv_file_path=None):
368     """
369     Saves the generated RSA generated keys to the filesystem
370     :param keys: the keys to save generated by cryptography
371     :param pub_file_path: the path to the public keys
372     :param priv_file_path: the path to the private keys
373     """
374     if keys:
375         if pub_file_path:
376             # To support '~'
377             pub_expand_file = os.path.expanduser(pub_file_path)
378             pub_dir = os.path.dirname(pub_expand_file)
379
380             if not os.path.isdir(pub_dir):
381                 os.mkdir(pub_dir)
382
383             public_handle = None
384             try:
385                 public_handle = open(pub_expand_file, 'wb')
386                 public_bytes = keys.public_key().public_bytes(
387                     serialization.Encoding.OpenSSH,
388                     serialization.PublicFormat.OpenSSH)
389                 public_handle.write(public_bytes)
390             finally:
391                 if public_handle:
392                     public_handle.close()
393
394             os.chmod(pub_expand_file, 0o600)
395             logger.info("Saved public key to - " + pub_expand_file)
396         if priv_file_path:
397             # To support '~'
398             priv_expand_file = os.path.expanduser(priv_file_path)
399             priv_dir = os.path.dirname(priv_expand_file)
400             if not os.path.isdir(priv_dir):
401                 os.mkdir(priv_dir)
402
403             private_handle = None
404             try:
405                 private_handle = open(priv_expand_file, 'wb')
406                 private_handle.write(
407                     keys.private_bytes(
408                         encoding=serialization.Encoding.PEM,
409                         format=serialization.PrivateFormat.TraditionalOpenSSL,
410                         encryption_algorithm=serialization.NoEncryption()))
411             finally:
412                 if private_handle:
413                     private_handle.close()
414
415             os.chmod(priv_expand_file, 0o600)
416             logger.info("Saved private key to - " + priv_expand_file)
417
418
419 def upload_keypair_file(nova, name, file_path):
420     """
421     Uploads a public key from a file
422     :param nova: the Nova client
423     :param name: the keypair name
424     :param file_path: the path to the public key file
425     :return: the keypair object
426     """
427     fpubkey = None
428     try:
429         with open(os.path.expanduser(file_path), 'rb') as fpubkey:
430             logger.info('Saving keypair to - ' + file_path)
431             return upload_keypair(nova, name, fpubkey.read())
432     finally:
433         if fpubkey:
434             fpubkey.close()
435
436
437 def upload_keypair(nova, name, key):
438     """
439     Uploads a public key from a file
440     :param nova: the Nova client
441     :param name: the keypair name
442     :param key: the public key object
443     :return: the keypair object
444     """
445     logger.info('Creating keypair with name - ' + name)
446     os_kp = nova.keypairs.create(name=name, public_key=key.decode('utf-8'))
447     return Keypair(name=os_kp.name, kp_id=os_kp.id,
448                    public_key=os_kp.public_key, fingerprint=os_kp.fingerprint)
449
450
451 def keypair_exists(nova, keypair_obj):
452     """
453     Returns a copy of the keypair object if found
454     :param nova: the Nova client
455     :param keypair_obj: the keypair object
456     :return: the keypair object or None if not found
457     """
458     try:
459         os_kp = nova.keypairs.get(keypair_obj)
460         return Keypair(name=os_kp.name, kp_id=os_kp.id,
461                        public_key=os_kp.public_key)
462     except:
463         return None
464
465
466 def get_keypair_by_name(nova, name):
467     """
468     Returns a list of all available keypairs
469     :param nova: the Nova client
470     :param name: the name of the keypair to lookup
471     :return: the keypair object or None if not found
472     """
473     keypairs = nova.keypairs.list()
474
475     for keypair in keypairs:
476         if keypair.name == name:
477             return Keypair(name=keypair.name, kp_id=keypair.id,
478                            public_key=keypair.public_key)
479
480     return None
481
482
483 def get_keypair_by_id(nova, kp_id):
484     """
485     Returns a list of all available keypairs
486     :param nova: the Nova client
487     :param kp_id: the ID of the keypair to return
488     :return: the keypair object
489     """
490     keypair = nova.keypairs.get(kp_id)
491     return Keypair(name=keypair.name, kp_id=keypair.id,
492                    public_key=keypair.public_key)
493
494
495 def delete_keypair(nova, key):
496     """
497     Deletes a keypair object from OpenStack
498     :param nova: the Nova client
499     :param key: the SNAPS-OO keypair domain object to delete
500     """
501     logger.debug('Deleting keypair - ' + key.name)
502     nova.keypairs.delete(key.id)
503
504
505 def get_availability_zone_hosts(nova, zone_name='nova'):
506     """
507     Returns the names of all nova active compute servers
508     :param nova: the Nova client
509     :param zone_name: the Nova client
510     :return: a list of compute server names
511     """
512     out = list()
513     zones = nova.availability_zones.list()
514     for zone in zones:
515         if zone.zoneName == zone_name and zone.hosts:
516             for key, host in zone.hosts.items():
517                 if host['nova-compute']['available']:
518                     out.append(zone.zoneName + ':' + key)
519
520     return out
521
522
523 def get_hypervisor_hosts(nova):
524     """
525     Returns the host names of all nova nodes with active hypervisors
526     :param nova: the Nova client
527     :return: a list of hypervisor host names
528     """
529     out = list()
530     hypervisors = nova.hypervisors.list()
531     for hypervisor in hypervisors:
532         if hypervisor.state == "up":
533             out.append(hypervisor.hypervisor_hostname)
534
535     return out
536
537
538 def delete_vm_instance(nova, vm_inst):
539     """
540     Deletes a VM instance
541     :param nova: the nova client
542     :param vm_inst: the snaps.domain.VmInst object
543     """
544     nova.servers.delete(vm_inst.id)
545
546
547 def __get_os_flavor(nova, flavor_id):
548     """
549     Returns to OpenStack flavor object by name
550     :param nova: the Nova client
551     :param flavor_id: the flavor's ID value
552     :return: the OpenStack Flavor object
553     """
554     try:
555         return nova.flavors.get(flavor_id)
556     except NotFound:
557         return None
558
559
560 def get_flavor(nova, flavor):
561     """
562     Returns to OpenStack flavor object by name
563     :param nova: the Nova client
564     :param flavor: the SNAPS flavor domain object
565     :return: the SNAPS Flavor domain object
566     """
567     os_flavor = __get_os_flavor(nova, flavor.id)
568     if os_flavor:
569         return Flavor(
570             name=os_flavor.name, id=os_flavor.id, ram=os_flavor.ram,
571             disk=os_flavor.disk, vcpus=os_flavor.vcpus,
572             ephemeral=os_flavor.ephemeral, swap=os_flavor.swap,
573             rxtx_factor=os_flavor.rxtx_factor, is_public=os_flavor.is_public)
574     try:
575         return nova.flavors.get(flavor.id)
576     except NotFound:
577         return None
578
579
580 def get_flavor_by_id(nova, flavor_id):
581     """
582     Returns to OpenStack flavor object by name
583     :param nova: the Nova client
584     :param flavor_id: the flavor ID value
585     :return: the SNAPS Flavor domain object
586     """
587     os_flavor = __get_os_flavor(nova, flavor_id)
588     if os_flavor:
589         return Flavor(
590             name=os_flavor.name, id=os_flavor.id, ram=os_flavor.ram,
591             disk=os_flavor.disk, vcpus=os_flavor.vcpus,
592             ephemeral=os_flavor.ephemeral, swap=os_flavor.swap,
593             rxtx_factor=os_flavor.rxtx_factor, is_public=os_flavor.is_public)
594
595
596 def __get_os_flavor_by_name(nova, name):
597     """
598     Returns to OpenStack flavor object by name
599     :param nova: the Nova client
600     :param name: the name of the flavor to query
601     :return: OpenStack flavor object
602     """
603     try:
604         return nova.flavors.find(name=name)
605     except NotFound:
606         return None
607
608
609 def get_flavor_by_name(nova, name):
610     """
611     Returns a flavor by name
612     :param nova: the Nova client
613     :param name: the flavor name to return
614     :return: the SNAPS flavor domain object or None if not exists
615     """
616     os_flavor = __get_os_flavor_by_name(nova, name)
617     if os_flavor:
618         return Flavor(
619             name=os_flavor.name, id=os_flavor.id, ram=os_flavor.ram,
620             disk=os_flavor.disk, vcpus=os_flavor.vcpus,
621             ephemeral=os_flavor.ephemeral, swap=os_flavor.swap,
622             rxtx_factor=os_flavor.rxtx_factor, is_public=os_flavor.is_public)
623
624
625 def create_flavor(nova, flavor_settings):
626     """
627     Creates and returns and OpenStack flavor object
628     :param nova: the Nova client
629     :param flavor_settings: the flavor settings
630     :return: the SNAPS flavor domain object
631     """
632     os_flavor = nova.flavors.create(
633         name=flavor_settings.name, flavorid=flavor_settings.flavor_id,
634         ram=flavor_settings.ram, vcpus=flavor_settings.vcpus,
635         disk=flavor_settings.disk, ephemeral=flavor_settings.ephemeral,
636         swap=flavor_settings.swap, rxtx_factor=flavor_settings.rxtx_factor,
637         is_public=flavor_settings.is_public)
638     return Flavor(
639         name=os_flavor.name, id=os_flavor.id, ram=os_flavor.ram,
640         disk=os_flavor.disk, vcpus=os_flavor.vcpus,
641         ephemeral=os_flavor.ephemeral, swap=os_flavor.swap,
642         rxtx_factor=os_flavor.rxtx_factor, is_public=os_flavor.is_public)
643
644
645 def delete_flavor(nova, flavor):
646     """
647     Deletes a flavor
648     :param nova: the Nova client
649     :param flavor: the SNAPS flavor domain object
650     """
651     nova.flavors.delete(flavor.id)
652
653
654 def set_flavor_keys(nova, flavor, metadata):
655     """
656     Sets metadata on the flavor
657     :param nova: the Nova client
658     :param flavor: the SNAPS flavor domain object
659     :param metadata: the metadata to set
660     """
661     os_flavor = __get_os_flavor(nova, flavor.id)
662     if os_flavor:
663         os_flavor.set_keys(metadata)
664
665
666 def get_flavor_keys(nova, flavor):
667     """
668     Sets metadata on the flavor
669     :param nova: the Nova client
670     :param flavor: the SNAPS flavor domain object
671     """
672     os_flavor = __get_os_flavor(nova, flavor.id)
673     if os_flavor:
674         return os_flavor.get_keys()
675
676
677 def add_security_group(nova, vm, security_group_name):
678     """
679     Adds a security group to an existing VM
680     :param nova: the nova client
681     :param vm: the OpenStack server object (VM) to alter
682     :param security_group_name: the name of the security group to add
683     """
684     try:
685         nova.servers.add_security_group(str(vm.id), security_group_name)
686     except ClientException as e:
687         sec_grp_names = get_server_security_group_names(nova, vm)
688         if security_group_name in sec_grp_names:
689             logger.warn('Security group [%s] already added to VM [%s]',
690                         security_group_name, vm.name)
691             return
692
693         logger.error('Unexpected error while adding security group [%s] - %s',
694                      security_group_name, e)
695         raise
696
697
698 def remove_security_group(nova, vm, security_group):
699     """
700     Removes a security group from an existing VM
701     :param nova: the nova client
702     :param vm: the OpenStack server object (VM) to alter
703     :param security_group: the SNAPS SecurityGroup domain object to add
704     """
705     nova.servers.remove_security_group(str(vm.id), security_group.name)
706
707
708 def get_compute_quotas(nova, project_id):
709     """
710     Returns a list of all available keypairs
711     :param nova: the Nova client
712     :param project_id: the project's ID of the quotas to lookup
713     :return: an object of type ComputeQuotas or None if not found
714     """
715     quotas = nova.quotas.get(tenant_id=project_id)
716     if quotas:
717         return ComputeQuotas(quotas)
718
719
720 def update_quotas(nova, project_id, compute_quotas):
721     """
722     Updates the compute quotas for a given project
723     :param nova: the Nova client
724     :param project_id: the project's ID that requires quota updates
725     :param compute_quotas: an object of type ComputeQuotas containing the
726                            values to update
727     :return:
728     """
729     update_values = dict()
730     update_values['metadata_items'] = compute_quotas.metadata_items
731     update_values['cores'] = compute_quotas.cores
732     update_values['instances'] = compute_quotas.instances
733     update_values['injected_files'] = compute_quotas.injected_files
734     update_values['injected_file_content_bytes'] = (
735         compute_quotas.injected_file_content_bytes)
736     update_values['ram'] = compute_quotas.ram
737     update_values['fixed_ips'] = compute_quotas.fixed_ips
738     update_values['key_pairs'] = compute_quotas.key_pairs
739
740     return nova.quotas.update(project_id, **update_values)
741
742
743 def attach_volume(nova, neutron, keystone, server, volume, project_name,
744                   timeout=120):
745     """
746     Attaches a volume to a server. When the timeout parameter is used, a VmInst
747     object with the proper volume updates is returned unless it has not been
748     updated in the allotted amount of time then an Exception will be raised.
749     :param nova: the nova client
750     :param neutron: the neutron client
751     :param keystone: the neutron client
752     :param server: the VMInst domain object
753     :param volume: the Volume domain object
754     :param project_name: the associated project name
755     :param timeout: denotes the amount of time to block to determine if the
756                     has been properly attached.
757     :return: updated VmInst object
758     """
759     nova.volumes.create_server_volume(server.id, volume.id)
760
761     start_time = time.time()
762     while time.time() < start_time + timeout:
763         vm = get_server_object_by_id(
764             nova, neutron, keystone, server.id, project_name)
765         for vol_dict in vm.volume_ids:
766             if volume.id == vol_dict['id']:
767                 return vm
768         time.sleep(POLL_INTERVAL)
769
770     raise NovaException(
771         'Attach failed on volume - {} and server - {}'.format(
772             volume.id, server.id))
773
774
775 def detach_volume(nova, neutron, keystone, server, volume, project_name,
776                   timeout=120):
777     """
778     Detaches a volume to a server. When the timeout parameter is used, a VmInst
779     object with the proper volume updates is returned unless it has not been
780     updated in the allotted amount of time then an Exception will be raised.
781     :param nova: the nova client
782     :param neutron: the neutron client
783     :param keystone: the keystone client
784     :param server: the VMInst domain object
785     :param volume: the Volume domain object
786     :param project_name: the associated project name
787     :param timeout: denotes the amount of time to block to determine if the
788                     has been properly detached.
789     :return: updated VmInst object
790     """
791     nova.volumes.delete_server_volume(server.id, volume.id)
792
793     start_time = time.time()
794     while time.time() < start_time + timeout:
795         vm = get_server_object_by_id(
796             nova, neutron, keystone, server.id, project_name)
797         if len(vm.volume_ids) == 0:
798             return vm
799         else:
800             ids = list()
801             for vol_dict in vm.volume_ids:
802                 ids.append(vol_dict['id'])
803             if volume.id not in ids:
804                 return vm
805         time.sleep(POLL_INTERVAL)
806
807     raise NovaException(
808         'Detach failed on volume - {} server - {}'.format(
809             volume.id, server.id))
810
811
812 class RebootType(enum.Enum):
813     """
814     A rule's direction
815     """
816     soft = 'SOFT'
817     hard = 'HARD'
818
819
820 class NovaException(Exception):
821     """
822     Exception when calls to the Keystone client cannot be served properly
823     """
824
825
826 class ServerNotFoundError(Exception):
827     """
828     Exception when operations to a VM/Server is requested and the OpenStack
829     Server instance cannot be located
830     """