peerfinder.py 10 KB

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