Debian Codegraph @

networking_bagpipe/bagpipe_bgp/cli/looking_glass.py

raw
1 # Copyright 2014 Orange
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import os
16 from sys import stdout
17 import urllib.error
18 import urllib.parse
19 import urllib.request
20
21
22 import optparse
23 from oslo_config import cfg
24 from oslo_serialization import jsonutils
25
26 from networking_bagpipe.bagpipe_bgp.api import config as api_config
27
28
29 BAGPIPE_PORT = 8082
30 LOOKING_GLASS_BASE = "looking-glass"
31
32 INDENT_INCREMENT = 2
33
34
35 def pretty_print_recurse(data, indent, recursive_requests, url,
36 already_anew_line=False):
37 """recursively pretty print data
38
39 key has already been output, this function will print data and finish at
40 a start of line
41
42 returns True if the key output was spread across multiple lines.
43 """
44 if isinstance(data, dict):
45 more = False
46
47 if ("id" in data and "href" in data):
48 stdout.write(data["id"])
49 del data["id"]
50
51 if ("href" in data):
52 more = True
53
54 if more:
55 target_url = data["href"]
56 if recursive_requests:
57 if target_url.startswith(url):
58 response = urllib.request.urlopen(target_url)
59 if response.getcode() == 200:
60 pretty_print_recurse(jsonutils.load(response),
61 indent + INDENT_INCREMENT,
62 recursive_requests, target_url,
63 already_anew_line=False)
64 return True
65 else:
66 stdout.write(" (ERROR %d)", response.getcode())
67 return False
68
69 del data["href"]
70 stdout.write(" (...)")
71 already_anew_line = False
72
73 if len(data) > 0:
74 if not already_anew_line:
75 stdout.write("\n")
76 first_val = True
77 for (key, value) in data.items():
78 if not first_val or not already_anew_line:
79 stdout.write("%s" % (" " * indent))
80 if first_val:
81 first_val = False
82 stdout.write("%s: " % key)
83 pretty_print_recurse(value, indent + INDENT_INCREMENT,
84 recursive_requests, url)
85 else:
86 if more:
87 stdout.write("\n")
88 else:
89 stdout.write("-\n")
90
91 elif isinstance(data, list):
92
93 if len(data) > 0:
94 if not already_anew_line:
95 stdout.write("\n")
96 already_anew_line = True
97
98 for value in data:
99 stdout.write("%s* " % (" " * indent))
100 if isinstance(value, dict) or isinstance(value, list):
101 pretty_print_recurse(value, indent + INDENT_INCREMENT,
102 recursive_requests, url,
103 already_anew_line)
104 else:
105 stdout.write("%s\n" % value)
106 already_anew_line = True
107 else:
108 stdout.write("-\n")
109
110 else:
111 if isinstance(data, str) and "\n" in data:
112 data = data.strip("\n").replace("\n", "\n%s" % (" " * indent))
113 stdout.write("\n%s" % (" " * indent))
114
115 stdout.write("%s\n" % data)
116 return False
117
118
119 def main():
120 api_config.register_config()
121 try:
122 cfg.CONF(args=[],
123 project='bagpipe-looking-glass',
124 default_config_files=['/etc/bagpipe-bgp/bgp.conf'])
125 api_port = cfg.CONF.API.port
126 except cfg.ConfigFilesNotFoundError:
127 api_port = api_config.DEFAULT_PORT
128
129 usage = """ %prog [--server <ip>] path to object in looking-glass
130
131 e.g.: %prog vpns instances"""
132 parser = optparse.OptionParser(usage)
133
134 parser.add_option(
135 "--server", dest="server", default="127.0.0.1",
136 help="IP address of BaGPipe BGP (optional, default: %default)")
137
138 parser.add_option(
139 "--port", dest="port", type="int", default=api_port,
140 help="Port of BaGPipe BGP (optional, default: %default)")
141
142 parser.add_option(
143 "--prefix", dest="prefix", default=LOOKING_GLASS_BASE,
144 help="Looking-glass URL Prefix (optional, default: %default)")
145
146 parser.add_option(
147 "-r", "--recurse", dest="recurse", action="store_true", default=False,
148 help="Recurse down into the whole looking-glass (disabled by default)")
149
150 (options, args) = parser.parse_args()
151
152 quoted_args = [urllib.parse.quote(arg) for arg in args]
153 target_url = "http://%s:%d/%s/%s" % (options.server, options.port,
154 options.prefix, "/".join(quoted_args))
155 try:
156 os.environ['NO_PROXY'] = options.server
157 response = urllib.request.urlopen(target_url)
158
159 if response.getcode() == 200:
160 data = jsonutils.load(response)
161
162 if (isinstance(data, dict) and "href" in data):
163 target_url_bis = data["href"]
164 response_bis = urllib.request.urlopen(target_url_bis)
165 if response.getcode() == 200:
166 target_url = target_url_bis
167 data = jsonutils.load(response_bis)
168
169 pretty_print_recurse(data, 0, options.recurse, target_url,
170 already_anew_line=True)
171
172 except urllib.error.HTTPError as e:
173 if e.code == 404:
174 print("No such looking glass path: %s\n(%s)" %
175 (" ".join(quoted_args), target_url))
176 else:
177 print("Error code %d: %s" % (e.getcode(), e.read()))
178 return
179 except urllib.error.URLError as e:
180 print("No server at http://%s:%d : %s" % (options.server,
181 options.port, e))