JudgeServer/server/service.py

47 lines
1.4 KiB
Python
Raw Normal View History

2016-10-03 08:13:46 +00:00
import json
2018-03-18 00:19:44 +00:00
import os
2016-10-03 08:13:46 +00:00
import requests
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:
2018-12-12 06:27:40 +00:00
if not os.environ.get("DISABLE_HEARTBEAT"):
service = JudgeService()
service.heartbeat()
2016-10-03 08:13:46 +00:00
exit(0)
except Exception as e:
logger.exception(e)
2017-05-02 07:55:48 +00:00
exit(1)