556
|
1 import asyncio |
|
2 import aiohttp |
551
|
3 |
556
|
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 """ |
551
|
10 |
556
|
11 def __init__(self, server): |
|
12 self.server = server |
|
13 self.epoch_tag = None |
|
14 self.http_session = aiohttp.ClientSession() |
551
|
15 |
556
|
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) |
551
|
25 |
556
|
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: |
557
|
39 rawresp = yield from asyncio.wait_for(r.text(), 600) |
551
|
40 |
556
|
41 resp = utils.json_load_round_float(rawresp) |
551
|
42 |
556
|
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) |
551
|
53 |
562
|
54 except asyncio.TimeoutError: |
|
55 D("configwaiter http timed out") |
|
56 pass |
556
|
57 except Exception as e: |
557
|
58 EX("Error watching config: %s" % str(e)) |
551
|
59 |
|
60 |
|
61 |
|
62 |