Adds NSDriver to Neutron agent drivers
[apex.git] / lib / python / apex_python_utils.py
1 ##############################################################################
2 # Copyright (c) 2016 Feng Pan (fpan@redhat.com), Dan Radez (dradez@redhat.com)
3 #
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9
10 import argparse
11 import sys
12 import logging
13 import os
14 import yaml
15
16 from copy import copy
17
18 from jinja2 import Environment
19 from jinja2 import FileSystemLoader
20
21 from apex import NetworkSettings
22 from apex import NetworkEnvironment
23 from apex import DeploySettings
24 from apex import ip_utils
25 from apex.common.constants import ADMIN_NETWORK
26
27
28 def parse_net_settings(args):
29     """
30     Parse OPNFV Apex network_settings.yaml config file
31     and dump bash syntax to set environment variables
32
33     Args:
34     - file: string
35       file to network_settings.yaml file
36     - network_isolation: bool
37       enable or disable network_isolation
38     """
39     settings = NetworkSettings(args.net_settings_file,
40                                args.network_isolation)
41     net_env = NetworkEnvironment(settings, args.net_env_file,
42                                  args.compute_pre_config,
43                                  args.controller_pre_config)
44     dump_yaml(dict(net_env), '/tmp/network-environment.yaml')
45     settings.dump_bash()
46
47
48 def dump_yaml(data, file):
49     """
50     Dumps data to a file as yaml
51     :param data: yaml to be written to file
52     :param file: filename to write to
53     :return:
54     """
55     with open(file, "w") as fh:
56         yaml.dump(data, fh, default_flow_style=False)
57
58
59 def parse_deploy_settings(args):
60     settings = DeploySettings(args.file)
61     settings.dump_bash()
62
63
64 def find_ip(args):
65     """
66     Get and print the IP from a specific interface
67
68     Args:
69     - interface: string
70       network interface name
71     - address_family: int
72       4 or 6, respective to ipv4 or ipv6
73     """
74     interface = ip_utils.get_interface(args.interface,
75                                        args.address_family)
76     if interface:
77         print(interface.ip)
78
79
80 def build_nic_template(args):
81     """
82     Build and print a Triple-O nic template from jinja template
83
84     Args:
85     - template: string
86       path to jinja template to load
87     - enabled_networks: comma delimited list
88       list of networks defined in net_env.py
89     - ext_net_type: string
90       interface or br-ex, defines the external network configuration
91     - address_family: string
92       4 or 6, respective to ipv4 or ipv6
93     - ovs_dpdk_bridge: string
94       bridge name to use as ovs_dpdk
95     """
96     template_dir, template = args.template.rsplit('/', 1)
97
98     network_settings = NetworkSettings(args.net_settings_file,
99                                        args.network_isolation)
100     env = Environment(loader=FileSystemLoader(template_dir))
101     template = env.get_template(template)
102
103     # gather vlan values into a dict
104     net_list = copy(args.enabled_networks).split(' ')
105     net_list.remove(ADMIN_NETWORK)
106     vlans_vals = map(lambda x: network_settings[x]['vlan'], net_list)
107     vlans = dict(zip(net_list, vlans_vals))
108     nics = network_settings.nics
109
110     print(template.render(enabled_networks=args.enabled_networks,
111                           role=args.role,
112                           vlans=vlans,
113                           external_net_type=args.ext_net_type,
114                           external_net_af=args.address_family,
115                           ovs_dpdk_bridge=args.ovs_dpdk_bridge,
116                           nics=nics))
117
118
119 def get_parser():
120     parser = argparse.ArgumentParser()
121     parser.add_argument('--debug', action='store_true', default=False,
122                         help="Turn on debug messages")
123     parser.add_argument('-l', '--log-file', default='/var/log/apex/apex.log',
124                         dest='log_file', help="Log file to log to")
125     subparsers = parser.add_subparsers()
126
127     net_settings = subparsers.add_parser('parse-net-settings',
128                                          help='Parse network settings file')
129     net_settings.add_argument('-s', '--net-settings-file',
130                               default='network-settings.yaml',
131                               dest='net_settings_file',
132                               help='path to network settings file')
133     net_settings.add_argument('--flat', action='store_false',
134                               default=True, dest='network_isolation',
135                               help='disable network isolation')
136     net_settings.add_argument('-e', '--net-env-file',
137                               default="network-environment.yaml",
138                               dest='net_env_file',
139                               help='path to network environment file')
140     net_settings.add_argument('--compute-pre-config',
141                               default=False,
142                               action='store_true',
143                               dest='compute_pre_config',
144                               help='Boolean to enable Compute Pre Config')
145     net_settings.add_argument('--controller-pre-config',
146                               action='store_true',
147                               default=False,
148                               dest='controller_pre_config',
149                               help='Boolean to enable Controller Pre Config')
150
151     net_settings.set_defaults(func=parse_net_settings)
152
153     get_int_ip = subparsers.add_parser('find-ip',
154                                        help='Find interface ip')
155     get_int_ip.add_argument('-i', '--interface', required=True,
156                             help='Interface name')
157     get_int_ip.add_argument('-af', '--address-family', default=4, type=int,
158                             choices=[4, 6], dest='address_family',
159                             help='IP Address family')
160     get_int_ip.set_defaults(func=find_ip)
161
162     nic_template = subparsers.add_parser('nic-template',
163                                          help='Build NIC templates')
164     nic_template.add_argument('-r', '--role', required=True,
165                               choices=['controller', 'compute'],
166                               help='Role template generated for')
167     nic_template.add_argument('-t', '--template', required=True,
168                               dest='template',
169                               help='Template file to process')
170     nic_template.add_argument('-s', '--net-settings-file',
171                               default='network-settings.yaml',
172                               dest='net_settings_file',
173                               help='path to network settings file')
174     nic_template.add_argument('--flat', action='store_false',
175                               default=True, dest='network_isolation',
176                               help='disable network isolation')
177     nic_template.add_argument('-n', '--enabled-networks', required=True,
178                               dest='enabled_networks',
179                               help='enabled network list')
180     nic_template.add_argument('-e', '--ext-net-type', default='interface',
181                               dest='ext_net_type',
182                               choices=['interface', 'br-ex'],
183                               help='External network type')
184     nic_template.add_argument('-af', '--address-family', type=int, default=4,
185                               dest='address_family', help='IP address family')
186     nic_template.add_argument('-d', '--ovs-dpdk-bridge',
187                               default=None, dest='ovs_dpdk_bridge',
188                               help='OVS DPDK Bridge Name')
189     nic_template.set_defaults(func=build_nic_template)
190
191     deploy_settings = subparsers.add_parser('parse-deploy-settings',
192                                             help='Parse deploy settings file')
193     deploy_settings.add_argument('-f', '--file',
194                                  default='deploy_settings.yaml',
195                                  help='path to deploy settings file')
196     deploy_settings.set_defaults(func=parse_deploy_settings)
197
198     return parser
199
200
201 def main():
202     parser = get_parser()
203     args = parser.parse_args(sys.argv[1:])
204     if args.debug:
205         logging.basicConfig(level=logging.DEBUG)
206     else:
207         apex_log_filename = args.log_file
208         os.makedirs(os.path.dirname(apex_log_filename), exist_ok=True)
209         logging.basicConfig(filename=apex_log_filename,
210                             format='%(asctime)s %(levelname)s: %(message)s',
211                             datefmt='%m/%d/%Y %I:%M:%S %p',
212                             level=logging.DEBUG)
213     if hasattr(args, 'func'):
214         args.func(args)
215     else:
216         parser.print_help()
217         exit(1)
218
219 if __name__ == "__main__":
220     main()