peerfinder.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #!/usr/bin/env python3
  2. from flask import Flask
  3. from flask import request, render_template
  4. from flask.ext.sqlalchemy import SQLAlchemy
  5. #from flask import session, request, url_for, redirect, render_template
  6. import netaddr
  7. from netaddr import IPAddress
  8. # Hack for python3
  9. from netaddr.strategy.ipv4 import packed_to_int as unpack_v4
  10. from netaddr.strategy.ipv6 import packed_to_int as unpack_v6
  11. import socket
  12. from datetime import datetime
  13. from uuid import uuid4
  14. app = Flask(__name__)
  15. app.config.from_pyfile('config.py')
  16. db = SQLAlchemy(app)
  17. def unpack(ip):
  18. if len(ip) == 4:
  19. return unpack_v4(ip)
  20. elif len(ip) == 16:
  21. return unpack_v6(ip)
  22. def is_valid_ip(ip):
  23. return netaddr.valid_ipv4(ip) or netaddr.valid_ipv6(ip)
  24. def resolve_name(hostname):
  25. return list({s[4][0] for s in socket.getaddrinfo(hostname, None)})
  26. class Target(db.Model):
  27. """Target IP to ping"""
  28. id = db.Column(db.Integer, primary_key=True)
  29. # IP addresses are encoded as their binary representation
  30. ip = db.Column(db.BINARY(length=16))
  31. # Date at which a user asked for measurements to this target
  32. submitted = db.Column(db.DateTime)
  33. def __init__(self, ip):
  34. self.ip = IPAddress(ip).packed
  35. self.submitted = datetime.now()
  36. def get_ip(self):
  37. return IPAddress(unpack(self.ip))
  38. def is_v4(self):
  39. return self.get_ip().version == 4
  40. def is_v6(self):
  41. return self.get_ip().version == 6
  42. def __repr__(self):
  43. return '%r' % self.get_ip()
  44. def __str__(self):
  45. return str(self.get_ip())
  46. # Many-to-many table to record which target has been given to which
  47. # participant.
  48. handled_targets = db.Table('handled_targets',
  49. db.Column('target_id', db.Integer, db.ForeignKey('target.id')),
  50. db.Column('participant_id', db.Integer, db.ForeignKey('participant.id'))
  51. )
  52. class Participant(db.Model):
  53. """Participant in the ping network"""
  54. id = db.Column(db.Integer, primary_key=True)
  55. # Used both as identification and password
  56. uuid = db.Column(db.String, unique=True)
  57. # Name of the machine
  58. name = db.Column(db.String)
  59. # Mostly free-form (nick, mail address, ...)
  60. contact = db.Column(db.String)
  61. # Whether we accept this participant or not
  62. active = db.Column(db.Boolean)
  63. # Many-to-many relationship
  64. targets = db.relationship('Target',
  65. secondary=handled_targets,
  66. backref=db.backref('participants', lazy='dynamic'),
  67. lazy='dynamic')
  68. def __init__(self, name, contact):
  69. self.uuid = str(uuid4())
  70. self.name = name
  71. self.contact = contact
  72. self.active = False
  73. def __str__(self):
  74. return "{} ({})".format(self.name, self.contact)
  75. class Result(db.Model):
  76. """Result of a ping measurement"""
  77. id = db.Column(db.Integer, primary_key=True)
  78. target_id = db.Column(db.Integer, db.ForeignKey('target.id'))
  79. target = db.relationship('Target',
  80. backref=db.backref('results', lazy='dynamic'))
  81. participant_id = db.Column(db.Integer, db.ForeignKey('participant.id'))
  82. participant = db.relationship('Participant',
  83. backref=db.backref('results', lazy='dynamic'))
  84. # In milliseconds
  85. rtt = db.Column(db.Float)
  86. # Date at which the result was reported back to us
  87. date = db.Column(db.DateTime)
  88. def __init__(self, target_id, participant_uuid, rtt):
  89. target = Target.query.get_or_404(int(target_id))
  90. participant = Participant.query.filter_by(uuid=participant_uuid,
  91. active=True).first_or_404()
  92. self.target = target
  93. self.participant = participant
  94. self.rtt = float(rtt)
  95. self.date = datetime.now()
  96. def init_db():
  97. db.create_all()
  98. def get_targets(uuid):
  99. """Returns the queryset of potential targets for the given participant
  100. UUID, that is, targets that have not already been handed out to this
  101. participant.
  102. """
  103. participant = Participant.query.filter_by(uuid=uuid, active=True).first_or_404()
  104. # We want to get all targets that do not have a relationship with the
  105. # given participant. Note that the following lines manipulate SQL
  106. # queries, which are only executed at the very end.
  107. # This gives all targets that have already been sent to the given
  108. # participant.
  109. already_done = Target.query.join(handled_targets).filter_by(participant_id=participant.id).with_entities(Target.id)
  110. # This takes the negation of the previous set.
  111. return Target.query.filter(~Target.id.in_(already_done))
  112. @app.route('/')
  113. def homepage():
  114. return render_template('home.html')
  115. @app.route('/submit', methods=['POST'])
  116. def submit_job():
  117. if 'target' in request.form:
  118. target = request.form['target']
  119. if is_valid_ip(target):
  120. # Explicit IP
  121. targets = [Target(target)]
  122. else:
  123. # DNS name, might give multiple IP
  124. targets = [Target(ip) for ip in resolve_name(target)]
  125. for t in targets:
  126. db.session.add(t)
  127. db.session.commit()
  128. return render_template('submit.html', targets=targets)
  129. else:
  130. return "Invalid arguments"
  131. @app.route('/create/participant', methods=['POST'])
  132. def create_participant():
  133. if {'name', 'contact'}.issubset(request.form) and request.form['name']:
  134. participant = Participant(request.form['name'], request.form['contact'])
  135. db.session.add(participant)
  136. db.session.commit()
  137. return "OK\nPlease wait for manual validation\n"
  138. else:
  139. return "Invalid arguments"
  140. @app.route('/target/<uuid>')
  141. def get_next_target(uuid):
  142. """"Returns the next target to ping for the given participant"""
  143. target = get_targets(uuid).first()
  144. if target is not None:
  145. return "{} {}".format(target.id, target)
  146. else:
  147. return ""
  148. @app.route('/target/<uuid>/<family>')
  149. def get_next_target_family(uuid, family):
  150. """Same as above, but for a specific family ("ipv4" or "ipv6")"""
  151. if family not in ("ipv4", "ipv6"):
  152. return "Invalid family, should be ipv4 or ipv6\n"
  153. predicate = lambda t: t.is_v4() if family == "ipv4" else t.is_v6()
  154. targets = [t for t in get_targets(uuid).all() if predicate(t)]
  155. if not targets:
  156. return ""
  157. return "{} {}".format(targets[0].id, targets[0])
  158. @app.route('/result/report/<uuid>', methods=['POST'])
  159. def report_result(uuid):
  160. if {'rtt', 'target'}.issubset(request.form):
  161. target_id = request.form['target']
  162. rtt = request.form['rtt']
  163. result = Result(target_id, uuid, rtt)
  164. db.session.add(result)
  165. # Record that the participant has returned a result
  166. participant = result.participant
  167. participant.targets.append(result.target)
  168. db.session.commit()
  169. return "OK\n"
  170. else:
  171. return "Invalid arguments\n"
  172. @app.route('/result/show/<int:target_id>')
  173. def show_results(target_id):
  174. target = Target.query.get_or_404(target_id)
  175. results = target.results.order_by('rtt').all()
  176. return render_template('results.html', target=target, results=results)
  177. if __name__ == '__main__':
  178. init_db()
  179. app.run(host='0.0.0.0', port=8888)