peerfinder.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. def __init__(self, target_id, participant_uuid, rtt):
  81. target = Target.query.get_or_404(int(target_id))
  82. participant = Participant.query.filter_by(uuid=participant_uuid,
  83. active=True).first_or_404()
  84. self.target = target
  85. self.participant = participant
  86. self.rtt = float(rtt)
  87. def init_db():
  88. db.create_all()
  89. @app.route('/')
  90. def homepage():
  91. return render_template('home.html')
  92. @app.route('/submit', methods=['POST'])
  93. def submit_job():
  94. if 'target' in request.form:
  95. target = Target(request.form['target'])
  96. db.session.add(target)
  97. db.session.commit()
  98. return "Launching jobs towards {}".format(target)
  99. else:
  100. return "Invalid arguments"
  101. @app.route('/create/participant', methods=['POST'])
  102. def create_participant():
  103. if {'name', 'contact'}.issubset(request.form) and request.form['name']:
  104. participant = Participant(request.form['name'], request.form['contact'])
  105. db.session.add(participant)
  106. db.session.commit()
  107. return "OK\nPlease wait for manual validation\n"
  108. else:
  109. return "Invalid arguments"
  110. @app.route('/target/<uuid>')
  111. def get_next_target(uuid):
  112. """"Returns the next target to ping for the given participant"""
  113. participant = Participant.query.filter_by(uuid=uuid, active=True).first_or_404()
  114. # We want to get all targets that do not have a relationship with the
  115. # given participant. Note that the following lines manipulate SQL
  116. # queries, which are only executed at the very end.
  117. # This gives all targets that have already been sent to the given
  118. # participant.
  119. already_done = Target.query.join(handled_targets).filter_by(participant_id=participant.id).with_entities(Target.id)
  120. # This takes the negation of the previous set.
  121. todo = Target.query.filter(~Target.id.in_(already_done))
  122. target = todo.first()
  123. if target is not None:
  124. return "{} {}".format(target.id, target)
  125. else:
  126. return ""
  127. @app.route('/result/report/<uuid>', methods=['POST'])
  128. def report_result(uuid):
  129. if {'rtt', 'target'}.issubset(request.form):
  130. target_id = request.form['target']
  131. rtt = request.form['rtt']
  132. result = Result(target_id, uuid, rtt)
  133. db.session.add(result)
  134. # Record that the participant has returned a result
  135. participant = result.participant
  136. participant.targets.append(result.target)
  137. db.session.commit()
  138. return "OK\n"
  139. else:
  140. return "Invalid arguments\n"
  141. @app.route('/result/show/<int:target_id>')
  142. def show_results(target_id):
  143. target = Target.query.get_or_404(target_id)
  144. results = target.results.order_by('rtt').all()
  145. return render_template('results.html', target=target, results=results)
  146. if __name__ == '__main__':
  147. init_db()
  148. app.run(host='0.0.0.0', port=8888)