Added Ansible substitution value support for flavor IDs, image IDs, and image_user...
[snaps.git] / snaps / deploy_venv.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2016 Cable Television Laboratories, Inc. ("CableLabs")
4 #                    and others.  All rights reserved.
5 #
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:
9 #
10 #     http://www.apache.org/licenses/LICENSE-2.0
11 #
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.
17 #
18 # This script is responsible for deploying virtual environments
19 import argparse
20 import logging
21 import os
22 import re
23
24 from snaps import file_utils
25 from snaps.openstack.create_flavor import FlavorSettings, OpenStackFlavor
26 from snaps.openstack.create_image import ImageSettings
27 from snaps.openstack.create_instance import VmInstanceSettings
28 from snaps.openstack.create_network import PortSettings, NetworkSettings
29 from snaps.openstack.create_router import RouterSettings
30 from snaps.openstack.create_keypairs import KeypairSettings
31 from snaps.openstack.os_credentials import OSCreds, ProxySettings
32 from snaps.openstack.utils import deploy_utils
33 from snaps.provisioning import ansible_utils
34
35 __author__ = 'spisarski'
36
37 logger = logging.getLogger('deploy_venv')
38
39 ARG_NOT_SET = "argument not set"
40
41
42 def __get_os_credentials(os_conn_config):
43     """
44     Returns an object containing all of the information required to access OpenStack APIs
45     :param os_conn_config: The configuration holding the credentials
46     :return: an OSCreds instance
47     """
48     proxy_settings = None
49     http_proxy = os_conn_config.get('http_proxy')
50     if http_proxy:
51         tokens = re.split(':', http_proxy)
52         ssh_proxy_cmd = os_conn_config.get('ssh_proxy_cmd')
53         proxy_settings = ProxySettings(tokens[0], tokens[1], ssh_proxy_cmd)
54
55     return OSCreds(username=os_conn_config.get('username'),
56                    password=os_conn_config.get('password'),
57                    auth_url=os_conn_config.get('auth_url'),
58                    project_name=os_conn_config.get('project_name'),
59                    proxy_settings=proxy_settings)
60
61
62 def __parse_ports_config(config):
63     """
64     Parses the "ports" configuration
65     :param config: The dictionary to parse
66     :param os_creds: The OpenStack credentials object
67     :return: a list of PortConfig objects
68     """
69     out = list()
70     for port_config in config:
71         out.append(PortSettings(config=port_config.get('port')))
72     return out
73
74
75 def __create_flavors(os_conn_config, flavors_config, cleanup=False):
76     """
77     Returns a dictionary of flavors where the key is the image name and the value is the image object
78     :param os_conn_config: The OpenStack connection credentials
79     :param flavors_config: The list of image configurations
80     :param cleanup: Denotes whether or not this is being called for cleanup or not
81     :return: dictionary
82     """
83     flavors = {}
84
85     if flavors_config:
86         try:
87             for flavor_config_dict in flavors_config:
88                 flavor_config = flavor_config_dict.get('flavor')
89                 if flavor_config and flavor_config.get('name'):
90                     flavor_creator = OpenStackFlavor(__get_os_credentials(os_conn_config),
91                                                      FlavorSettings(flavor_config))
92                     flavor_creator.create(cleanup=cleanup)
93                     flavors[flavor_config['name']] = flavor_creator
94         except Exception as e:
95             for key, flavor_creator in flavors.iteritems():
96                 flavor_creator.clean()
97             raise e
98         logger.info('Created configured flavors')
99
100     return flavors
101
102
103 def __create_images(os_conn_config, images_config, cleanup=False):
104     """
105     Returns a dictionary of images where the key is the image name and the value is the image object
106     :param os_conn_config: The OpenStack connection credentials
107     :param images_config: The list of image configurations
108     :param cleanup: Denotes whether or not this is being called for cleanup or not
109     :return: dictionary
110     """
111     images = {}
112
113     if images_config:
114         try:
115             for image_config_dict in images_config:
116                 image_config = image_config_dict.get('image')
117                 if image_config and image_config.get('name'):
118                     images[image_config['name']] = deploy_utils.create_image(__get_os_credentials(os_conn_config),
119                                                                              ImageSettings(image_config), cleanup)
120         except Exception as e:
121             for key, image_creator in images.iteritems():
122                 image_creator.clean()
123             raise e
124         logger.info('Created configured images')
125
126     return images
127
128
129 def __create_networks(os_conn_config, network_confs, cleanup=False):
130     """
131     Returns a dictionary of networks where the key is the network name and the value is the network object
132     :param os_conn_config: The OpenStack connection credentials
133     :param network_confs: The list of network configurations
134     :param cleanup: Denotes whether or not this is being called for cleanup or not
135     :return: dictionary
136     """
137     network_dict = {}
138
139     if network_confs:
140         try:
141             for network_conf in network_confs:
142                 net_name = network_conf['network']['name']
143                 os_creds = __get_os_credentials(os_conn_config)
144                 network_dict[net_name] = deploy_utils.create_network(
145                     os_creds, NetworkSettings(config=network_conf['network']), cleanup)
146         except Exception as e:
147             for key, net_creator in network_dict.iteritems():
148                 net_creator.clean()
149             raise e
150
151         logger.info('Created configured networks')
152
153     return network_dict
154
155
156 def __create_routers(os_conn_config, router_confs, cleanup=False):
157     """
158     Returns a dictionary of networks where the key is the network name and the value is the network object
159     :param os_conn_config: The OpenStack connection credentials
160     :param router_confs: The list of router configurations
161     :param cleanup: Denotes whether or not this is being called for cleanup or not
162     :return: dictionary
163     """
164     router_dict = {}
165     os_creds = __get_os_credentials(os_conn_config)
166
167     if router_confs:
168         try:
169             for router_conf in router_confs:
170                 router_name = router_conf['router']['name']
171                 router_dict[router_name] = deploy_utils.create_router(
172                     os_creds, RouterSettings(config=router_conf['router']), cleanup)
173         except Exception as e:
174             for key, router_creator in router_dict.iteritems():
175                 router_creator.clean()
176             raise e
177
178         logger.info('Created configured networks')
179
180     return router_dict
181
182
183 def __create_keypairs(os_conn_config, keypair_confs, cleanup=False):
184     """
185     Returns a dictionary of keypairs where the key is the keypair name and the value is the keypair object
186     :param os_conn_config: The OpenStack connection credentials
187     :param keypair_confs: The list of keypair configurations
188     :param cleanup: Denotes whether or not this is being called for cleanup or not
189     :return: dictionary
190     """
191     keypairs_dict = {}
192     if keypair_confs:
193         try:
194             for keypair_dict in keypair_confs:
195                 keypair_config = keypair_dict['keypair']
196                 kp_settings = KeypairSettings(keypair_config)
197                 keypairs_dict[keypair_config['name']] = deploy_utils.create_keypair(
198                     __get_os_credentials(os_conn_config), kp_settings, cleanup)
199         except Exception as e:
200             for key, keypair_creator in keypairs_dict.iteritems():
201                 keypair_creator.clean()
202             raise e
203
204         logger.info('Created configured keypairs')
205
206     return keypairs_dict
207
208
209 def __create_instances(os_conn_config, instances_config, image_dict, keypairs_dict, cleanup=False):
210     """
211     Returns a dictionary of instances where the key is the instance name and the value is the VM object
212     :param os_conn_config: The OpenStack connection credentials
213     :param instances_config: The list of VM instance configurations
214     :param image_dict: A dictionary of images that will probably be used to instantiate the VM instance
215     :param keypairs_dict: A dictionary of keypairs that will probably be used to instantiate the VM instance
216     :param cleanup: Denotes whether or not this is being called for cleanup or not
217     :return: dictionary
218     """
219     os_creds = __get_os_credentials(os_conn_config)
220
221     vm_dict = {}
222
223     if instances_config:
224         try:
225             for instance_config in instances_config:
226                 conf = instance_config.get('instance')
227                 if conf:
228                     if image_dict:
229                         image_creator = image_dict.get(conf.get('imageName'))
230                         if image_creator:
231                             instance_settings = VmInstanceSettings(config=instance_config['instance'])
232                             kp_name = conf.get('keypair_name')
233                             vm_dict[conf['name']] = deploy_utils.create_vm_instance(
234                                 os_creds, instance_settings, image_creator.image_settings,
235                                 keypair_creator=keypairs_dict[kp_name], cleanup=cleanup)
236                         else:
237                             raise Exception('Image creator instance not found. Cannot instantiate')
238                     else:
239                         raise Exception('Image dictionary is None. Cannot instantiate')
240                 else:
241                     raise Exception('Instance configuration is None. Cannot instantiate')
242         except Exception as e:
243             logger.error('Unexpected error creating instances. Attempting to cleanup environment - ' + e.message)
244             for key, inst_creator in vm_dict.iteritems():
245                 inst_creator.clean()
246             raise e
247
248         logger.info('Created configured instances')
249
250     return vm_dict
251
252
253 def __apply_ansible_playbooks(ansible_configs, os_conn_config, vm_dict, image_dict, flavor_dict, env_file):
254     """
255     Applies ansible playbooks to running VMs with floating IPs
256     :param ansible_configs: a list of Ansible configurations
257     :param os_conn_config: the OpenStack connection configuration used to create an OSCreds instance
258     :param vm_dict: the dictionary of newly instantiated VMs where the name is the key
259     :param image_dict: the dictionary of newly instantiated images where the name is the key
260     :param flavor_dict: the dictionary of newly instantiated flavors where the name is the key
261     :param env_file: the path of the environment for setting the CWD so playbook location is relative to the deployment
262                      file
263     :return: t/f - true if successful
264     """
265     logger.info("Applying Ansible Playbooks")
266     if ansible_configs:
267         # Ensure all hosts are accepting SSH session requests
268         for vm_inst in vm_dict.values():
269             if not vm_inst.vm_ssh_active(block=True):
270                 logger.warn("Timeout waiting for instance to respond to SSH requests")
271                 return False
272
273         # Set CWD so the deployment file's playbook location can leverage relative paths
274         orig_cwd = os.getcwd()
275         env_dir = os.path.dirname(env_file)
276         os.chdir(env_dir)
277
278         # Apply playbooks
279         for ansible_config in ansible_configs:
280             os_creds = __get_os_credentials(os_conn_config)
281             __apply_ansible_playbook(ansible_config, os_creds, vm_dict, image_dict, flavor_dict)
282
283         # Return to original directory
284         os.chdir(orig_cwd)
285
286     return True
287
288
289 def __apply_ansible_playbook(ansible_config, os_creds, vm_dict, image_dict, flavor_dict):
290     """
291     Applies an Ansible configuration setting
292     :param ansible_config: the configuration settings
293     :param os_creds: the OpenStack credentials object
294     :param vm_dict: the dictionary of newly instantiated VMs where the name is the key
295     :param image_dict: the dictionary of newly instantiated images where the name is the key
296     :param flavor_dict: the dictionary of newly instantiated flavors where the name is the key
297     """
298     if ansible_config:
299         remote_user, floating_ips, private_key_filepath, proxy_settings = __get_connection_info(ansible_config, vm_dict)
300         if floating_ips:
301             retval = ansible_utils.apply_playbook(
302                 ansible_config['playbook_location'], floating_ips, remote_user, private_key_filepath,
303                 variables=__get_variables(ansible_config.get('variables'), os_creds, vm_dict, image_dict, flavor_dict),
304                 proxy_setting=proxy_settings)
305             if retval != 0:
306                 # Not a fatal type of event
307                 logger.warn('Unable to apply playbook found at location - ' + ansible_config('playbook_location'))
308
309
310 def __get_connection_info(ansible_config, vm_dict):
311     """
312     Returns a tuple of data required for connecting to the running VMs
313     (remote_user, [floating_ips], private_key_filepath, proxy_settings)
314     :param ansible_config: the configuration settings
315     :param vm_dict: the dictionary of VMs where the VM name is the key
316     :return: tuple where the first element is the user and the second is a list of floating IPs and the third is the
317     private key file location and the fourth is an instance of the snaps.ProxySettings class
318     (note: in order to work, each of the hosts need to have the same sudo_user and private key file location values)
319     """
320     if ansible_config.get('hosts'):
321         hosts = ansible_config['hosts']
322         if len(hosts) > 0:
323             floating_ips = list()
324             remote_user = None
325             private_key_filepath = None
326             proxy_settings = None
327             for host in hosts:
328                 vm = vm_dict.get(host)
329                 if vm:
330                     fip = vm.get_floating_ip()
331                     if fip:
332                         remote_user = vm.get_image_user()
333
334                         if fip:
335                             floating_ips.append(fip.ip)
336                         else:
337                             raise Exception('Could not find floating IP for VM - ' + vm.name)
338
339                         private_key_filepath = vm.keypair_settings.private_filepath
340                         proxy_settings = vm.get_os_creds().proxy_settings
341                 else:
342                     logger.error('Could not locate VM with name - ' + host)
343
344             return remote_user, floating_ips, private_key_filepath, proxy_settings
345     return None
346
347
348 def __get_variables(var_config, os_creds, vm_dict, image_dict, flavor_dict):
349     """
350     Returns a dictionary of substitution variables to be used for Ansible templates
351     :param var_config: the variable configuration settings
352     :param os_creds: the OpenStack credentials object
353     :param vm_dict: the dictionary of newly instantiated VMs where the name is the key
354     :param image_dict: the dictionary of newly instantiated images where the name is the key
355     :param flavor_dict: the dictionary of newly instantiated flavors where the name is the key
356     :return: dictionary or None
357     """
358     if var_config and vm_dict and len(vm_dict) > 0:
359         variables = dict()
360         for key, value in var_config.iteritems():
361             value = __get_variable_value(value, os_creds, vm_dict, image_dict, flavor_dict)
362             if key and value:
363                 variables[key] = value
364                 logger.info("Set Jinga2 variable with key [" + key + "] the value [" + value + ']')
365             else:
366                 logger.warn('Key [' + str(key) + '] or Value [' + str(value) + '] must not be None')
367         return variables
368     return None
369
370
371 def __get_variable_value(var_config_values, os_creds, vm_dict, image_dict, flavor_dict):
372     """
373     Returns the associated variable value for use by Ansible for substitution purposes
374     :param var_config_values: the configuration dictionary
375     :param os_creds: the OpenStack credentials object
376     :param vm_dict: the dictionary of newly instantiated VMs where the name is the key
377     :param image_dict: the dictionary of newly instantiated images where the name is the key
378     :param flavor_dict: the dictionary of newly instantiated flavors where the name is the key
379     :return:
380     """
381     if var_config_values['type'] == 'string':
382         return __get_string_variable_value(var_config_values)
383     if var_config_values['type'] == 'vm-attr':
384         return __get_vm_attr_variable_value(var_config_values, vm_dict)
385     if var_config_values['type'] == 'os_creds':
386         return __get_os_creds_variable_value(var_config_values, os_creds)
387     if var_config_values['type'] == 'port':
388         return __get_vm_port_variable_value(var_config_values, vm_dict)
389     if var_config_values['type'] == 'image':
390         return __get_image_variable_value(var_config_values, image_dict)
391     if var_config_values['type'] == 'flavor':
392         return __get_flavor_variable_value(var_config_values, flavor_dict)
393     return None
394
395
396 def __get_string_variable_value(var_config_values):
397     """
398     Returns the associated string value
399     :param var_config_values: the configuration dictionary
400     :return: the value contained in the dictionary with the key 'value'
401     """
402     return var_config_values['value']
403
404
405 def __get_vm_attr_variable_value(var_config_values, vm_dict):
406     """
407     Returns the associated value contained on a VM instance
408     :param var_config_values: the configuration dictionary
409     :param vm_dict: the dictionary containing all VMs where the key is the VM's name
410     :return: the value
411     """
412     vm = vm_dict.get(var_config_values['vm_name'])
413     if vm:
414         if var_config_values['value'] == 'floating_ip':
415             return vm.get_floating_ip().ip
416         if var_config_values['value'] == 'image_user':
417             return vm.get_image_user()
418
419
420 def __get_os_creds_variable_value(var_config_values, os_creds):
421     """
422     Returns the associated OS credentials value
423     :param var_config_values: the configuration dictionary
424     :param os_creds: the credentials
425     :return: the value
426     """
427     logger.info("Retrieving OS Credentials")
428     if os_creds:
429         if var_config_values['value'] == 'username':
430             logger.info("Returning OS username")
431             return os_creds.username
432         elif var_config_values['value'] == 'password':
433             logger.info("Returning OS password")
434             return os_creds.password
435         elif var_config_values['value'] == 'auth_url':
436             logger.info("Returning OS auth_url")
437             return os_creds.auth_url
438         elif var_config_values['value'] == 'project_name':
439             logger.info("Returning OS project_name")
440             return os_creds.project_name
441
442     logger.info("Returning none")
443     return None
444
445
446 def __get_vm_port_variable_value(var_config_values, vm_dict):
447     """
448     Returns the associated OS credentials value
449     :param var_config_values: the configuration dictionary
450     :param vm_dict: the dictionary containing all VMs where the key is the VM's name
451     :return: the value
452     """
453     port_name = var_config_values.get('port_name')
454     vm_name = var_config_values.get('vm_name')
455
456     if port_name and vm_name:
457         vm = vm_dict.get(vm_name)
458         if vm:
459             port_value_id = var_config_values.get('port_value')
460             if port_value_id:
461                 if port_value_id == 'mac_address':
462                     return vm.get_port_mac(port_name)
463                 if port_value_id == 'ip_address':
464                     return vm.get_port_ip(port_name)
465
466
467 def __get_image_variable_value(var_config_values, image_dict):
468     """
469     Returns the associated image value
470     :param var_config_values: the configuration dictionary
471     :param image_dict: the dictionary containing all images where the key is the name
472     :return: the value
473     """
474     logger.info("Retrieving image values")
475
476     if image_dict:
477         if var_config_values.get('image_name'):
478             image_creator = image_dict.get(var_config_values['image_name'])
479             if image_creator:
480                 if var_config_values.get('value') and var_config_values['value'] == 'id':
481                     return image_creator.get_image().id
482                 if var_config_values.get('value') and var_config_values['value'] == 'user':
483                     return image_creator.image_settings.image_user
484
485     logger.info("Returning none")
486     return None
487
488
489 def __get_flavor_variable_value(var_config_values, flavor_dict):
490     """
491     Returns the associated flavor value
492     :param var_config_values: the configuration dictionary
493     :param flavor_dict: the dictionary containing all flavor creators where the key is the name
494     :return: the value or None
495     """
496     logger.info("Retrieving flavor values")
497
498     if flavor_dict:
499         if var_config_values.get('flavor_name'):
500             flavor_creator = flavor_dict.get(var_config_values['flavor_name'])
501             if flavor_creator:
502                 if var_config_values.get('value') and var_config_values['value'] == 'id':
503                     return flavor_creator.get_flavor().id
504
505     logger.info("Returning none")
506     return None
507
508
509 def main(arguments):
510     """
511     Will need to set environment variable ANSIBLE_HOST_KEY_CHECKING=False or ...
512     Create a file located in /etc/ansible/ansible/cfg or ~/.ansible.cfg containing the following content:
513
514     [defaults]
515     host_key_checking = False
516
517     CWD must be this directory where this script is located.
518
519     :return: To the OS
520     """
521     log_level = logging.INFO
522     if arguments.log_level != 'INFO':
523         log_level = logging.DEBUG
524     logging.basicConfig(level=log_level)
525
526     logger.info('Starting to Deploy')
527     config = file_utils.read_yaml(arguments.environment)
528     logger.info('Read configuration file - ' + arguments.environment)
529
530     if config:
531         os_config = config.get('openstack')
532
533         image_dict = {}
534         network_dict = {}
535         router_dict = {}
536         keypairs_dict = {}
537         vm_dict = {}
538
539         if os_config:
540             try:
541                 os_conn_config = os_config.get('connection')
542
543                 # Create flavors
544                 flavor_dict = __create_flavors(os_conn_config, os_config.get('flavors'),
545                                               arguments.clean is not ARG_NOT_SET)
546
547                 # Create images
548                 image_dict = __create_images(os_conn_config, os_config.get('images'),
549                                              arguments.clean is not ARG_NOT_SET)
550
551                 # Create network
552                 network_dict = __create_networks(os_conn_config, os_config.get('networks'),
553                                                  arguments.clean is not ARG_NOT_SET)
554
555                 # Create network
556                 router_dict = __create_routers(os_conn_config, os_config.get('routers'),
557                                                arguments.clean is not ARG_NOT_SET)
558
559                 # Create keypairs
560                 keypairs_dict = __create_keypairs(os_conn_config, os_config.get('keypairs'),
561                                                   arguments.clean is not ARG_NOT_SET)
562
563                 # Create instance
564                 vm_dict = __create_instances(os_conn_config, os_config.get('instances'), image_dict, keypairs_dict,
565                                              arguments.clean is not ARG_NOT_SET)
566                 logger.info('Completed creating/retrieving all configured instances')
567             except Exception as e:
568                 logger.error('Unexpected error deploying environment. Rolling back due to - ' + e.message)
569                 __cleanup(vm_dict, keypairs_dict, router_dict, network_dict, image_dict, flavor_dict, True)
570                 raise e
571
572
573         # Must enter either block
574         if arguments.clean is not ARG_NOT_SET:
575             # Cleanup Environment
576             __cleanup(vm_dict, keypairs_dict, router_dict, network_dict, image_dict, flavor_dict,
577                       arguments.clean_image is not ARG_NOT_SET)
578         elif arguments.deploy is not ARG_NOT_SET:
579             logger.info('Configuring NICs where required')
580             for vm in vm_dict.itervalues():
581                 vm.config_nics()
582             logger.info('Completed NIC configuration')
583
584             # Provision VMs
585             ansible_config = config.get('ansible')
586             if ansible_config and vm_dict:
587                 if not __apply_ansible_playbooks(ansible_config, os_conn_config, vm_dict, image_dict, flavor_dict,
588                                                  arguments.environment):
589                     logger.error("Problem applying ansible playbooks")
590     else:
591         logger.error('Unable to read configuration file - ' + arguments.environment)
592         exit(1)
593
594     exit(0)
595
596
597 def __cleanup(vm_dict, keypairs_dict, router_dict, network_dict, image_dict, flavor_dict, clean_image=False):
598     for key, vm_inst in vm_dict.iteritems():
599         vm_inst.clean()
600     for key, kp_inst in keypairs_dict.iteritems():
601         kp_inst.clean()
602     for key, router_inst in router_dict.iteritems():
603         router_inst.clean()
604     for key, net_inst in network_dict.iteritems():
605         net_inst.clean()
606     if clean_image:
607         for key, image_inst in image_dict.iteritems():
608             image_inst.clean()
609     for key, flavor_inst in flavor_dict.iteritems():
610         flavor_inst.clean()
611
612
613 if __name__ == '__main__':
614     # To ensure any files referenced via a relative path will begin from the diectory in which this file resides
615     os.chdir(os.path.dirname(os.path.realpath(__file__)))
616
617     parser = argparse.ArgumentParser()
618     parser.add_argument('-d', '--deploy', dest='deploy', nargs='?', default=ARG_NOT_SET,
619                         help='When used, environment will be deployed and provisioned')
620     parser.add_argument('-c', '--clean', dest='clean', nargs='?', default=ARG_NOT_SET,
621                         help='When used, the environment will be removed')
622     parser.add_argument('-i', '--clean-image', dest='clean_image', nargs='?', default=ARG_NOT_SET,
623                         help='When cleaning, if this is set, the image will be cleaned too')
624     parser.add_argument('-e', '--env', dest='environment', required=True,
625                         help='The environment configuration YAML file - REQUIRED')
626     parser.add_argument('-l', '--log-level', dest='log_level', default='INFO', help='Logging Level (INFO|DEBUG)')
627     args = parser.parse_args()
628
629     if args.deploy is ARG_NOT_SET and args.clean is ARG_NOT_SET:
630         print 'Must enter either -d for deploy or -c for cleaning up and environment'
631         exit(1)
632     if args.deploy is not ARG_NOT_SET and args.clean is not ARG_NOT_SET:
633         print 'Cannot enter both options -d/--deploy and -c/--clean'
634         exit(1)
635     main(args)