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