c9dcaa555f849af45f1bb0f33119b4211cae5737
[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 apex
13 import logging
14 import os
15 import yaml
16 from jinja2 import Environment, FileSystemLoader
17
18
19 def parse_net_settings(args):
20     """
21     Parse OPNFV Apex network_settings.yaml config file
22     and dump bash syntax to set environment variables
23
24     Args:
25     - file: string
26       file to network_settings.yaml file
27     - network_isolation: bool
28       enable or disable network_isolation
29     """
30     settings = apex.NetworkSettings(args.net_settings_file,
31                                     args.network_isolation)
32     net_env = apex.NetworkEnvironment(settings, args.net_env_file)
33     dump_yaml(net_env.get_netenv_settings(), '/tmp/network-environment.yaml')
34     settings.dump_bash()
35
36
37 def dump_yaml(data, file):
38     """
39     Dumps data to a file as yaml
40     :param data: yaml to be written to file
41     :param file: filename to write to
42     :return:
43     """
44     with open(file, "w") as fh:
45         yaml.dump(data, fh, default_flow_style=False)
46
47
48 def parse_deploy_settings(args):
49     settings = apex.DeploySettings(args.file)
50     settings.dump_bash()
51
52
53 def find_ip(args):
54     """
55     Get and print the IP from a specific interface
56
57     Args:
58     - interface: string
59       network interface name
60     - address_family: int
61       4 or 6, respective to ipv4 or ipv6
62     """
63     interface = apex.ip_utils.get_interface(args.interface,
64                                             args.address_family)
65     if interface:
66         print(interface.ip)
67
68
69 def build_nic_template(args):
70     """
71     Build and print a Triple-O nic template from jinja template
72
73     Args:
74     - template: string
75       path to jinja template to load
76     - enabled_networks: comma delimited list
77       list of networks defined in net_env.py
78     - ext_net_type: string
79       interface or br-ex, defines the external network configuration
80     - address_family: string
81       4 or 6, respective to ipv4 or ipv6
82     - ovs_dpdk_bridge: string
83       bridge name to use as ovs_dpdk
84     """
85     template_dir, template = args.template.rsplit('/', 1)
86
87     env = Environment(loader=FileSystemLoader(template_dir))
88     template = env.get_template(template)
89     print(template.render(enabled_networks=args.enabled_networks,
90                           external_net_type=args.ext_net_type,
91                           external_net_af=args.address_family,
92                           ovs_dpdk_bridge=args.ovs_dpdk_bridge))
93
94
95 def parse_args():
96     parser = argparse.ArgumentParser()
97     parser.add_argument('--debug', action='store_true', default=False,
98                         help="Turn on debug messages")
99     parser.add_argument('-l', '--log-file', default='/var/log/apex/apex.log',
100                         dest='log_file', help="Log file to log to")
101     subparsers = parser.add_subparsers()
102
103     net_settings = subparsers.add_parser('parse-net-settings',
104                                          help='Parse network settings file')
105     net_settings.add_argument('-s', '--net-settings-file',
106                               default='network-settings.yaml',
107                               dest='net_settings_file',
108                               help='path to network settings file')
109     net_settings.add_argument('-i', '--network-isolation', type=bool,
110                               default=True, dest='network_isolation',
111                               help='network isolation')
112     net_settings.add_argument('-e', '--net-env-file',
113                               default="network-environment.yaml",
114                               dest='net_env_file',
115                               help='path to network environment file')
116     net_settings.set_defaults(func=parse_net_settings)
117
118     get_int_ip = subparsers.add_parser('find-ip',
119                                        help='Find interface ip')
120     get_int_ip.add_argument('-i', '--interface', required=True,
121                             help='Interface name')
122     get_int_ip.add_argument('-af', '--address-family', default=4, type=int,
123                             choices=[4, 6], dest='address_family',
124                             help='IP Address family')
125     get_int_ip.set_defaults(func=find_ip)
126
127     nic_template = subparsers.add_parser('nic-template',
128                                          help='Build NIC templates')
129     nic_template.add_argument('-t', '--template', required=True,
130                               dest='template',
131                               help='Template file to process')
132     nic_template.add_argument('-n', '--enabled-networks', required=True,
133                               dest='enabled_networks',
134                               help='enabled network list')
135     nic_template.add_argument('-e', '--ext-net-type', default='interface',
136                               dest='ext_net_type',
137                               choices=['interface', 'br-ex'],
138                               help='External network type')
139     nic_template.add_argument('-af', '--address-family', type=int, default=4,
140                               dest='address_family', help='IP address family')
141     nic_template.add_argument('-d', '--ovs-dpdk-bridge',
142                               default=None, dest='ovs_dpdk_bridge',
143                               help='OVS DPDK Bridge Name')
144     nic_template.set_defaults(func=build_nic_template)
145
146     deploy_settings = subparsers.add_parser('parse-deploy-settings',
147                               help='Parse deploy settings file')
148     deploy_settings.add_argument('-f', '--file', default='deploy_settings.yaml',
149                               help='path to deploy settings file')
150     deploy_settings.set_defaults(func=parse_deploy_settings)
151
152     args = parser.parse_args(sys.argv[1:])
153     if args.debug:
154         logging.basicConfig(level=logging.DEBUG)
155     else:
156         apex_log_filename = args.log_file
157         os.makedirs(os.path.dirname(apex_log_filename), exist_ok=True)
158         logging.basicConfig(filename=apex_log_filename,
159                             format='%(asctime)s %(levelname)s: %(message)s',
160                             datefmt='%m/%d/%Y %I:%M:%S %p',
161                             level=logging.DEBUG)
162     return parser, args
163
164
165 def main(parser, args):
166     if hasattr(args, 'func'):
167         args.func(args)
168     else:
169         parser.print_help()
170         exit(1)
171
172 if __name__ == "__main__":
173     parser, args = parse_args()
174     main(parser, args)