]> git.ipfire.org Git - people/jschlag/pbs.git/blame - src/buildservice/mirrors.py
mirror check: Catch any false responses
[people/jschlag/pbs.git] / src / buildservice / mirrors.py
CommitLineData
f6e6ff79
MT
1#!/usr/bin/python
2
c660ff59 3import datetime
f6e6ff79
MT
4import logging
5import math
6import socket
c660ff59
MT
7import time
8import tornado.httpclient
9import urlparse
f6e6ff79 10
2c909128
MT
11from . import base
12from . import logs
f6e6ff79 13
c660ff59
MT
14log = logging.getLogger("mirrors")
15log.propagate = 1
16
d3e7a9fb 17from .decorators import lazy_property
f6e6ff79
MT
18
19class Mirrors(base.Object):
c660ff59
MT
20 def _get_mirror(self, query, *args):
21 res = self.db.get(query, *args)
22
23 if res:
24 return Mirror(self.backend, res.id, data=res)
f6e6ff79 25
313331aa
MT
26 def _get_mirrors(self, query, *args):
27 res = self.db.query(query, *args)
28
29 for row in res:
30 yield Mirror(self.backend, row.id, data=row)
31
32 def __iter__(self):
33 mirrors = self._get_mirrors("SELECT * FROM mirrors \
34 WHERE deleted IS FALSE ORDER BY hostname")
35
36 return iter(mirrors)
37
c660ff59
MT
38 def create(self, hostname, path="", owner=None, contact=None, user=None):
39 mirror = self._get_mirror("INSERT INTO mirrors(hostname, path, owner, contact) \
40 VALUES(%s, %s, %s, %s) RETURNING *", hostname, path, owner, contact)
f6e6ff79 41
c660ff59
MT
42 # Log creation
43 mirror.log("created", user=user)
f6e6ff79 44
c660ff59 45 return mirror
f6e6ff79 46
f6e6ff79 47 def get_by_id(self, id):
c660ff59 48 return self._get_mirror("SELECT * FROM mirrors WHERE id = %s", id)
f6e6ff79
MT
49
50 def get_by_hostname(self, hostname):
c660ff59
MT
51 return self._get_mirror("SELECT * FROM mirrors \
52 WHERE hostname = %s AND deleted IS FALSE", hostname)
f6e6ff79 53
c660ff59
MT
54 def get_for_location(self, address):
55 country_code = self.backend.geoip.guess_from_address(address)
f6e6ff79 56
d3e7a9fb
MT
57 # Cannot return any good mirrors if location is unknown
58 if not country_code:
59 return []
f6e6ff79
MT
60
61 mirrors = []
f6e6ff79 62
d3e7a9fb 63 # Walk through all mirrors
07ee26ad 64 for mirror in self:
d3e7a9fb
MT
65 if mirror.country_code == country_code:
66 mirrors.append(mirror)
f6e6ff79 67
d3e7a9fb 68 # XXX needs to search for nearby countries
f6e6ff79
MT
69
70 return mirrors
71
72 def get_history(self, limit=None, offset=None, mirror=None, user=None):
73 query = "SELECT * FROM mirrors_history"
74 args = []
75
76 conditions = []
77
78 if mirror:
79 conditions.append("mirror_id = %s")
80 args.append(mirror.id)
81
82 if user:
83 conditions.append("user_id = %s")
84 args.append(user.id)
85
86 if conditions:
87 query += " WHERE %s" % " AND ".join(conditions)
88
89 query += " ORDER BY time DESC"
90
91 if limit:
92 if offset:
93 query += " LIMIT %s,%s"
94 args += [offset, limit,]
95 else:
96 query += " LIMIT %s"
97 args += [limit,]
98
99 entries = []
100 for entry in self.db.query(query, *args):
101 entry = logs.MirrorLogEntry(self.pakfire, entry)
102 entries.append(entry)
103
104 return entries
105
c660ff59
MT
106 def check(self, **kwargs):
107 """
108 Runs the mirror check for all mirrors
109 """
110 for mirror in self:
111 with self.db.transaction():
112 mirror.check(**kwargs)
f6e6ff79 113
f6e6ff79 114
c660ff59
MT
115class Mirror(base.DataObject):
116 table = "mirrors"
f6e6ff79 117
c660ff59
MT
118 def __eq__(self, other):
119 if isinstance(other, self.__class__):
120 return self.id == other.id
f6e6ff79
MT
121
122 def log(self, action, user=None):
123 user_id = None
124 if user:
125 user_id = user.id
126
127 self.db.execute("INSERT INTO mirrors_history(mirror_id, action, user_id, time) \
128 VALUES(%s, %s, %s, NOW())", self.id, action, user_id)
129
f6e6ff79 130 def set_hostname(self, hostname):
c660ff59 131 self._set_attribute("hostname", hostname)
f6e6ff79
MT
132
133 hostname = property(lambda self: self.data.hostname, set_hostname)
134
ac8f5d9c
MT
135 def set_deleted(self, deleted):
136 self._set_attribute("deleted", deleted)
137
138 deleted = property(lambda s: s.data.deleted, set_deleted)
139
f6e6ff79
MT
140 @property
141 def path(self):
142 return self.data.path
143
144 def set_path(self, path):
c660ff59 145 self._set_attribute("path", path)
f6e6ff79
MT
146
147 path = property(lambda self: self.data.path, set_path)
148
149 @property
150 def url(self):
c660ff59 151 return self.make_url()
f6e6ff79 152
c660ff59 153 def make_url(self, path=""):
3163c789
MT
154 url = "%s://%s%s" % (
155 "https" if self.supports_https else "http",
156 self.hostname,
157 self.path
158 )
f6e6ff79 159
c660ff59
MT
160 if path.startswith("/"):
161 path = path[1:]
f6e6ff79 162
c660ff59 163 return urlparse.urljoin(url, path)
f6e6ff79 164
3163c789
MT
165 def set_supports_https(self, supports_https):
166 self._set_attribute("supports_https", supports_https)
167
168 supports_https = property(lambda s: s.data.supports_https, set_supports_https)
169
c660ff59
MT
170 def set_owner(self, owner):
171 self._set_attribute("owner", owner)
f6e6ff79 172
c660ff59 173 owner = property(lambda self: self.data.owner or "", set_owner)
f6e6ff79 174
c660ff59
MT
175 def set_contact(self, contact):
176 self._set_attribute("contact", contact)
f6e6ff79 177
c660ff59 178 contact = property(lambda self: self.data.contact or "", set_contact)
f6e6ff79 179
c660ff59
MT
180 def check(self, connect_timeout=10, request_timeout=10):
181 log.info("Running mirror check for %s" % self.hostname)
f6e6ff79 182
c660ff59 183 client = tornado.httpclient.HTTPClient()
f6e6ff79 184
c660ff59
MT
185 # Get URL for .timestamp
186 url = self.make_url(".timestamp")
187 log.debug(" Fetching %s..." % url)
f6e6ff79 188
c660ff59
MT
189 # Record start time
190 time_start = time.time()
f6e6ff79 191
c660ff59
MT
192 http_status = None
193 last_sync_at = None
194 status = "OK"
f6e6ff79 195
c660ff59 196 # XXX needs to catch connection resets, DNS errors, etc.
f6e6ff79 197
c660ff59
MT
198 try:
199 response = client.fetch(url,
200 connect_timeout=connect_timeout,
201 request_timeout=request_timeout)
f6e6ff79 202
c660ff59
MT
203 # We expect the response to be an integer
204 # which holds the timestamp of the last sync
205 # in seconds since epoch UTC
206 try:
207 timestamp = int(response.body)
9950acfe
MT
208
209 # If we could not parse the timestamp, we probably got
210 # an error page or something similar.
211 # So that's an error then...
c660ff59 212 except ValueError:
9950acfe 213 status = "ERROR"
c660ff59 214
9950acfe
MT
215 # Timestamp seems to be okay
216 else:
217 # Convert to datetime
218 last_sync_at = datetime.datetime.utcfromtimestamp(timestamp)
c660ff59 219
9950acfe
MT
220 # Must have synced within 24 hours
221 now = datetime.datetime.utcnow()
222 if now - last_sync_at >= datetime.timedelta(hours=24):
223 status = "OUTOFSYNC"
c660ff59
MT
224
225 except tornado.httpclient.HTTPError as e:
226 http_status = e.code
227 status = "ERROR"
228
229 finally:
230 response_time = time.time() - time_start
231
232 # Log check
233 self.db.execute("INSERT INTO mirrors_checks(mirror_id, response_time, \
234 http_status, last_sync_at, status) VALUES(%s, %s, %s, %s, %s)",
235 self.id, response_time, http_status, last_sync_at, status)
236
237 @lazy_property
238 def last_check(self):
239 res = self.db.get("SELECT * FROM mirrors_checks \
240 WHERE mirror_id = %s ORDER BY timestamp DESC LIMIT 1", self.id)
241
242 return res
f6e6ff79
MT
243
244 @property
c660ff59
MT
245 def status(self):
246 if self.last_check:
247 return self.last_check.status
f6e6ff79
MT
248
249 @property
c660ff59
MT
250 def average_response_time(self):
251 res = self.db.get("SELECT AVG(response_time) AS response_time \
252 FROM mirrors_checks WHERE mirror_id = %s \
253 AND timestamp >= NOW() - '24 hours'::interval", self.id)
254
255 return res.response_time
f6e6ff79
MT
256
257 @property
258 def address(self):
259 return socket.gethostbyname(self.hostname)
260
d3e7a9fb 261 @lazy_property
f6e6ff79 262 def country_code(self):
d3e7a9fb 263 return self.backend.geoip.guess_from_address(self.address) or "UNKNOWN"
f6e6ff79
MT
264
265 def get_history(self, *args, **kwargs):
266 kwargs["mirror"] = self
267
268 return self.pakfire.mirrors.get_history(*args, **kwargs)