Skip to content

Instantly share code, notes, and snippets.

@n0rc
Last active January 13, 2018 19:08
Show Gist options
  • Save n0rc/67630dad27455510688e2e3bfb68a179 to your computer and use it in GitHub Desktop.
Save n0rc/67630dad27455510688e2e3bfb68a179 to your computer and use it in GitHub Desktop.
wsgi script to get the current tinc graph as png image
# coding: utf-8
import os
import re
import time
from subprocess import Popen, PIPE, check_output
from urlparse import parse_qs
re_filter = re.compile(r' \w+ \[label = "[^"]+", color = "red"];\n')
png_graph_all = '/tmp/tinc-graph-all.png'
png_graph_reachable = '/tmp/tinc-graph-reachable.png'
# caching time
max_age = 300
def graph2png(graph, fname):
# you can also use dot, circo, whatever with different options here
p = Popen(['/usr/bin/neato', '-Tpng', '-Nfontname=Sans', '-Goverlap=scale', '-Gsplines=true', '-o', fname], stdin=PIPE)
p.communicate(input=graph)
return p.returncode
def application(environ, start_response):
d = parse_qs(environ['QUERY_STRING'])
mode = d.get('mode', [''])[0]
fname = png_graph_all if mode == 'all' else png_graph_reachable
rcs = 0
if not os.path.isfile(fname) or time.time() - os.path.getmtime(fname) > max_age:
# this command requires sudo permissions for the user running the wsgi/web service
graph_all = check_output(['/usr/bin/sudo', '/path/to/tinc', '-n', 'yournetwork', 'dump', 'graph'])
graph_reachable = re_filter.sub('', graph_all)
rcs += graph2png(graph_all, png_graph_all)
rcs += graph2png(graph_reachable, png_graph_reachable)
if rcs == 0:
headers = [('Content-Type', 'image/png')]
with open(fname, 'rb') as png:
ret = png.read()
else:
headers = [('Content-Type', 'text/plain')]
ret = 'some bad shit went down'
status = '200 OK'
start_response(status, headers)
return [ret]
@n0rc
Copy link
Author

n0rc commented Jan 13, 2018

Revision 3 writes image files to disk for caching.
Revision 1 keeps everything in memory but calls tinc every single time a request is made.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment