peerfinder.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. #!/usr/bin/env python
  2. from flask import Flask
  3. from flask import request, render_template
  4. from flask.ext.sqlalchemy import SQLAlchemy
  5. from flask.ext.script import Server, Manager
  6. from flask.ext.migrate import Migrate, MigrateCommand
  7. #from flask import session, request, url_for, redirect, render_template
  8. import netaddr
  9. from netaddr import IPAddress, IPSet
  10. # Hack for python3
  11. from netaddr.strategy.ipv4 import packed_to_int as unpack_v4
  12. from netaddr.strategy.ipv6 import packed_to_int as unpack_v6
  13. import socket
  14. from datetime import datetime, timedelta
  15. from uuid import uuid4
  16. DN42 = IPSet(['172.22.0.0/15', '172.31.0.0/16', '10.0.0.0/8'])
  17. app = Flask(__name__)
  18. app.config.from_pyfile('config.py')
  19. db = SQLAlchemy(app)
  20. migrate = Migrate(app, db)
  21. manager = Manager(app)
  22. manager.add_command("runserver", Server(host='0.0.0.0', port=8888))
  23. manager.add_command("db", MigrateCommand)
  24. def unpack(ip):
  25. if len(ip) == 4:
  26. return unpack_v4(ip)
  27. elif len(ip) == 16:
  28. return unpack_v6(ip)
  29. def is_valid_ip(ip):
  30. return netaddr.valid_ipv4(ip) or netaddr.valid_ipv6(ip)
  31. def resolve_name(hostname):
  32. try:
  33. return list({s[4][0] for s in socket.getaddrinfo(hostname, None)})
  34. except socket.gaierror:
  35. return []
  36. @app.template_filter()
  37. def ipaddress_pp(addr):
  38. """Pretty-print an IP address"""
  39. a = IPAddress(addr)
  40. try:
  41. # Handle v4-mapped addresses
  42. return a.ipv4()
  43. except netaddr.AddrConversionError:
  44. return a.ipv6()
  45. @app.template_filter()
  46. def not_dn42(addr):
  47. """Filter the input address if it is part of dn42"""
  48. a = IPAddress(addr)
  49. if a in DN42:
  50. return ""
  51. return a
  52. class Target(db.Model):
  53. """Target IP to ping"""
  54. id = db.Column(db.Integer, primary_key=True)
  55. # Unique ID for accessing the results (privacy reasons)
  56. unique_id = db.Column(db.String)
  57. # IP addresses are encoded as their binary representation
  58. ip = db.Column(db.BINARY(length=16))
  59. # Date at which a user asked for measurements to this target
  60. submitted = db.Column(db.DateTime)
  61. public = db.Column(db.Boolean)
  62. def __init__(self, ip, public=False):
  63. self.unique_id = str(uuid4())
  64. self.ip = IPAddress(ip).packed
  65. self.submitted = datetime.now()
  66. self.public = public
  67. def get_ip(self):
  68. return IPAddress(unpack(self.ip))
  69. def is_v4(self):
  70. return self.get_ip().version == 4
  71. def is_v6(self):
  72. return self.get_ip().version == 6
  73. def __repr__(self):
  74. return '%r' % self.get_ip()
  75. def __str__(self):
  76. return str(self.get_ip())
  77. # Many-to-many table to record which target has been given to which
  78. # participant.
  79. handled_targets = db.Table('handled_targets',
  80. db.Column('target_id', db.Integer, db.ForeignKey('target.id')),
  81. db.Column('participant_id', db.Integer, db.ForeignKey('participant.id'))
  82. )
  83. class Participant(db.Model):
  84. """Participant in the ping network"""
  85. id = db.Column(db.Integer, primary_key=True)
  86. # Used both as identification and password
  87. uuid = db.Column(db.String, unique=True)
  88. # Name of the machine
  89. name = db.Column(db.String)
  90. # Mostly free-form (nick, mail address, ...)
  91. contact = db.Column(db.String)
  92. # Optional
  93. country = db.Column(db.String)
  94. # Free-form (peering technology, DSL or fiber, etc)
  95. comment = db.Column(db.String)
  96. # Whether we accept this participant or not
  97. active = db.Column(db.Boolean)
  98. # Many-to-many relationship
  99. targets = db.relationship('Target',
  100. secondary=handled_targets,
  101. backref=db.backref('participants', lazy='dynamic'),
  102. lazy='dynamic')
  103. def __init__(self, name, contact, country, comment):
  104. self.uuid = str(uuid4())
  105. self.name = name
  106. self.contact = contact
  107. self.country = country
  108. self.comment = comment
  109. self.active = False
  110. def __str__(self):
  111. return "{} ({})".format(self.name, self.contact)
  112. class Result(db.Model):
  113. """Result of a ping measurement"""
  114. id = db.Column(db.Integer, primary_key=True)
  115. target_id = db.Column(db.Integer, db.ForeignKey('target.id'))
  116. target = db.relationship('Target',
  117. backref=db.backref('results', lazy='dynamic'))
  118. participant_id = db.Column(db.Integer, db.ForeignKey('participant.id'))
  119. participant = db.relationship('Participant',
  120. backref=db.backref('results', lazy='dynamic'))
  121. # Date at which the result was reported back to us
  122. date = db.Column(db.DateTime)
  123. # In milliseconds
  124. avgrtt = db.Column(db.Float)
  125. # All these are optional
  126. minrtt = db.Column(db.Float)
  127. maxrtt = db.Column(db.Float)
  128. jitter = db.Column(db.Float)
  129. # Number of ping requests
  130. probes_sent = db.Column(db.Integer)
  131. # Number of successful probes
  132. probes_received = db.Column(db.Integer)
  133. def __init__(self, target_id, participant_uuid, avgrtt, minrtt, maxrtt,
  134. jitter, probes_sent, probes_received):
  135. target = Target.query.get_or_404(int(target_id))
  136. participant = Participant.query.filter_by(uuid=participant_uuid,
  137. active=True).first_or_404()
  138. self.target = target
  139. self.participant = participant
  140. self.date = datetime.now()
  141. self.avgrtt = float(avgrtt)
  142. self.minrtt = float(minrtt) if minrtt is not None else None
  143. self.maxrtt = float(maxrtt) if maxrtt is not None else None
  144. self.jitter = float(jitter) if jitter is not None else None
  145. self.probes_sent = int(probes_sent) if probes_sent is not None else None
  146. self.probes_received = int(probes_received) if probes_received is not None else None
  147. def init_db():
  148. db.create_all()
  149. def get_targets(uuid):
  150. """Returns the queryset of potential targets for the given participant
  151. UUID, that is, targets that have not already been handed out to this
  152. participant.
  153. """
  154. participant = Participant.query.filter_by(uuid=uuid, active=True).first_or_404()
  155. # We want to get all targets that do not have a relationship with the
  156. # given participant. Note that the following lines manipulate SQL
  157. # queries, which are only executed at the very end.
  158. # This gives all targets that have already been sent to the given
  159. # participant.
  160. already_done = Target.query.join(handled_targets).filter_by(participant_id=participant.id).with_entities(Target.id)
  161. # This takes the negation of the previous set.
  162. new_tasks = Target.query.filter(~Target.id.in_(already_done))
  163. max_age = app.config.get('MAX_AGE', 0)
  164. if max_age == 0:
  165. return new_tasks
  166. else:
  167. limit = datetime.now() - timedelta(seconds=max_age)
  168. return new_tasks.filter(Target.submitted >= limit)
  169. @app.route('/')
  170. def homepage():
  171. public_targets = Target.query.filter_by(public=True).order_by("submitted DESC").all()
  172. return render_template('home.html', targets=public_targets)
  173. @app.route('/about')
  174. def about():
  175. return render_template('about.html')
  176. @app.route('/participate')
  177. def participate():
  178. return render_template('participate.html')
  179. @app.route('/privacy')
  180. def privacy():
  181. return render_template('privacy.html')
  182. @app.route('/dev')
  183. def dev():
  184. return render_template('dev.html')
  185. @app.route('/static/<path:path>')
  186. def static_proxy(path):
  187. # send_static_file will guess the correct MIME type
  188. return app.send_static_file(path)
  189. @app.route('/robots.txt')
  190. def robots():
  191. return app.send_static_file("robots.txt")
  192. @app.route('/submit', methods=['POST'])
  193. def submit_job():
  194. if 'target' in request.form:
  195. target = request.form['target'].strip()
  196. public = bool(request.form.get('public'))
  197. if is_valid_ip(target):
  198. # Explicit IP
  199. targets = [Target(target, public)]
  200. else:
  201. # DNS name, might give multiple IP
  202. targets = [Target(ip, public) for ip in resolve_name(target)]
  203. if targets == []:
  204. return render_template('submit_error.html', target=request.form['target'])
  205. for t in targets:
  206. db.session.add(t)
  207. db.session.commit()
  208. return render_template('submit.html', targets=targets)
  209. else:
  210. return "Invalid arguments"
  211. @app.route('/create/participant', methods=['POST'])
  212. def create_participant():
  213. fields = ['name', 'contact', 'country', 'comment']
  214. if set(fields).issubset(request.form) and request.form['name']:
  215. participant = Participant(*(request.form[f] for f in fields))
  216. db.session.add(participant)
  217. db.session.commit()
  218. return render_template('participant.html', participant=participant,
  219. uuid=participant.uuid,
  220. peerfinder=app.config["PEERFINDER_DN42"])
  221. else:
  222. return "Invalid arguments"
  223. @app.route('/script.sh')
  224. def get_script():
  225. r = render_template('run.sh', peerfinder=app.config["PEERFINDER_DN42"])
  226. return r, 200, {'Content-Type': 'text/x-shellscript'}
  227. @app.route('/cron.sh')
  228. def get_cron():
  229. r = render_template('cron.sh', peerfinder=app.config["PEERFINDER_DN42"])
  230. return r, 200, {'Content-Type': 'text/x-shellscript'}
  231. @app.route('/target/<uuid>/<family>')
  232. @app.route('/target/<uuid>')
  233. def get_next_target(uuid, family="any"):
  234. """"Returns the next target to ping for the given participant and family
  235. ("any", "ipv4", or "ipv6")"""
  236. if family not in ("ipv4", "ipv6", "any"):
  237. return "Invalid family, should be 'any', 'ipv4' or 'ipv6'\n"
  238. if family == "any":
  239. targets = get_targets(uuid).all()
  240. else:
  241. predicate = lambda t: t.is_v4() if family == "ipv4" else t.is_v6()
  242. targets = [t for t in get_targets(uuid).all() if predicate(t)]
  243. if targets:
  244. return "{} {}".format(targets[0].id, targets[0])
  245. return ""
  246. @app.route('/result/report/<uuid>', methods=['POST'])
  247. def report_result(uuid):
  248. if {'avgrtt', 'target'}.issubset(request.form):
  249. target_id = request.form['target']
  250. avgrtt = request.form['avgrtt']
  251. optional_args = [request.form.get(f) for f in
  252. ('minrtt', 'maxrtt', 'jitter', 'probes_sent',
  253. 'probes_received')]
  254. result = Result(target_id, uuid, avgrtt, *optional_args)
  255. db.session.add(result)
  256. # Record that the participant has returned a result
  257. participant = result.participant
  258. participant.targets.append(result.target)
  259. db.session.commit()
  260. return "OK\n"
  261. else:
  262. return "Invalid arguments\n"
  263. @app.route('/result/show/<target_uniqueid>')
  264. def show_results(target_uniqueid):
  265. target = Target.query.filter_by(unique_id=target_uniqueid).first_or_404()
  266. results = target.results.order_by('avgrtt').all()
  267. return render_template('results.html', target=target, results=results)
  268. if __name__ == '__main__':
  269. init_db()
  270. manager.run()