peerfinder.py 6.6 KB

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