submit_telemetry_data.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # This Source Code Form is subject to the terms of the Mozilla Public
  2. # License, v. 2.0. If a copy of the MPL was not distributed with this
  3. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. import errno
  5. import logging
  6. import os
  7. import sys
  8. import time
  9. HERE = os.path.abspath(os.path.dirname(__file__))
  10. sys.path.append(os.path.join(HERE, '..', 'python', 'requests'))
  11. import requests
  12. # Server to which to submit telemetry data
  13. BUILD_TELEMETRY_SERVER = 'http://52.88.27.118/build-metrics-dev'
  14. def submit_telemetry_data(statedir):
  15. # No data to work with anyway
  16. outgoing = os.path.join(statedir, 'telemetry', 'outgoing')
  17. if not os.path.isdir(outgoing):
  18. return 0
  19. submitted = os.path.join(statedir, 'telemetry', 'submitted')
  20. try:
  21. os.mkdir(submitted)
  22. except OSError as e:
  23. if e.errno != errno.EEXIST:
  24. raise
  25. session = requests.Session()
  26. for filename in os.listdir(outgoing):
  27. path = os.path.join(outgoing, filename)
  28. if os.path.isdir(path) or not path.endswith('.json'):
  29. continue
  30. with open(path, 'r') as f:
  31. data = f.read()
  32. try:
  33. r = session.post(BUILD_TELEMETRY_SERVER, data=data,
  34. headers={'Content-Type': 'application/json'})
  35. except Exception as e:
  36. logging.error('Exception posting to telemetry '
  37. 'server: %s' % str(e))
  38. break
  39. # TODO: some of these errors are likely not recoverable, as
  40. # written, we'll retry indefinitely
  41. if r.status_code != 200:
  42. logging.error('Error posting to telemetry: %s %s' %
  43. (r.status_code, r.text))
  44. continue
  45. os.rename(os.path.join(outgoing, filename),
  46. os.path.join(submitted, filename))
  47. session.close()
  48. # Discard submitted data that is >= 30 days old
  49. now = time.time()
  50. for filename in os.listdir(submitted):
  51. ctime = os.stat(os.path.join(submitted, filename)).st_ctime
  52. if now - ctime >= 60*60*24*30:
  53. os.remove(os.path.join(submitted, filename))
  54. return 0
  55. if __name__ == '__main__':
  56. if len(sys.argv) != 2:
  57. print('usage: python submit_telemetry_data.py <statedir>')
  58. sys.exit(1)
  59. statedir = sys.argv[1]
  60. logging.basicConfig(filename=os.path.join(statedir, 'telemetry', 'telemetry.log'),
  61. format='%(asctime)s %(message)s')
  62. sys.exit(submit_telemetry_data(statedir))