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