JudgeServer/server/service.py

49 lines
1.4 KiB
Python
Raw Normal View History

2016-10-03 08:13:46 +00:00
# coding=utf-8
from __future__ import unicode_literals
import os
import json
import requests
2016-10-04 06:32:40 +00:00
import hashlib
2016-10-03 08:13:46 +00:00
from exception import JudgeServiceError
2016-10-27 10:38:04 +00:00
from utils import server_info, logger, token
2016-10-03 08:13:46 +00:00
class JudgeService(object):
def __init__(self):
2017-12-06 03:50:15 +00:00
self.service_url = os.environ["SERVICE_URL"]
self.backend_url = os.environ["BACKEND_URL"]
2016-10-03 08:13:46 +00:00
def _request(self, data):
try:
2017-12-22 14:16:03 +00:00
resp = requests.post(self.backend_url, json=data,
headers={"X-JUDGE-SERVER-TOKEN": token,
"Content-Type": "application/json"}, timeout=5).text
2016-10-03 08:13:46 +00:00
except Exception as e:
logger.exception(e)
2017-12-22 14:16:03 +00:00
raise JudgeServiceError("Heartbeat request failed")
try:
r = json.loads(resp)
if r["error"]:
raise JudgeServiceError(r["data"])
except Exception as e:
logger.exception("Heartbeat failed, response is {}".format(resp))
raise JudgeServiceError("Invalid heartbeat response")
2016-10-03 08:13:46 +00:00
def heartbeat(self):
data = server_info()
data["action"] = "heartbeat"
2016-10-05 05:38:49 +00:00
data["service_url"] = self.service_url
2016-10-03 08:13:46 +00:00
self._request(data)
if __name__ == "__main__":
try:
service = JudgeService()
service.heartbeat()
exit(0)
except Exception as e:
logger.exception(e)
2017-05-02 07:55:48 +00:00
exit(1)