1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
|
# Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
# and others. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os
import time
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from novaclient.client import Client
from novaclient.exceptions import NotFound
from snaps import file_utils
from snaps.domain.flavor import Flavor
from snaps.domain.keypair import Keypair
from snaps.domain.project import ComputeQuotas
from snaps.domain.vm_inst import VmInst
from snaps.openstack.utils import keystone_utils, glance_utils, neutron_utils
__author__ = 'spisarski'
logger = logging.getLogger('nova_utils')
"""
Utilities for basic OpenStack Nova API calls
"""
def nova_client(os_creds):
"""
Instantiates and returns a client for communications with OpenStack's Nova
server
:param os_creds: The connection credentials to the OpenStack API
:return: the client object
"""
logger.debug('Retrieving Nova Client')
return Client(os_creds.compute_api_version,
session=keystone_utils.keystone_session(os_creds),
region_name=os_creds.region_name)
def create_server(nova, neutron, glance, instance_settings, image_settings,
keypair_settings=None):
"""
Creates a VM instance
:param nova: the nova client (required)
:param neutron: the neutron client for retrieving ports (required)
:param glance: the glance client (required)
:param instance_settings: the VM instance settings object (required)
:param image_settings: the VM's image settings object (required)
:param keypair_settings: the VM's keypair settings object (optional)
:return: a snaps.domain.VmInst object
"""
ports = list()
for port_setting in instance_settings.port_settings:
ports.append(neutron_utils.get_port(
neutron, port_settings=port_setting))
nics = []
for port in ports:
kv = dict()
kv['port-id'] = port.id
nics.append(kv)
logger.info('Creating VM with name - ' + instance_settings.name)
keypair_name = None
if keypair_settings:
keypair_name = keypair_settings.name
flavor = get_flavor_by_name(nova, instance_settings.flavor)
if not flavor:
raise NovaException(
'Flavor not found with name - %s', instance_settings.flavor)
image = glance_utils.get_image(glance, image_settings=image_settings)
if image:
userdata = None
if instance_settings.userdata:
if isinstance(instance_settings.userdata, str):
userdata = instance_settings.userdata + '\n'
elif (isinstance(instance_settings.userdata, dict) and
'script_file' in instance_settings.userdata):
try:
userdata = file_utils.read_file(
instance_settings.userdata['script_file'])
except Exception as e:
logger.warn('error reading userdata file %s - %s',
instance_settings.userdata, e)
args = {'name': instance_settings.name,
'flavor': flavor,
'image': image,
'nics': nics,
'key_name': keypair_name,
'security_groups':
instance_settings.security_group_names,
'userdata': userdata}
if instance_settings.availability_zone:
args['availability_zone'] = instance_settings.availability_zone
server = nova.servers.create(**args)
return __map_os_server_obj_to_vm_inst(server)
else:
raise NovaException(
'Cannot create instance, image cannot be located with name %s',
image_settings.name)
def get_server(nova, vm_inst_settings=None, server_name=None):
"""
Returns a VmInst object for the first server instance found.
:param nova: the Nova client
:param vm_inst_settings: the VmInstanceSettings object from which to build
the query if not None
:param server_name: the server with this name to return if vm_inst_settings
is not None
:return: a snaps.domain.VmInst object or None if not found
"""
search_opts = dict()
if vm_inst_settings:
search_opts['name'] = vm_inst_settings.name
elif server_name:
search_opts['name'] = server_name
servers = nova.servers.list(search_opts=search_opts)
for server in servers:
return __map_os_server_obj_to_vm_inst(server)
def get_server_connection(nova, vm_inst_settings=None, server_name=None):
"""
Returns a VmInst object for the first server instance found.
:param nova: the Nova client
:param vm_inst_settings: the VmInstanceSettings object from which to build
the query if not None
:param server_name: the server with this name to return if vm_inst_settings
is not None
:return: a snaps.domain.VmInst object or None if not found
"""
search_opts = dict()
if vm_inst_settings:
search_opts['name'] = vm_inst_settings.name
elif server_name:
search_opts['name'] = server_name
servers = nova.servers.list(search_opts=search_opts)
for server in servers:
return server.links[0]
def __map_os_server_obj_to_vm_inst(os_server):
"""
Returns a VmInst object for an OpenStack Server object
:param os_server: the OpenStack server object
:return: an equivalent SNAPS-OO VmInst domain object
"""
sec_grp_names = list()
# VM must be active for 'security_groups' attr to be initialized
if hasattr(os_server, 'security_groups'):
for sec_group in os_server.security_groups:
if sec_group.get('name'):
sec_grp_names.append(sec_group.get('name'))
volumes = None
if hasattr(os_server, 'os-extended-volumes:volumes_attached'):
volumes = getattr(os_server, 'os-extended-volumes:volumes_attached')
return VmInst(
name=os_server.name, inst_id=os_server.id,
image_id=os_server.image['id'], flavor_id=os_server.flavor['id'],
networks=os_server.networks, keypair_name=os_server.key_name,
sec_grp_names=sec_grp_names, volume_ids=volumes)
def __get_latest_server_os_object(nova, server):
"""
Returns a server with a given id
:param nova: the Nova client
:param server: the domain VmInst object
:return: the list of servers or None if not found
"""
return __get_latest_server_os_object_by_id(nova, server.id)
def __get_latest_server_os_object_by_id(nova, server_id):
"""
Returns a server with a given id
:param nova: the Nova client
:param server_id: the server's ID
:return: the list of servers or None if not found
"""
return nova.servers.get(server_id)
def get_server_status(nova, server):
"""
Returns the a VM instance's status from OpenStack
:param nova: the Nova client
:param server: the domain VmInst object
:return: the VM's string status or None if not founc
"""
server = __get_latest_server_os_object(nova, server)
if server:
return server.status
return None
def get_server_console_output(nova, server):
"""
Returns the console object for parsing VM activity
:param nova: the Nova client
:param server: the domain VmInst object
:return: the console output object or None if server object is not found
"""
server = __get_latest_server_os_object(nova, server)
if server:
return server.get_console_output()
return None
def get_latest_server_object(nova, server):
"""
Returns a server with a given id
:param nova: the Nova client
:param server: the old server object
:return: the list of servers or None if not found
"""
server = __get_latest_server_os_object(nova, server)
return __map_os_server_obj_to_vm_inst(server)
def get_server_object_by_id(nova, server_id):
"""
Returns a server with a given id
:param nova: the Nova client
:param server_id: the server's id
:return: an SNAPS-OO VmInst object or None if not found
"""
server = __get_latest_server_os_object_by_id(nova, server_id)
return __map_os_server_obj_to_vm_inst(server)
def get_server_security_group_names(nova, server):
"""
Returns a server with a given id
:param nova: the Nova client
:param server: the old server object
:return: the list of security groups associated with a VM
"""
out = list()
os_vm_inst = __get_latest_server_os_object(nova, server)
for sec_grp_dict in os_vm_inst.security_groups:
out.append(sec_grp_dict['name'])
return out
def get_server_info(nova, server):
"""
Returns a dictionary of a VMs info as returned by OpenStack
:param nova: the Nova client
:param server: the old server object
:return: a dict of the info if VM exists else None
"""
vm = __get_latest_server_os_object(nova, server)
if vm:
return vm._info
return None
def create_keys(key_size=2048):
"""
Generates public and private keys
:param key_size: the number of bytes for the key size
:return: the cryptography keys
"""
return rsa.generate_private_key(backend=default_backend(),
public_exponent=65537,
key_size=key_size)
def public_key_openssh(keys):
"""
Returns the public key for OpenSSH
:param keys: the keys generated by create_keys() from cryptography
:return: the OpenSSH public key
"""
return keys.public_key().public_bytes(serialization.Encoding.OpenSSH,
serialization.PublicFormat.OpenSSH)
def save_keys_to_files(keys=None, pub_file_path=None, priv_file_path=None):
"""
Saves the generated RSA generated keys to the filesystem
:param keys: the keys to save generated by cryptography
:param pub_file_path: the path to the public keys
:param priv_file_path: the path to the private keys
"""
if keys:
if pub_file_path:
# To support '~'
pub_expand_file = os.path.expanduser(pub_file_path)
pub_dir = os.path.dirname(pub_expand_file)
if not os.path.isdir(pub_dir):
os.mkdir(pub_dir)
public_handle = None
try:
public_handle = open(pub_expand_file, 'wb')
public_bytes = keys.public_key().public_bytes(
serialization.Encoding.OpenSSH,
serialization.PublicFormat.OpenSSH)
public_handle.write(public_bytes)
finally:
if public_handle:
public_handle.close()
os.chmod(pub_expand_file, 0o600)
logger.info("Saved public key to - " + pub_expand_file)
if priv_file_path:
# To support '~'
priv_expand_file = os.path.expanduser(priv_file_path)
priv_dir = os.path.dirname(priv_expand_file)
if not os.path.isdir(priv_dir):
os.mkdir(priv_dir)
private_handle = None
try:
private_handle = open(priv_expand_file, 'wb')
private_handle.write(
keys.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()))
finally:
if private_handle:
private_handle.close()
os.chmod(priv_expand_file, 0o600)
logger.info("Saved private key to - " + priv_expand_file)
def upload_keypair_file(nova, name, file_path):
"""
Uploads a public key from a file
:param nova: the Nova client
:param name: the keypair name
:param file_path: the path to the public key file
:return: the keypair object
"""
fpubkey = None
try:
with open(os.path.expanduser(file_path), 'rb') as fpubkey:
logger.info('Saving keypair to - ' + file_path)
return upload_keypair(nova, name, fpubkey.read())
finally:
if fpubkey:
fpubkey.close()
def upload_keypair(nova, name, key):
"""
Uploads a public key from a file
:param nova: the Nova client
:param name: the keypair name
:param key: the public key object
:return: the keypair object
"""
logger.info('Creating keypair with name - ' + name)
os_kp = nova.keypairs.create(name=name, public_key=key.decode('utf-8'))
return Keypair(name=os_kp.name, kp_id=os_kp.id,
public_key=os_kp.public_key, fingerprint=os_kp.fingerprint)
def keypair_exists(nova, keypair_obj):
"""
Returns a copy of the keypair object if found
:param nova: the Nova client
:param keypair_obj: the keypair object
:return: the keypair object or None if not found
"""
try:
os_kp = nova.keypairs.get(keypair_obj)
return Keypair(name=os_kp.name, kp_id=os_kp.id,
public_key=os_kp.public_key)
except:
return None
def get_keypair_by_name(nova, name):
"""
Returns a list of all available keypairs
:param nova: the Nova client
:param name: the name of the keypair to lookup
:return: the keypair object or None if not found
"""
keypairs = nova.keypairs.list()
for keypair in keypairs:
if keypair.name == name:
return Keypair(name=keypair.name, kp_id=keypair.id,
public_key=keypair.public_key)
return None
def delete_keypair(nova, key):
"""
Deletes a keypair object from OpenStack
:param nova: the Nova client
:param key: the SNAPS-OO keypair domain object to delete
"""
logger.debug('Deleting keypair - ' + key.name)
nova.keypairs.delete(key.id)
def get_availability_zone_hosts(nova, zone_name='nova'):
"""
Returns the names of all nova active compute servers
:param nova: the Nova client
:param zone_name: the Nova client
:return: a list of compute server names
"""
out = list()
zones = nova.availability_zones.list()
for zone in zones:
if zone.zoneName == zone_name and zone.hosts:
for key, host in zone.hosts.items():
if host['nova-compute']['available']:
out.append(zone.zoneName + ':' + key)
return out
def delete_vm_instance(nova, vm_inst):
"""
Deletes a VM instance
:param nova: the nova client
:param vm_inst: the snaps.domain.VmInst object
"""
nova.servers.delete(vm_inst.id)
def __get_os_flavor(nova, flavor_id):
"""
Returns to OpenStack flavor object by name
:param nova: the Nova client
:param flavor_id: the flavor's ID value
:return: the OpenStack Flavor object
"""
try:
return nova.flavors.get(flavor_id)
except NotFound:
return None
def get_flavor(nova, flavor):
"""
Returns to OpenStack flavor object by name
:param nova: the Nova client
:param flavor: the SNAPS flavor domain object
:return: the SNAPS Flavor domain object
"""
os_flavor = __get_os_flavor(nova, flavor.id)
if os_flavor:
return Flavor(
name=os_flavor.name, id=os_flavor.id, ram=os_flavor.ram,
disk=os_flavor.disk, vcpus=os_flavor.vcpus,
ephemeral=os_flavor.ephemeral, swap=os_flavor.swap,
rxtx_factor=os_flavor.rxtx_factor, is_public=os_flavor.is_public)
try:
return nova.flavors.get(flavor.id)
except NotFound:
return None
def get_flavor_by_id(nova, flavor_id):
"""
Returns to OpenStack flavor object by name
:param nova: the Nova client
:param flavor_id: the flavor ID value
:return: the SNAPS Flavor domain object
"""
os_flavor = __get_os_flavor(nova, flavor_id)
if os_flavor:
return Flavor(
name=os_flavor.name, id=os_flavor.id, ram=os_flavor.ram,
disk=os_flavor.disk, vcpus=os_flavor.vcpus,
ephemeral=os_flavor.ephemeral, swap=os_flavor.swap,
rxtx_factor=os_flavor.rxtx_factor, is_public=os_flavor.is_public)
def __get_os_flavor_by_name(nova, name):
"""
Returns to OpenStack flavor object by name
:param nova: the Nova client
:param name: the name of the flavor to query
:return: OpenStack flavor object
"""
try:
return nova.flavors.find(name=name)
except NotFound:
return None
def get_flavor_by_name(nova, name):
"""
Returns a flavor by name
:param nova: the Nova client
:param name: the flavor name to return
:return: the SNAPS flavor domain object or None if not exists
"""
os_flavor = __get_os_flavor_by_name(nova, name)
if os_flavor:
return Flavor(
name=os_flavor.name, id=os_flavor.id, ram=os_flavor.ram,
disk=os_flavor.disk, vcpus=os_flavor.vcpus,
ephemeral=os_flavor.ephemeral, swap=os_flavor.swap,
rxtx_factor=os_flavor.rxtx_factor, is_public=os_flavor.is_public)
def create_flavor(nova, flavor_settings):
"""
Creates and returns and OpenStack flavor object
:param nova: the Nova client
:param flavor_settings: the flavor settings
:return: the SNAPS flavor domain object
"""
os_flavor = nova.flavors.create(
name=flavor_settings.name, flavorid=flavor_settings.flavor_id,
ram=flavor_settings.ram, vcpus=flavor_settings.vcpus,
disk=flavor_settings.disk, ephemeral=flavor_settings.ephemeral,
swap=flavor_settings.swap, rxtx_factor=flavor_settings.rxtx_factor,
is_public=flavor_settings.is_public)
return Flavor(
name=os_flavor.name, id=os_flavor.id, ram=os_flavor.ram,
disk=os_flavor.disk, vcpus=os_flavor.vcpus,
ephemeral=os_flavor.ephemeral, swap=os_flavor.swap,
rxtx_factor=os_flavor.rxtx_factor, is_public=os_flavor.is_public)
def delete_flavor(nova, flavor):
"""
Deletes a flavor
:param nova: the Nova client
:param flavor: the SNAPS flavor domain object
"""
nova.flavors.delete(flavor.id)
def set_flavor_keys(nova, flavor, metadata):
"""
Sets metadata on the flavor
:param nova: the Nova client
:param flavor: the SNAPS flavor domain object
:param metadata: the metadata to set
"""
os_flavor = __get_os_flavor(nova, flavor.id)
if os_flavor:
os_flavor.set_keys(metadata)
def get_flavor_keys(nova, flavor):
"""
Sets metadata on the flavor
:param nova: the Nova client
:param flavor: the SNAPS flavor domain object
"""
os_flavor = __get_os_flavor(nova, flavor.id)
if os_flavor:
return os_flavor.get_keys()
def add_security_group(nova, vm, security_group_name):
"""
Adds a security group to an existing VM
:param nova: the nova client
:param vm: the OpenStack server object (VM) to alter
:param security_group_name: the name of the security group to add
"""
nova.servers.add_security_group(str(vm.id), security_group_name)
def remove_security_group(nova, vm, security_group):
"""
Removes a security group from an existing VM
:param nova: the nova client
:param vm: the OpenStack server object (VM) to alter
:param security_group: the SNAPS SecurityGroup domain object to add
"""
nova.servers.remove_security_group(str(vm.id), security_group.name)
def add_floating_ip_to_server(nova, vm, floating_ip, ip_addr):
"""
Adds a floating IP to a server instance
:param nova: the nova client
:param vm: VmInst domain object
:param floating_ip: FloatingIp domain object
:param ip_addr: the IP to which to bind the floating IP to
"""
vm = __get_latest_server_os_object(nova, vm)
vm.add_floating_ip(floating_ip.ip, ip_addr)
def get_compute_quotas(nova, project_id):
"""
Returns a list of all available keypairs
:param nova: the Nova client
:param project_id: the project's ID of the quotas to lookup
:return: an object of type ComputeQuotas or None if not found
"""
quotas = nova.quotas.get(tenant_id=project_id)
if quotas:
return ComputeQuotas(quotas)
def update_quotas(nova, project_id, compute_quotas):
"""
Updates the compute quotas for a given project
:param nova: the Nova client
:param project_id: the project's ID that requires quota updates
:param compute_quotas: an object of type ComputeQuotas containing the
values to update
:return:
"""
update_values = dict()
update_values['metadata_items'] = compute_quotas.metadata_items
update_values['cores'] = compute_quotas.cores
update_values['instances'] = compute_quotas.instances
update_values['injected_files'] = compute_quotas.injected_files
update_values['injected_file_content_bytes'] = (
compute_quotas.injected_file_content_bytes)
update_values['ram'] = compute_quotas.ram
update_values['fixed_ips'] = compute_quotas.fixed_ips
update_values['key_pairs'] = compute_quotas.key_pairs
return nova.quotas.update(project_id, **update_values)
def attach_volume(nova, server, volume, timeout=None):
"""
Attaches a volume to a server
:param nova: the nova client
:param server: the VMInst domain object
:param volume: the Volume domain object
:param timeout: denotes the amount of time to block to determine if the
has been properly attached. When None, do not wait.
:return: the value from the nova call
"""
nova.volumes.create_server_volume(server.id, volume.id)
if timeout:
start_time = time.time()
while time.time() < start_time + timeout:
vm = get_server_object_by_id(nova, server.id)
for vol_dict in vm.volume_ids:
if volume.id == vol_dict['id']:
return vm
return None
else:
return get_server_object_by_id(nova, server.id)
def detach_volume(nova, server, volume, timeout=None):
"""
Attaches a volume to a server
:param nova: the nova client
:param server: the VMInst domain object
:param volume: the Volume domain object
:param timeout: denotes the amount of time to block to determine if the
has been properly detached. When None, do not wait.
:return: the value from the nova call
"""
nova.volumes.delete_server_volume(server.id, volume.id)
if timeout:
start_time = time.time()
while time.time() < start_time + timeout:
vm = get_server_object_by_id(nova, server.id)
found = False
for vol_dict in vm.volume_ids:
if volume.id == vol_dict['id']:
found = True
if not found:
return vm
return None
else:
return get_server_object_by_id(nova, server.id)
class NovaException(Exception):
"""
Exception when calls to the Keystone client cannot be served properly
"""
|