|
8 | 8 | from io import StringIO
|
9 | 9 | import logging
|
10 | 10 | import os
|
| 11 | +import random |
11 | 12 | import re
|
12 | 13 | import sys
|
13 | 14 | import traceback
|
14 | 15 | import urllib.parse
|
15 | 16 | import requests
|
| 17 | +import threading |
16 | 18 | from wtforms import ValidationError
|
17 | 19 | from flask_wtf.csrf import CSRFProtect
|
18 | 20 |
|
@@ -116,6 +118,35 @@ def _verify_config(cfg):
|
116 | 118 | csrf = CSRFProtect()
|
117 | 119 | csrf.init_app(app)
|
118 | 120 |
|
| 121 | +############################################################################# |
| 122 | +# Background update thread |
| 123 | +# Run when the topology cache is 2/3 to expiration |
| 124 | +bg_update_freq = max(global_data.topology.cache_lifetime*2/3, 60) # seconds |
| 125 | +bg_update_thread = threading.Thread() |
| 126 | + |
| 127 | +def bg_update_run(): |
| 128 | + '''Background update task''' |
| 129 | + app.logger.debug('Background update started') |
| 130 | + global_data.update_topology() |
| 131 | + |
| 132 | + # Add +/- 10% random offset to avoid thundering herds |
| 133 | + delay = bg_update_freq |
| 134 | + delay *= random.uniform(0.9, 1.1) |
| 135 | + |
| 136 | + # Set next run |
| 137 | + global bg_update_thread |
| 138 | + bg_update_thread = threading.Timer(delay, bg_update_run, ()) |
| 139 | + bg_update_thread.daemon = True |
| 140 | + bg_update_thread.start() |
| 141 | + app.logger.info('Background update complete') |
| 142 | + |
| 143 | +# Start background update thread |
| 144 | +bg_update_thread = threading.Timer(bg_update_freq, bg_update_run, ()) |
| 145 | +# Make it a daemon thread, so interpreter won't wait on it when exiting |
| 146 | +bg_update_thread.daemon = True |
| 147 | +bg_update_thread.start() |
| 148 | +############################################################################# |
| 149 | + |
119 | 150 |
|
120 | 151 | def _fix_unicode(text):
|
121 | 152 | """Convert a partial unicode string to full unicode"""
|
|
0 commit comments