blob: d44bc961a3381f8c11ac1b9f5717306fe7a40b31 [file] [log] [blame]
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +08001#!/usr/bin/env python3
2
3# SPDX-FileCopyrightText: © 2021 Open Networking Foundation <support@opennetworking.org>
4# SPDX-License-Identifier: Apache-2.0
5
6# utils.py
7# The utility functions shared among nbhelper objects
8
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +08009import argparse
Zack Williamsdac2be42021-08-19 16:14:31 -070010import logging
11import re
12import sys
13
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +080014import requests
Zack Williamsdac2be42021-08-19 16:14:31 -070015import pynetbox
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +080016
17from ruamel import yaml
18
19# Initialize module-level variables
20netboxapi = None
21netbox_config = None
22netbox_version = None
23
24# create shared logger
25logging.basicConfig()
26logger = logging.getLogger("nbh")
27
28
29def initialize(extra_args):
30 """
31 Initialize the NBHelper module, the extra_args is required, it contains the
32 NetBox API url, API token, and the name of site
33 """
34 global netboxapi, netbox_config, netbox_version
35
36 args = parse_cli_args(extra_args)
37 netbox_config = yaml.safe_load(args.settings.read())
38
39 for require_args in ["api_endpoint", "token", "tenant_name"]:
40 if not netbox_config.get(require_args):
Zack Williamsdac2be42021-08-19 16:14:31 -070041 logger.error("The require argument: %s was not set. Stop.", require_args)
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +080042 sys.exit(1)
43
44 netboxapi = pynetbox.api(
45 netbox_config["api_endpoint"], token=netbox_config["token"], threading=True,
46 )
47
48 if not netbox_config.get("validate_certs", True):
49 session = requests.Session()
50 session.verify = False
51 netboxapi.http_session = session
52
53 netbox_version = netboxapi.version
54
55 return args
56
57
Zack Williamsdac2be42021-08-19 16:14:31 -070058def parse_cli_args(extra_args):
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +080059 """
60 parse CLI arguments. Can add extra arguments with a option:kwargs dict
61 """
62
63 parser = argparse.ArgumentParser(description="Netbox")
64
65 # Positional args
66 parser.add_argument(
67 "settings",
68 type=argparse.FileType("r"),
69 help="YAML Ansible inventory file w/NetBox API token",
70 )
71
72 parser.add_argument(
73 "--debug", action="store_true", help="Print additional debugging information"
74 )
75
76 for ename, ekwargs in extra_args.items():
77 parser.add_argument(ename, **ekwargs)
78
79 args = parser.parse_args()
80 log_level = logging.DEBUG if args.debug else logging.INFO
81 logger.setLevel(log_level)
82
83 return args
84
85
86def check_name_dns(name):
87
88 badchars = re.search("[^a-z0-9.-]", name.lower(), re.ASCII)
89
90 if badchars:
91 logger.error(
92 "DNS name '%s' has one or more invalid characters: '%s'",
93 name,
94 badchars.group(0),
95 )
96 sys.exit(1)
97
98 return name.lower()
99
100
101def clean_name_dns(name):
102 return re.sub("[^a-z0-9.-]", "-", name.lower(), 0, re.ASCII)
103
104
105def apply_as_router(output_yaml):
106 """ Add the router-specific value for output structure """
107
108 output_yaml.setdefault("netprep_router", True)
109 output_yaml.setdefault("tftpd_files", ["undionly.kpxe"])
110 output_yaml.setdefault(
111 "vhosts", [{"name": "default", "default_server": True, "autoindex": True}]
112 )
113 output_yaml.setdefault("acme_username", "www-data")
114
115 return output_yaml
116
117
118class AttrDict(dict):
119 def __init__(self, *args, **kwargs):
Zack Williamsdac2be42021-08-19 16:14:31 -0700120 super().__init__(*args, **kwargs)
Wei-Yu Chenbd495ba2021-08-31 19:46:35 +0800121 self.__dict__ = self