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.openstack.create_flavor import FlavorSettings, OpenStackFlavor
30 from snaps.openstack.create_image import ImageSettings, OpenStackImage
31 from snaps.openstack.create_instance import VmInstanceSettings
32 from snaps.openstack.create_keypairs import KeypairSettings, OpenStackKeypair
33 from snaps.openstack.create_network import (
34 PortSettings, NetworkSettings, OpenStackNetwork)
35 from snaps.openstack.create_project import OpenStackProject, ProjectSettings
36 from snaps.openstack.create_qos import QoSSettings, OpenStackQoS
37 from snaps.openstack.create_router import RouterSettings, OpenStackRouter
38 from snaps.openstack.create_security_group import (
39 OpenStackSecurityGroup, SecurityGroupSettings)
40 from snaps.openstack.create_user import OpenStackUser, UserSettings
41 from snaps.openstack.create_volume import OpenStackVolume, VolumeSettings
42 from snaps.openstack.create_volume_type import (
43 OpenStackVolumeType, VolumeTypeSettings)
44 from snaps.openstack.os_credentials import OSCreds, ProxySettings
45 from snaps.openstack.utils import deploy_utils
46 from snaps.provisioning import ansible_utils
48 __author__ = 'spisarski'
50 logger = logging.getLogger('snaps_launcher')
52 ARG_NOT_SET = "argument not set"
53 DEFAULT_CREDS_KEY = 'admin'
56 def __get_creds_dict(os_conn_config):
58 Returns a dict of OSCreds where the key is the creds name.
59 For backwards compatibility, credentials not contained in a list (only
60 one) will be returned with the key of None
61 :param os_conn_config: the credential configuration
62 :return: a dict of OSCreds objects
64 if 'connection' in os_conn_config:
65 return {DEFAULT_CREDS_KEY: __get_os_credentials(os_conn_config)}
66 elif 'connections' in os_conn_config:
68 for os_conn_dict in os_conn_config['connections']:
69 config = os_conn_dict.get('connection')
71 raise Exception('Invalid connection format')
73 name = config.get('name')
75 raise Exception('Connection config requires a name field')
77 out[name] = __get_os_credentials(os_conn_dict)
81 def __get_creds(os_creds_dict, os_user_dict, inst_config):
83 Returns the appropriate credentials
84 :param os_creds_dict: a dictionary of OSCreds objects where the name is the
86 :param os_user_dict: a dictionary of OpenStackUser objects where the name
89 :return: an OSCreds instance or None
91 os_creds = os_creds_dict.get(DEFAULT_CREDS_KEY)
92 if 'os_user' in inst_config:
93 os_user_conf = inst_config['os_user']
94 if 'name' in os_user_conf:
95 user_creator = os_user_dict.get(os_user_conf['name'])
97 return user_creator.get_os_creds(
98 project_name=os_user_conf.get('project_name'))
99 elif 'os_creds_name' in inst_config:
100 if 'os_creds_name' in inst_config:
101 os_creds = os_creds_dict[inst_config['os_creds_name']]
105 def __get_os_credentials(os_conn_config):
107 Returns an object containing all of the information required to access
109 :param os_conn_config: The configuration holding the credentials
110 :return: an OSCreds instance
112 config = os_conn_config.get('connection')
114 raise Exception('Invalid connection configuration')
116 proxy_settings = None
117 http_proxy = config.get('http_proxy')
119 tokens = re.split(':', http_proxy)
120 ssh_proxy_cmd = config.get('ssh_proxy_cmd')
121 proxy_settings = ProxySettings(host=tokens[0], port=tokens[1],
122 ssh_proxy_cmd=ssh_proxy_cmd)
124 if 'proxy_settings' in config:
125 host = config['proxy_settings'].get('host')
126 port = config['proxy_settings'].get('port')
127 if host and host != 'None' and port and port != 'None':
128 proxy_settings = ProxySettings(**config['proxy_settings'])
131 config['proxy_settings'] = proxy_settings
133 if config.get('proxy_settings'):
134 del config['proxy_settings']
136 return OSCreds(**config)
139 def __parse_ports_config(config):
141 Parses the "ports" configuration
142 :param config: The dictionary to parse
143 :return: a list of PortConfig objects
146 for port_config in config:
147 out.append(PortSettings(**port_config.get('port')))
151 def __create_instances(os_creds_dict, creator_class, config_class, config,
152 config_key, cleanup=False, os_users_dict=None):
154 Returns a dictionary of SNAPS creator objects where the key is the name
155 :param os_creds_dict: Dictionary of OSCreds objects where the key is the
157 :param config: The list of configurations for the same type
158 :param config_key: The list of configurations for the same type
159 :param cleanup: Denotes whether or not this is being called for cleanup
166 for config_dict in config:
167 inst_config = config_dict.get(config_key)
169 creator = creator_class(
170 __get_creds(os_creds_dict, os_users_dict, inst_config),
171 config_class(**inst_config))
177 out[inst_config['name']] = creator
178 logger.info('Created configured %s', config_key)
179 except Exception as e:
180 logger.error('Unexpected error instantiating creator [%s] '
181 'with exception %s', creator_class, e)
186 def __create_vm_instances(os_creds_dict, os_users_dict, instances_config,
187 image_dict, keypairs_dict, cleanup=False):
189 Returns a dictionary of OpenStackVmInstance objects where the key is the
191 :param os_creds_dict: Dictionary of OSCreds objects where the key is the
193 :param os_users_dict: Dictionary of OpenStackUser objects where the key is
195 :param instances_config: The list of VM instance configurations
196 :param image_dict: A dictionary of images that will probably be used to
197 instantiate the VM instance
198 :param keypairs_dict: A dictionary of keypairs that will probably be used
199 to instantiate the VM instance
200 :param cleanup: Denotes whether or not this is being called for cleanup
207 for instance_config in instances_config:
208 conf = instance_config.get('instance')
211 image_creator = image_dict.get(conf.get('imageName'))
213 instance_settings = VmInstanceSettings(
214 **instance_config['instance'])
215 kp_creator = keypairs_dict.get(
216 conf.get('keypair_name'))
218 'name']] = deploy_utils.create_vm_instance(
220 os_creds_dict, os_users_dict, conf),
222 image_creator.image_settings,
223 keypair_creator=kp_creator,
226 raise Exception('Image creator instance not found.'
227 ' Cannot instantiate')
229 raise Exception('Image dictionary is None. Cannot '
232 raise Exception('Instance configuration is None. Cannot '
234 logger.info('Created configured instances')
235 except Exception as e:
236 logger.error('Unexpected error creating VM instances - %s', e)
240 def __apply_ansible_playbooks(ansible_configs, os_creds_dict, vm_dict,
241 image_dict, flavor_dict, env_file):
243 Applies ansible playbooks to running VMs with floating IPs
244 :param ansible_configs: a list of Ansible configurations
245 :param os_creds_dict: Dictionary of OSCreds objects where the key is the
247 :param vm_dict: the dictionary of newly instantiated VMs where the name is
249 :param image_dict: the dictionary of newly instantiated images where the
251 :param flavor_dict: the dictionary of newly instantiated flavors where the
253 :param env_file: the path of the environment for setting the CWD so
254 playbook location is relative to the deployment file
255 :return: t/f - true if successful
257 logger.info("Applying Ansible Playbooks")
259 # Ensure all hosts are accepting SSH session requests
260 for vm_inst in list(vm_dict.values()):
261 if not vm_inst.vm_ssh_active(block=True):
263 "Timeout waiting for instance to respond to SSH requests")
266 # Set CWD so the deployment file's playbook location can leverage
268 orig_cwd = os.getcwd()
269 env_dir = os.path.dirname(env_file)
273 for ansible_config in ansible_configs:
274 if 'pre_sleep_time' in ansible_config:
276 sleep_time = int(ansible_config['pre_sleep_time'])
277 logger.info('Waiting %s seconds to apply playbooks',
279 time.sleep(sleep_time)
283 os_creds = os_creds_dict.get(None, 'admin')
284 __apply_ansible_playbook(ansible_config, os_creds, vm_dict,
285 image_dict, flavor_dict)
287 # Return to original directory
293 def __apply_ansible_playbook(ansible_config, os_creds, vm_dict, image_dict,
296 Applies an Ansible configuration setting
297 :param ansible_config: the configuration settings
298 :param os_creds: the OpenStack credentials object
299 :param vm_dict: the dictionary of newly instantiated VMs where the name is
301 :param image_dict: the dictionary of newly instantiated images where the
303 :param flavor_dict: the dictionary of newly instantiated flavors where the
307 (remote_user, floating_ips, private_key_filepath,
308 proxy_settings) = __get_connection_info(
309 ansible_config, vm_dict)
311 retval = ansible_utils.apply_playbook(
312 ansible_config['playbook_location'], floating_ips, remote_user,
313 private_key_filepath,
314 variables=__get_variables(ansible_config.get('variables'),
315 os_creds, vm_dict, image_dict,
317 proxy_setting=proxy_settings)
319 # Not a fatal type of event
321 'Unable to apply playbook found at location - %s',
322 ansible_config.get('playbook_location'))
325 def __get_connection_info(ansible_config, vm_dict):
327 Returns a tuple of data required for connecting to the running VMs
328 (remote_user, [floating_ips], private_key_filepath, proxy_settings)
329 :param ansible_config: the configuration settings
330 :param vm_dict: the dictionary of VMs where the VM name is the key
331 :return: tuple where the first element is the user and the second is a list
332 of floating IPs and the third is the
333 private key file location and the fourth is an instance of the
334 snaps.ProxySettings class
335 (note: in order to work, each of the hosts need to have the same sudo_user
336 and private key file location values)
338 if ansible_config.get('hosts'):
339 hosts = ansible_config['hosts']
341 floating_ips = list()
344 proxy_settings = None
346 vm = vm_dict.get(host)
348 fip = vm.get_floating_ip()
350 remote_user = vm.get_image_user()
353 floating_ips.append(fip.ip)
356 'Could not find floating IP for VM - ' +
359 pk_file = vm.keypair_settings.private_filepath
360 proxy_settings = vm.get_os_creds().proxy_settings
362 logger.error('Could not locate VM with name - ' + host)
364 return remote_user, floating_ips, pk_file, proxy_settings
368 def __get_variables(var_config, os_creds, vm_dict, image_dict, flavor_dict):
370 Returns a dictionary of substitution variables to be used for Ansible
372 :param var_config: the variable configuration settings
373 :param os_creds: the OpenStack credentials object
374 :param vm_dict: the dictionary of newly instantiated VMs where the name is
376 :param image_dict: the dictionary of newly instantiated images where the
378 :param flavor_dict: the dictionary of newly instantiated flavors where the
380 :return: dictionary or None
382 if var_config and vm_dict and len(vm_dict) > 0:
384 for key, value in var_config.items():
385 value = __get_variable_value(value, os_creds, vm_dict, image_dict,
388 variables[key] = value
390 "Set Jinga2 variable with key [%s] the value [%s]",
393 logger.warning('Key [%s] or Value [%s] must not be None',
394 str(key), str(value))
399 def __get_variable_value(var_config_values, os_creds, vm_dict, image_dict,
402 Returns the associated variable value for use by Ansible for substitution
404 :param var_config_values: the configuration dictionary
405 :param os_creds: the OpenStack credentials object
406 :param vm_dict: the dictionary of newly instantiated VMs where the name is
408 :param image_dict: the dictionary of newly instantiated images where the
410 :param flavor_dict: the dictionary of newly instantiated flavors where the
414 if var_config_values['type'] == 'string':
415 return __get_string_variable_value(var_config_values)
416 if var_config_values['type'] == 'vm-attr':
417 return __get_vm_attr_variable_value(var_config_values, vm_dict)
418 if var_config_values['type'] == 'os_creds':
419 return __get_os_creds_variable_value(var_config_values, os_creds)
420 if var_config_values['type'] == 'port':
421 return __get_vm_port_variable_value(var_config_values, vm_dict)
422 if var_config_values['type'] == 'floating_ip':
423 return __get_vm_fip_variable_value(var_config_values, vm_dict)
424 if var_config_values['type'] == 'image':
425 return __get_image_variable_value(var_config_values, image_dict)
426 if var_config_values['type'] == 'flavor':
427 return __get_flavor_variable_value(var_config_values, flavor_dict)
431 def __get_string_variable_value(var_config_values):
433 Returns the associated string value
434 :param var_config_values: the configuration dictionary
435 :return: the value contained in the dictionary with the key 'value'
437 return var_config_values['value']
440 def __get_vm_attr_variable_value(var_config_values, vm_dict):
442 Returns the associated value contained on a VM instance
443 :param var_config_values: the configuration dictionary
444 :param vm_dict: the dictionary containing all VMs where the key is the VM's
448 vm = vm_dict.get(var_config_values['vm_name'])
450 if var_config_values['value'] == 'floating_ip':
451 return vm.get_floating_ip().ip
452 if var_config_values['value'] == 'image_user':
453 return vm.get_image_user()
456 def __get_os_creds_variable_value(var_config_values, os_creds):
458 Returns the associated OS credentials value
459 :param var_config_values: the configuration dictionary
460 :param os_creds: the credentials
463 logger.info("Retrieving OS Credentials")
465 if var_config_values['value'] == 'username':
466 logger.info("Returning OS username")
467 return os_creds.username
468 elif var_config_values['value'] == 'password':
469 logger.info("Returning OS password")
470 return os_creds.password
471 elif var_config_values['value'] == 'auth_url':
472 logger.info("Returning OS auth_url")
473 return os_creds.auth_url
474 elif var_config_values['value'] == 'project_name':
475 logger.info("Returning OS project_name")
476 return os_creds.project_name
478 logger.info("Returning none")
482 def __get_vm_port_variable_value(var_config_values, vm_dict):
484 Returns the associated OS credentials value
485 :param var_config_values: the configuration dictionary
486 :param vm_dict: the dictionary containing all VMs where the key is the VM's
490 port_name = var_config_values.get('port_name')
491 vm_name = var_config_values.get('vm_name')
493 if port_name and vm_name:
494 vm = vm_dict.get(vm_name)
496 port_value_id = var_config_values.get('port_value')
498 if port_value_id == 'mac_address':
499 return vm.get_port_mac(port_name)
500 if port_value_id == 'ip_address':
501 return vm.get_port_ip(port_name)
504 def __get_vm_fip_variable_value(var_config_values, vm_dict):
506 Returns the floating IP value if found
507 :param var_config_values: the configuration dictionary
508 :param vm_dict: the dictionary containing all VMs where the key is the VM's
510 :return: the floating IP string value or None
512 fip_name = var_config_values.get('fip_name')
513 vm_name = var_config_values.get('vm_name')
516 vm = vm_dict.get(vm_name)
518 fip = vm.get_floating_ip(fip_name)
523 def __get_image_variable_value(var_config_values, image_dict):
525 Returns the associated image value
526 :param var_config_values: the configuration dictionary
527 :param image_dict: the dictionary containing all images where the key is
531 logger.info("Retrieving image values")
534 if var_config_values.get('image_name'):
535 image_creator = image_dict.get(var_config_values['image_name'])
537 if var_config_values.get('value') and \
538 var_config_values['value'] == 'id':
539 return image_creator.get_image().id
540 if var_config_values.get('value') and \
541 var_config_values['value'] == 'user':
542 return image_creator.image_settings.image_user
544 logger.info("Returning none")
548 def __get_flavor_variable_value(var_config_values, flavor_dict):
550 Returns the associated flavor value
551 :param var_config_values: the configuration dictionary
552 :param flavor_dict: the dictionary containing all flavor creators where the
554 :return: the value or None
556 logger.info("Retrieving flavor values")
559 if var_config_values.get('flavor_name'):
560 flavor_creator = flavor_dict.get(var_config_values['flavor_name'])
562 if var_config_values.get('value') and \
563 var_config_values['value'] == 'id':
564 return flavor_creator.get_flavor().id
569 Will need to set environment variable ANSIBLE_HOST_KEY_CHECKING=False or
570 Create a file located in /etc/ansible/ansible/cfg or ~/.ansible.cfg
571 containing the following content:
574 host_key_checking = False
576 CWD must be this directory where this script is located.
580 log_level = logging.INFO
581 if arguments.log_level != 'INFO':
582 log_level = logging.DEBUG
583 logging.basicConfig(level=log_level)
585 logger.info('Starting to Deploy')
587 # Apply env_file/substitution file to template
588 env = Environment(loader=FileSystemLoader(
589 searchpath=os.path.dirname(arguments.tmplt_file)))
590 template = env.get_template(os.path.basename(arguments.tmplt_file))
593 if arguments.env_file:
594 env_dict = file_utils.read_yaml(arguments.env_file)
595 output = template.render(**env_dict)
597 config = yaml.load(output)
600 os_config = config.get('openstack')
605 flavors_dict = dict()
606 os_creds_dict = dict()
607 clean = arguments.clean is not ARG_NOT_SET
610 os_creds_dict = __get_creds_dict(os_config)
614 projects_dict = __create_instances(
615 os_creds_dict, OpenStackProject, ProjectSettings,
616 os_config.get('projects'), 'project', clean)
617 creators.append(projects_dict)
620 users_dict = __create_instances(
621 os_creds_dict, OpenStackUser, UserSettings,
622 os_config.get('users'), 'user', clean)
623 creators.append(users_dict)
625 # Associate new users to projects
627 for project_creator in projects_dict.values():
628 users = project_creator.project_settings.users
629 for user_name in users:
630 user_creator = users_dict.get(user_name)
632 project_creator.assoc_user(
633 user_creator.get_user())
636 flavors_dict = __create_instances(
637 os_creds_dict, OpenStackFlavor, FlavorSettings,
638 os_config.get('flavors'), 'flavor', clean, users_dict)
639 creators.append(flavors_dict)
642 qos_dict = __create_instances(
643 os_creds_dict, OpenStackQoS, QoSSettings,
644 os_config.get('qos_specs'), 'qos_spec', clean, users_dict)
645 creators.append(qos_dict)
647 # Create volume types
648 vol_type_dict = __create_instances(
649 os_creds_dict, OpenStackVolumeType, VolumeTypeSettings,
650 os_config.get('volume_types'), 'volume_type', clean,
652 creators.append(vol_type_dict)
654 # Create volume types
655 vol_dict = __create_instances(
656 os_creds_dict, OpenStackVolume, VolumeSettings,
657 os_config.get('volumes'), 'volume', clean, users_dict)
658 creators.append(vol_dict)
661 images_dict = __create_instances(
662 os_creds_dict, OpenStackImage, ImageSettings,
663 os_config.get('images'), 'image', clean, users_dict)
664 creators.append(images_dict)
667 creators.append(__create_instances(
668 os_creds_dict, OpenStackNetwork, NetworkSettings,
669 os_config.get('networks'), 'network', clean, users_dict))
672 creators.append(__create_instances(
673 os_creds_dict, OpenStackRouter, RouterSettings,
674 os_config.get('routers'), 'router', clean, users_dict))
677 keypairs_dict = __create_instances(
678 os_creds_dict, OpenStackKeypair, KeypairSettings,
679 os_config.get('keypairs'), 'keypair', clean, users_dict)
680 creators.append(keypairs_dict)
682 # Create security groups
683 creators.append(__create_instances(
684 os_creds_dict, OpenStackSecurityGroup,
685 SecurityGroupSettings,
686 os_config.get('security_groups'), 'security_group', clean,
690 vm_dict = __create_vm_instances(
691 os_creds_dict, users_dict, os_config.get('instances'),
692 images_dict, keypairs_dict,
693 arguments.clean is not ARG_NOT_SET)
694 creators.append(vm_dict)
696 'Completed creating/retrieving all configured instances')
697 except Exception as e:
699 'Unexpected error deploying environment. Rolling back due'
703 # Must enter either block
704 if arguments.clean is not ARG_NOT_SET:
705 # Cleanup Environment
706 __cleanup(creators, arguments.clean_image is not ARG_NOT_SET)
707 elif arguments.deploy is not ARG_NOT_SET:
708 logger.info('Configuring NICs where required')
709 for vm in vm_dict.values():
711 logger.info('Completed NIC configuration')
714 ansible_config = config.get('ansible')
715 if ansible_config and vm_dict:
716 if not __apply_ansible_playbooks(ansible_config,
717 os_creds_dict, vm_dict,
718 images_dict, flavors_dict,
719 arguments.tmplt_file):
720 logger.error("Problem applying ansible playbooks")
723 'Unable to read configuration file - ' + arguments.tmplt_file)
729 def __cleanup(creators, clean_image=False):
730 for creator_dict in reversed(creators):
731 for key, creator in creator_dict.items():
732 if ((isinstance(creator, OpenStackImage) and clean_image)
733 or not isinstance(creator, OpenStackImage)):
736 except Exception as e:
737 logger.warning('Error cleaning component - %s', e)
740 if __name__ == '__main__':
741 # To ensure any files referenced via a relative path will begin from the
742 # directory in which this file resides
743 os.chdir(os.path.dirname(os.path.realpath(__file__)))
745 parser = argparse.ArgumentParser()
747 '-d', '--deploy', dest='deploy', nargs='?', default=ARG_NOT_SET,
748 help='When used, environment will be deployed and provisioned')
750 '-c', '--clean', dest='clean', nargs='?', default=ARG_NOT_SET,
751 help='When used, the environment will be removed')
753 '-i', '--clean-image', dest='clean_image', nargs='?',
755 help='When cleaning, if this is set, the image will be cleaned too')
757 '-t', '--tmplt', dest='tmplt_file', required=True,
758 help='The SNAPS deployment template YAML file - REQUIRED')
760 '-e', '--env-file', dest='env_file',
761 help='Yaml file containing substitution values to the env file')
763 '-l', '--log-level', dest='log_level', default='INFO',
764 help='Logging Level (INFO|DEBUG)')
765 args = parser.parse_args()
767 if args.deploy is ARG_NOT_SET and args.clean is ARG_NOT_SET:
769 'Must enter either -d for deploy or -c for cleaning up and '
772 if args.deploy is not ARG_NOT_SET and args.clean is not ARG_NOT_SET:
773 print('Cannot enter both options -d/--deploy and -c/--clean')