1 import json
2 from requests import post, RequestException
3 import time
4
5
7 """
8 Object to send data back to fronted
9 """
10
12 super(FrontendClient, self).__init__()
13 self.frontend_url = opts.frontend_url
14 self.frontend_auth = opts.frontend_auth
15
16 self.msg = None
17
18 - def _post_to_frontend(self, data, url_path):
19 """
20 Make a request to the frontend
21 """
22
23 headers = {"content-type": "application/json"}
24 url = "{0}/{1}/".format(self.frontend_url, url_path)
25 auth = ("user", self.frontend_auth)
26
27 self.msg = None
28
29 try:
30 response = post(url, data=json.dumps(data), auth=auth, headers=headers)
31 if response.status_code >= 400:
32 self.msg = "Failed to submit to frontend: {0}: {1}".format(
33 response.status_code, response.text)
34 raise RequestException(self.msg)
35 except RequestException as e:
36 self.msg = "Post request failed: {0}".format(e)
37 raise
38 return response
39
40 - def _post_to_frontend_repeatedly(self, data, url_path, max_repeats=10):
41 """
42 Make a request max_repeats-time to the frontend
43 """
44 for i in range(max_repeats):
45 try:
46 return self._post_to_frontend(data, url_path)
47 except RequestException:
48 time.sleep(5)
49 else:
50 raise RequestException("Failed to post to frontend for {} times".format(max_repeats))
51
57
59 """
60 Announce to the frontend that a build is starting.
61 Return: True if the build can start
62 False if the build can not start (can be cancelled or deleted)
63 """
64 data = {"build_id": build_id, "chroot": chroot_name}
65 response = self._post_to_frontend_repeatedly(data, "starting_build")
66 if "can_start" not in response.json():
67 raise RequestException("Bad respond from the frontend")
68 return response.json()["can_start"]
69