Merge "Add library sourcing error check"
[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     """
83     dir, template = args.template.rsplit('/', 1)
84
85     env = Environment(loader=FileSystemLoader(dir))
86     template = env.get_template(template)
87     print(template.render(enabled_networks=args.enabled_networks,
88                           external_net_type=args.ext_net_type,
89                           external_net_af=args.address_family))
90
91
92 def parse_args():
93     parser = argparse.ArgumentParser()
94     parser.add_argument('--debug', action='store_true', default=False,
95                         help="Turn on debug messages")
96     parser.add_argument('-l', '--log-file', default='/var/log/apex/apex.log',
97                         dest='log_file', help="Log file to log to")
98     subparsers = parser.add_subparsers()
99
100     net_settings = subparsers.add_parser('parse-net-settings',
101                                          help='Parse network settings file')
102     net_settings.add_argument('-s', '--net-settings-file',
103                               default='network-settings.yaml',
104                               dest='net_settings_file',
105                               help='path to network settings file')
106     net_settings.add_argument('-i', '--network-isolation', type=bool,
107                               default=True, dest='network_isolation',
108                               help='network isolation')
109     net_settings.add_argument('-e', '--net-env-file',
110                               default="network-environment.yaml",
111                               dest='net_env_file',
112                               help='path to network environment file')
113     net_settings.set_defaults(func=parse_net_settings)
114
115     get_int_ip = subparsers.add_parser('find-ip',
116                                        help='Find interface ip')
117     get_int_ip.add_argument('-i', '--interface', required=True,
118                             help='Interface name')
119     get_int_ip.add_argument('-af', '--address-family', default=4, type=int,
120                             choices=[4, 6], dest='address_family',
121                             help='IP Address family')
122     get_int_ip.set_defaults(func=find_ip)
123
124     nic_template = subparsers.add_parser('nic-template',
125                                          help='Build NIC templates')
126     nic_template.add_argument('-t', '--template', required=True,
127                               dest='template',
128                               help='Template file to process')
129     nic_template.add_argument('-n', '--enabled-networks', required=True,
130                               dest='enabled_networks',
131                               help='enabled network list')
132     nic_template.add_argument('-e', '--ext-net-type', default='interface',
133                               dest='ext_net_type',
134                               choices=['interface', 'br-ex'],
135                               help='External network type')
136     nic_template.add_argument('-af', '--address-family', type=int, default=4,
137                               dest='address_family', help='IP address family')
138     nic_template.set_defaults(func=build_nic_template)
139
140     deploy_settings = subparsers.add_parser('parse-deploy-settings',
141                               help='Parse deploy settings file')
142     deploy_settings.add_argument('-f', '--file', default='deploy_settings.yaml',
143                               help='path to deploy settings file')
144     deploy_settings.set_defaults(func=parse_deploy_settings)
145
146     args = parser.parse_args(sys.argv[1:])
147     if args.debug:
148         logging.basicConfig(level=logging.DEBUG)
149     else:
150         apex_log_filename = args.log_file
151         os.makedirs(os.path.dirname(apex_log_filename), exist_ok=True)
152         logging.basicConfig(filename=apex_log_filename,
153                             format='%(asctime)s %(levelname)s: %(message)s',
154                             datefmt='%m/%d/%Y %I:%M:%S %p',
155                             level=logging.DEBUG)
156     return parser, args
157
158
159 def main(parser, args):
160     if hasattr(args, 'func'):
161         args.func(args)
162     else:
163         parser.print_help()
164         exit(1)
165
166 if __name__ == "__main__":
167     parser, args = parse_args()
168     main(parser, args)