3 # Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs")
4 # and others. All rights reserved.
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at:
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
18 # This script is responsible for deploying virtual environments
24 from jinja2 import Environment, FileSystemLoader
28 from snaps import file_utils
29 from snaps.config.flavor import FlavorConfig
30 from snaps.config.image import ImageConfig
31 from snaps.config.keypair import KeypairConfig
32 from snaps.config.project import ProjectConfig
33 from snaps.openstack.create_flavor import OpenStackFlavor
34 from snaps.openstack.create_image import OpenStackImage
35 from snaps.openstack.create_instance import VmInstanceSettings
36 from snaps.openstack.create_keypairs import OpenStackKeypair
37 from snaps.openstack.create_network import (
38 PortSettings, NetworkSettings, OpenStackNetwork)
39 from snaps.openstack.create_project import OpenStackProject
40 from snaps.openstack.create_qos import QoSSettings, OpenStackQoS
41 from snaps.openstack.create_router import RouterSettings, OpenStackRouter
42 from snaps.openstack.create_security_group import (
43 OpenStackSecurityGroup, SecurityGroupSettings)
44 from snaps.openstack.create_user import OpenStackUser, UserSettings
45 from snaps.openstack.create_volume import OpenStackVolume, VolumeSettings
46 from snaps.openstack.create_volume_type import (
47 OpenStackVolumeType, VolumeTypeSettings)
48 from snaps.openstack.os_credentials import OSCreds, ProxySettings
49 from snaps.openstack.utils import deploy_utils
50 from snaps.provisioning import ansible_utils
52 __author__ = 'spisarski'
54 logger = logging.getLogger('snaps_launcher')
56 ARG_NOT_SET = "argument not set"
57 DEFAULT_CREDS_KEY = 'admin'
60 def __get_creds_dict(os_conn_config):
62 Returns a dict of OSCreds where the key is the creds name.
63 For backwards compatibility, credentials not contained in a list (only
64 one) will be returned with the key of None
65 :param os_conn_config: the credential configuration
66 :return: a dict of OSCreds objects
68 if 'connection' in os_conn_config:
69 return {DEFAULT_CREDS_KEY: __get_os_credentials(os_conn_config)}
70 elif 'connections' in os_conn_config:
72 for os_conn_dict in os_conn_config['connections']:
73 config = os_conn_dict.get('connection')
75 raise Exception('Invalid connection format')
77 name = config.get('name')
79 raise Exception('Connection config requires a name field')
81 out[name] = __get_os_credentials(os_conn_dict)
85 def __get_creds(os_creds_dict, os_user_dict, inst_config):
87 Returns the appropriate credentials
88 :param os_creds_dict: a dictionary of OSCreds objects where the name is the
90 :param os_user_dict: a dictionary of OpenStackUser objects where the name
93 :return: an OSCreds instance or None
95 os_creds = os_creds_dict.get(DEFAULT_CREDS_KEY)
96 if 'os_user' in inst_config:
97 os_user_conf = inst_config['os_user']
98 if 'name' in os_user_conf:
99 user_creator = os_user_dict.get(os_user_conf['name'])
101 return user_creator.get_os_creds(
102 project_name=os_user_conf.get('project_name'))
103 elif 'os_creds_name' in inst_config:
104 if 'os_creds_name' in inst_config:
105 os_creds = os_creds_dict[inst_config['os_creds_name']]
109 def __get_os_credentials(os_conn_config):
111 Returns an object containing all of the information required to access
113 :param os_conn_config: The configuration holding the credentials
114 :return: an OSCreds instance
116 config = os_conn_config.get('connection')
118 raise Exception('Invalid connection configuration')
120 proxy_settings = None
121 http_proxy = config.get('http_proxy')
123 tokens = re.split(':', http_proxy)
124 ssh_proxy_cmd = config.get('ssh_proxy_cmd')
125 proxy_settings = ProxySettings(host=tokens[0], port=tokens[1],
126 ssh_proxy_cmd=ssh_proxy_cmd)
128 if 'proxy_settings' in config:
129 host = config['proxy_settings'].get('host')
130 port = config['proxy_settings'].get('port')
131 if host and host != 'None' and port and port != 'None':
132 proxy_settings = ProxySettings(**config['proxy_settings'])
135 config['proxy_settings'] = proxy_settings
137 if config.get('proxy_settings'):
138 del config['proxy_settings']
140 return OSCreds(**config)
143 def __parse_ports_config(config):
145 Parses the "ports" configuration
146 :param config: The dictionary to parse
147 :return: a list of PortConfig objects
150 for port_config in config:
151 out.append(PortSettings(**port_config.get('port')))
155 def __create_instances(os_creds_dict, creator_class, config_class, config,
156 config_key, cleanup=False, os_users_dict=None):
158 Returns a dictionary of SNAPS creator objects where the key is the name
159 :param os_creds_dict: Dictionary of OSCreds objects where the key is the
161 :param config: The list of configurations for the same type
162 :param config_key: The list of configurations for the same type
163 :param cleanup: Denotes whether or not this is being called for cleanup
170 for config_dict in config:
171 inst_config = config_dict.get(config_key)
173 creator = creator_class(
174 __get_creds(os_creds_dict, os_users_dict, inst_config),
175 config_class(**inst_config))
181 out[inst_config['name']] = creator
182 logger.info('Created configured %s', config_key)
183 except Exception as e:
184 logger.error('Unexpected error instantiating creator [%s] '
185 'with exception %s', creator_class, e)
190 def __create_vm_instances(os_creds_dict, os_users_dict, instances_config,
191 image_dict, keypairs_dict, cleanup=False):
193 Returns a dictionary of OpenStackVmInstance objects where the key is the
195 :param os_creds_dict: Dictionary of OSCreds objects where the key is the
197 :param os_users_dict: Dictionary of OpenStackUser objects where the key is
199 :param instances_config: The list of VM instance configurations
200 :param image_dict: A dictionary of images that will probably be used to
201 instantiate the VM instance
202 :param keypairs_dict: A dictionary of keypairs that will probably be used
203 to instantiate the VM instance
204 :param cleanup: Denotes whether or not this is being called for cleanup
211 for instance_config in instances_config:
212 conf = instance_config.get('instance')
215 image_creator = image_dict.get(conf.get('imageName'))
217 instance_settings = VmInstanceSettings(
218 **instance_config['instance'])
219 kp_creator = keypairs_dict.get(
220 conf.get('keypair_name'))
222 'name']] = deploy_utils.create_vm_instance(
224 os_creds_dict, os_users_dict, conf),
226 image_creator.image_settings,
227 keypair_creator=kp_creator,
230 raise Exception('Image creator instance not found.'
231 ' Cannot instantiate')
233 raise Exception('Image dictionary is None. Cannot '
236 raise Exception('Instance configuration is None. Cannot '
238 logger.info('Created configured instances')
239 except Exception as e:
240 logger.error('Unexpected error creating VM instances - %s', e)
244 def __apply_ansible_playbooks(ansible_configs, os_creds_dict, vm_dict,
245 image_dict, flavor_dict, env_file):
247 Applies ansible playbooks to running VMs with floating IPs
248 :param ansible_configs: a list of Ansible configurations
249 :param os_creds_dict: Dictionary of OSCreds objects where the key is the
251 :param vm_dict: the dictionary of newly instantiated VMs where the name is
253 :param image_dict: the dictionary of newly instantiated images where the
255 :param flavor_dict: the dictionary of newly instantiated flavors where the
257 :param env_file: the path of the environment for setting the CWD so
258 playbook location is relative to the deployment file
259 :return: t/f - true if successful
261 logger.info("Applying Ansible Playbooks")
263 # Ensure all hosts are accepting SSH session requests
264 for vm_inst in list(vm_dict.values()):
265 if not vm_inst.vm_ssh_active(block=True):
267 "Timeout waiting for instance to respond to SSH requests")
270 # Set CWD so the deployment file's playbook location can leverage
272 orig_cwd = os.getcwd()
273 env_dir = os.path.dirname(env_file)
277 for ansible_config in ansible_configs:
278 if 'pre_sleep_time' in ansible_config:
280 sleep_time = int(ansible_config['pre_sleep_time'])
281 logger.info('Waiting %s seconds to apply playbooks',
283 time.sleep(sleep_time)
287 os_creds = os_creds_dict.get(None, 'admin')
288 __apply_ansible_playbook(ansible_config, os_creds, vm_dict,
289 image_dict, flavor_dict)
291 # Return to original directory
297 def __apply_ansible_playbook(ansible_config, os_creds, vm_dict, image_dict,
300 Applies an Ansible configuration setting
301 :param ansible_config: the configuration settings
302 :param os_creds: the OpenStack credentials object
303 :param vm_dict: the dictionary of newly instantiated VMs where the name is
305 :param image_dict: the dictionary of newly instantiated images where the
307 :param flavor_dict: the dictionary of newly instantiated flavors where the
311 (remote_user, floating_ips, private_key_filepath,
312 proxy_settings) = __get_connection_info(
313 ansible_config, vm_dict)
315 retval = ansible_utils.apply_playbook(
316 ansible_config['playbook_location'], floating_ips, remote_user,
317 private_key_filepath,
318 variables=__get_variables(ansible_config.get('variables'),
319 os_creds, vm_dict, image_dict,
321 proxy_setting=proxy_settings)
323 # Not a fatal type of event
325 'Unable to apply playbook found at location - %s',
326 ansible_config.get('playbook_location'))
329 def __get_connection_info(ansible_config, vm_dict):
331 Returns a tuple of data required for connecting to the running VMs
332 (remote_user, [floating_ips], private_key_filepath, proxy_settings)
333 :param ansible_config: the configuration settings
334 :param vm_dict: the dictionary of VMs where the VM name is the key
335 :return: tuple where the first element is the user and the second is a list
336 of floating IPs and the third is the
337 private key file location and the fourth is an instance of the
338 snaps.ProxySettings class
339 (note: in order to work, each of the hosts need to have the same sudo_user
340 and private key file location values)
342 if ansible_config.get('hosts'):
343 hosts = ansible_config['hosts']
345 floating_ips = list()
348 proxy_settings = None
350 vm = vm_dict.get(host)
352 fip = vm.get_floating_ip()
354 remote_user = vm.get_image_user()
357 floating_ips.append(fip.ip)
360 'Could not find floating IP for VM - ' +
363 pk_file = vm.keypair_settings.private_filepath
364 proxy_settings = vm.get_os_creds().proxy_settings
366 logger.error('Could not locate VM with name - ' + host)
368 return remote_user, floating_ips, pk_file, proxy_settings
372 def __get_variables(var_config, os_creds, vm_dict, image_dict, flavor_dict):
374 Returns a dictionary of substitution variables to be used for Ansible
376 :param var_config: the variable configuration settings
377 :param os_creds: the OpenStack credentials object
378 :param vm_dict: the dictionary of newly instantiated VMs where the name is
380 :param image_dict: the dictionary of newly instantiated images where the
382 :param flavor_dict: the dictionary of newly instantiated flavors where the
384 :return: dictionary or None
386 if var_config and vm_dict and len(vm_dict) > 0:
388 for key, value in var_config.items():
389 value = __get_variable_value(value, os_creds, vm_dict, image_dict,
392 variables[key] = value
394 "Set Jinga2 variable with key [%s] the value [%s]",
397 logger.warning('Key [%s] or Value [%s] must not be None',
398 str(key), str(value))
403 def __get_variable_value(var_config_values, os_creds, vm_dict, image_dict,
406 Returns the associated variable value for use by Ansible for substitution
408 :param var_config_values: the configuration dictionary
409 :param os_creds: the OpenStack credentials object
410 :param vm_dict: the dictionary of newly instantiated VMs where the name is
412 :param image_dict: the dictionary of newly instantiated images where the
414 :param flavor_dict: the dictionary of newly instantiated flavors where the
418 if var_config_values['type'] == 'string':
419 return __get_string_variable_value(var_config_values)
420 if var_config_values['type'] == 'vm-attr':
421 return __get_vm_attr_variable_value(var_config_values, vm_dict)
422 if var_config_values['type'] == 'os_creds':
423 return __get_os_creds_variable_value(var_config_values, os_creds)
424 if var_config_values['type'] == 'port':
425 return __get_vm_port_variable_value(var_config_values, vm_dict)
426 if var_config_values['type'] == 'floating_ip':
427 return __get_vm_fip_variable_value(var_config_values, vm_dict)
428 if var_config_values['type'] == 'image':
429 return __get_image_variable_value(var_config_values, image_dict)
430 if var_config_values['type'] == 'flavor':
431 return __get_flavor_variable_value(var_config_values, flavor_dict)
435 def __get_string_variable_value(var_config_values):
437 Returns the associated string value
438 :param var_config_values: the configuration dictionary
439 :return: the value contained in the dictionary with the key 'value'
441 return var_config_values['value']
444 def __get_vm_attr_variable_value(var_config_values, vm_dict):
446 Returns the associated value contained on a VM instance
447 :param var_config_values: the configuration dictionary
448 :param vm_dict: the dictionary containing all VMs where the key is the VM's
452 vm = vm_dict.get(var_config_values['vm_name'])
454 if var_config_values['value'] == 'floating_ip':
455 return vm.get_floating_ip().ip
456 if var_config_values['value'] == 'image_user':
457 return vm.get_image_user()
460 def __get_os_creds_variable_value(var_config_values, os_creds):
462 Returns the associated OS credentials value
463 :param var_config_values: the configuration dictionary
464 :param os_creds: the credentials
467 logger.info("Retrieving OS Credentials")
469 if var_config_values['value'] == 'username':
470 logger.info("Returning OS username")
471 return os_creds.username
472 elif var_config_values['value'] == 'password':
473 logger.info("Returning OS password")
474 return os_creds.password
475 elif var_config_values['value'] == 'auth_url':
476 logger.info("Returning OS auth_url")
477 return os_creds.auth_url
478 elif var_config_values['value'] == 'project_name':
479 logger.info("Returning OS project_name")
480 return os_creds.project_name
482 logger.info("Returning none")
486 def __get_vm_port_variable_value(var_config_values, vm_dict):
488 Returns the associated OS credentials value
489 :param var_config_values: the configuration dictionary
490 :param vm_dict: the dictionary containing all VMs where the key is the VM's
494 port_name = var_config_values.get('port_name')
495 vm_name = var_config_values.get('vm_name')
497 if port_name and vm_name:
498 vm = vm_dict.get(vm_name)
500 port_value_id = var_config_values.get('port_value')
502 if port_value_id == 'mac_address':
503 return vm.get_port_mac(port_name)
504 if port_value_id == 'ip_address':
505 return vm.get_port_ip(port_name)
508 def __get_vm_fip_variable_value(var_config_values, vm_dict):
510 Returns the floating IP value if found
511 :param var_config_values: the configuration dictionary
512 :param vm_dict: the dictionary containing all VMs where the key is the VM's
514 :return: the floating IP string value or None
516 fip_name = var_config_values.get('fip_name')
517 vm_name = var_config_values.get('vm_name')
520 vm = vm_dict.get(vm_name)
522 fip = vm.get_floating_ip(fip_name)
527 def __get_image_variable_value(var_config_values, image_dict):
529 Returns the associated image value
530 :param var_config_values: the configuration dictionary
531 :param image_dict: the dictionary containing all images where the key is
535 logger.info("Retrieving image values")
538 if var_config_values.get('image_name'):
539 image_creator = image_dict.get(var_config_values['image_name'])
541 if var_config_values.get('value') and \
542 var_config_values['value'] == 'id':
543 return image_creator.get_image().id
544 if var_config_values.get('value') and \
545 var_config_values['value'] == 'user':
546 return image_creator.image_settings.image_user
548 logger.info("Returning none")
552 def __get_flavor_variable_value(var_config_values, flavor_dict):
554 Returns the associated flavor value
555 :param var_config_values: the configuration dictionary
556 :param flavor_dict: the dictionary containing all flavor creators where the
558 :return: the value or None
560 logger.info("Retrieving flavor values")
563 if var_config_values.get('flavor_name'):
564 flavor_creator = flavor_dict.get(var_config_values['flavor_name'])
566 if var_config_values.get('value') and \
567 var_config_values['value'] == 'id':
568 return flavor_creator.get_flavor().id
573 Will need to set environment variable ANSIBLE_HOST_KEY_CHECKING=False or
574 Create a file located in /etc/ansible/ansible/cfg or ~/.ansible.cfg
575 containing the following content:
578 host_key_checking = False
580 CWD must be this directory where this script is located.
584 log_level = logging.INFO
585 if arguments.log_level != 'INFO':
586 log_level = logging.DEBUG
587 logging.basicConfig(level=log_level)
589 logger.info('Starting to Deploy')
591 # Apply env_file/substitution file to template
592 env = Environment(loader=FileSystemLoader(
593 searchpath=os.path.dirname(arguments.tmplt_file)))
594 template = env.get_template(os.path.basename(arguments.tmplt_file))
597 if arguments.env_file:
598 env_dict = file_utils.read_yaml(arguments.env_file)
599 output = template.render(**env_dict)
601 config = yaml.load(output)
604 os_config = config.get('openstack')
609 flavors_dict = dict()
610 os_creds_dict = dict()
611 clean = arguments.clean is not ARG_NOT_SET
614 os_creds_dict = __get_creds_dict(os_config)
618 projects_dict = __create_instances(
619 os_creds_dict, OpenStackProject, ProjectConfig,
620 os_config.get('projects'), 'project', clean)
621 creators.append(projects_dict)
624 users_dict = __create_instances(
625 os_creds_dict, OpenStackUser, UserSettings,
626 os_config.get('users'), 'user', clean)
627 creators.append(users_dict)
629 # Associate new users to projects
631 for project_creator in projects_dict.values():
632 users = project_creator.project_settings.users
633 for user_name in users:
634 user_creator = users_dict.get(user_name)
636 project_creator.assoc_user(
637 user_creator.get_user())
640 flavors_dict = __create_instances(
641 os_creds_dict, OpenStackFlavor, FlavorConfig,
642 os_config.get('flavors'), 'flavor', clean, users_dict)
643 creators.append(flavors_dict)
646 qos_dict = __create_instances(
647 os_creds_dict, OpenStackQoS, QoSSettings,
648 os_config.get('qos_specs'), 'qos_spec', clean, users_dict)
649 creators.append(qos_dict)
651 # Create volume types
652 vol_type_dict = __create_instances(
653 os_creds_dict, OpenStackVolumeType, VolumeTypeSettings,
654 os_config.get('volume_types'), 'volume_type', clean,
656 creators.append(vol_type_dict)
658 # Create volume types
659 vol_dict = __create_instances(
660 os_creds_dict, OpenStackVolume, VolumeSettings,
661 os_config.get('volumes'), 'volume', clean, users_dict)
662 creators.append(vol_dict)
665 images_dict = __create_instances(
666 os_creds_dict, OpenStackImage, ImageConfig,
667 os_config.get('images'), 'image', clean, users_dict)
668 creators.append(images_dict)
671 creators.append(__create_instances(
672 os_creds_dict, OpenStackNetwork, NetworkSettings,
673 os_config.get('networks'), 'network', clean, users_dict))
676 creators.append(__create_instances(
677 os_creds_dict, OpenStackRouter, RouterSettings,
678 os_config.get('routers'), 'router', clean, users_dict))
681 keypairs_dict = __create_instances(
682 os_creds_dict, OpenStackKeypair, KeypairConfig,
683 os_config.get('keypairs'), 'keypair', clean, users_dict)
684 creators.append(keypairs_dict)
686 # Create security groups
687 creators.append(__create_instances(
688 os_creds_dict, OpenStackSecurityGroup,
689 SecurityGroupSettings,
690 os_config.get('security_groups'), 'security_group', clean,
694 vm_dict = __create_vm_instances(
695 os_creds_dict, users_dict, os_config.get('instances'),
696 images_dict, keypairs_dict,
697 arguments.clean is not ARG_NOT_SET)
698 creators.append(vm_dict)
700 'Completed creating/retrieving all configured instances')
701 except Exception as e:
703 'Unexpected error deploying environment. Rolling back due'
707 # Must enter either block
708 if arguments.clean is not ARG_NOT_SET:
709 # Cleanup Environment
710 __cleanup(creators, arguments.clean_image is not ARG_NOT_SET)
711 elif arguments.deploy is not ARG_NOT_SET:
712 logger.info('Configuring NICs where required')
713 for vm in vm_dict.values():
715 logger.info('Completed NIC configuration')
718 ansible_config = config.get('ansible')
719 if ansible_config and vm_dict:
720 if not __apply_ansible_playbooks(ansible_config,
721 os_creds_dict, vm_dict,
722 images_dict, flavors_dict,
723 arguments.tmplt_file):
724 logger.error("Problem applying ansible playbooks")
727 'Unable to read configuration file - ' + arguments.tmplt_file)
733 def __cleanup(creators, clean_image=False):
734 for creator_dict in reversed(creators):
735 for key, creator in creator_dict.items():
736 if ((isinstance(creator, OpenStackImage) and clean_image)
737 or not isinstance(creator, OpenStackImage)):
740 except Exception as e:
741 logger.warning('Error cleaning component - %s', e)
744 if __name__ == '__main__':
745 # To ensure any files referenced via a relative path will begin from the
746 # directory in which this file resides
747 os.chdir(os.path.dirname(os.path.realpath(__file__)))
749 parser = argparse.ArgumentParser()
751 '-d', '--deploy', dest='deploy', nargs='?', default=ARG_NOT_SET,
752 help='When used, environment will be deployed and provisioned')
754 '-c', '--clean', dest='clean', nargs='?', default=ARG_NOT_SET,
755 help='When used, the environment will be removed')
757 '-i', '--clean-image', dest='clean_image', nargs='?',
759 help='When cleaning, if this is set, the image will be cleaned too')
761 '-t', '--tmplt', dest='tmplt_file', required=True,
762 help='The SNAPS deployment template YAML file - REQUIRED')
764 '-e', '--env-file', dest='env_file',
765 help='Yaml file containing substitution values to the env file')
767 '-l', '--log-level', dest='log_level', default='INFO',
768 help='Logging Level (INFO|DEBUG)')
769 args = parser.parse_args()
771 if args.deploy is ARG_NOT_SET and args.clean is ARG_NOT_SET:
773 'Must enter either -d for deploy or -c for cleaning up and '
776 if args.deploy is not ARG_NOT_SET and args.clean is not ARG_NOT_SET:
777 print('Cannot enter both options -d/--deploy and -c/--clean')