259
|
1 import asyncio |
265
|
2 import datetime |
|
3 |
259
|
4 import aiohttp |
253
|
5 |
259
|
6 import utils |
|
7 from utils import L,D,EX,W,E |
|
8 import config |
|
9 |
|
10 class ConfigWaiter(object): |
|
11 """ Waits for config updates from the server. http long polling """ |
253
|
12 |
259
|
13 def __init__(self, server): |
|
14 self.server = server |
|
15 self.epoch_tag = None |
|
16 self.http_session = aiohttp.ClientSession() |
265
|
17 self.limitlog = utils.NotTooOften(datetime.timedelta(minutes=15)) |
253
|
18 |
259
|
19 @asyncio.coroutine |
|
20 def run(self): |
|
21 # wait until someting has been uploaded (the uploader itself waits 5 seconds) |
|
22 yield from asyncio.sleep(10) |
|
23 while True: |
|
24 yield from self.do() |
|
25 |
|
26 # avoid spinning too fast |
|
27 yield from asyncio.sleep(1) |
253
|
28 |
259
|
29 @asyncio.coroutine |
|
30 def do(self): |
|
31 try: |
|
32 if self.epoch_tag: |
|
33 headers = {'etag': self.epoch_tag} |
|
34 else: |
|
35 headers = None |
|
36 |
|
37 r = yield from asyncio.wait_for( |
|
38 self.http_session.get(config.SETTINGS_URL, headers=headers), |
|
39 300) |
|
40 D("waiter status %d" % r.status) |
|
41 if r.status == 200: |
260
|
42 rawresp = yield from asyncio.wait_for(r.text(), 600) |
253
|
43 |
259
|
44 resp = utils.json_load_round_float(rawresp) |
253
|
45 |
259
|
46 self.epoch_tag = resp['epoch_tag'] |
|
47 D("waiter got epoch tag %s" % self.epoch_tag) |
|
48 epoch = self.epoch_tag.split('-')[0] |
|
49 if self.server.params.receive(resp['params'], epoch): |
|
50 self.server.reload_signal(True) |
|
51 elif r.status == 304: |
|
52 pass |
|
53 else: |
|
54 # longer timeout to avoid spinning |
265
|
55 text = yield from asyncio.wait_for(r.text(), 600) |
|
56 D("Bad server response. %d %s" % (r.status, text)) |
259
|
57 yield from asyncio.sleep(30) |
253
|
58 |
265
|
59 except aiohttp.errors.ClientError as e: |
|
60 self.limitlog.log("Error with configwaiter: %s" % str(e)) |
|
61 except asyncio.TimeoutError as e: |
|
62 self.limitlog.log("configwaiter http timed out: %s" % str(e)) |
259
|
63 except Exception as e: |
260
|
64 EX("Error watching config: %s" % str(e)) |