]> git.ipfire.org Git - people/jschlag/pbs.git/blob - src/buildservice/mirrors.py
5b6f76b7299305074b9a36a5306cda3b5e435371
[people/jschlag/pbs.git] / src / buildservice / mirrors.py
1 #!/usr/bin/python
2
3 import datetime
4 import logging
5 import math
6 import socket
7 import time
8 import tornado.httpclient
9 import urlparse
10
11 from . import base
12 from . import logs
13
14 log = logging.getLogger("mirrors")
15 log.propagate = 1
16
17 from .decorators import lazy_property
18
19 class Mirrors(base.Object):
20 def __iter__(self):
21 res = self.db.query("SELECT * FROM mirrors \
22 WHERE deleted IS FALSE ORDER BY hostname")
23
24 mirrors = []
25 for row in res:
26 mirror = Mirror(self.backend, row.id, data=row)
27 mirrors.append(mirror)
28
29 return iter(mirrors)
30
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)
36
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)
40
41 # Log creation
42 mirror.log("created", user=user)
43
44 return mirror
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):
62 return self._get_mirror("SELECT * FROM mirrors WHERE id = %s", id)
63
64 def get_by_hostname(self, hostname):
65 return self._get_mirror("SELECT * FROM mirrors \
66 WHERE hostname = %s AND deleted IS FALSE", hostname)
67
68 def get_for_location(self, address):
69 country_code = self.backend.geoip.guess_from_address(address)
70
71 # Cannot return any good mirrors if location is unknown
72 if not country_code:
73 return []
74
75 mirrors = []
76
77 # Walk through all mirrors
78 for mirror in self:
79 if mirror.country_code == country_code:
80 mirrors.append(mirror)
81
82 # XXX needs to search for nearby countries
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
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)
127
128
129 class Mirror(base.DataObject):
130 table = "mirrors"
131
132 def __eq__(self, other):
133 if isinstance(other, self.__class__):
134 return self.id == other.id
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
144 def set_hostname(self, hostname):
145 self._set_attribute("hostname", hostname)
146
147 hostname = property(lambda self: self.data.hostname, set_hostname)
148
149 def set_deleted(self, deleted):
150 self._set_attribute("deleted", deleted)
151
152 deleted = property(lambda s: s.data.deleted, set_deleted)
153
154 @property
155 def path(self):
156 return self.data.path
157
158 def set_path(self, path):
159 self._set_attribute("path", path)
160
161 path = property(lambda self: self.data.path, set_path)
162
163 @property
164 def url(self):
165 return self.make_url()
166
167 def make_url(self, path=""):
168 url = "%s://%s%s" % (
169 "https" if self.supports_https else "http",
170 self.hostname,
171 self.path
172 )
173
174 if path.startswith("/"):
175 path = path[1:]
176
177 return urlparse.urljoin(url, path)
178
179 def set_supports_https(self, supports_https):
180 self._set_attribute("supports_https", supports_https)
181
182 supports_https = property(lambda s: s.data.supports_https, set_supports_https)
183
184 def set_owner(self, owner):
185 self._set_attribute("owner", owner)
186
187 owner = property(lambda self: self.data.owner or "", set_owner)
188
189 def set_contact(self, contact):
190 self._set_attribute("contact", contact)
191
192 contact = property(lambda self: self.data.contact or "", set_contact)
193
194 def check(self, connect_timeout=10, request_timeout=10):
195 log.info("Running mirror check for %s" % self.hostname)
196
197 client = tornado.httpclient.HTTPClient()
198
199 # Get URL for .timestamp
200 url = self.make_url(".timestamp")
201 log.debug(" Fetching %s..." % url)
202
203 # Record start time
204 time_start = time.time()
205
206 http_status = None
207 last_sync_at = None
208 status = "OK"
209
210 # XXX needs to catch connection resets, DNS errors, etc.
211
212 try:
213 response = client.fetch(url,
214 connect_timeout=connect_timeout,
215 request_timeout=request_timeout)
216
217 # We expect the response to be an integer
218 # which holds the timestamp of the last sync
219 # in seconds since epoch UTC
220 try:
221 timestamp = int(response.body)
222 except ValueError:
223 raise
224
225 # Convert to datetime
226 last_sync_at = datetime.datetime.utcfromtimestamp(timestamp)
227
228 # Must have synced within 24 hours
229 now = datetime.datetime.utcnow()
230 if now - last_sync_at >= datetime.timedelta(hours=24):
231 status = "OUTOFSYNC"
232
233 except tornado.httpclient.HTTPError as e:
234 http_status = e.code
235 status = "ERROR"
236
237 finally:
238 response_time = time.time() - time_start
239
240 # Log check
241 self.db.execute("INSERT INTO mirrors_checks(mirror_id, response_time, \
242 http_status, last_sync_at, status) VALUES(%s, %s, %s, %s, %s)",
243 self.id, response_time, http_status, last_sync_at, status)
244
245 @lazy_property
246 def last_check(self):
247 res = self.db.get("SELECT * FROM mirrors_checks \
248 WHERE mirror_id = %s ORDER BY timestamp DESC LIMIT 1", self.id)
249
250 return res
251
252 @property
253 def status(self):
254 if self.last_check:
255 return self.last_check.status
256
257 @property
258 def average_response_time(self):
259 res = self.db.get("SELECT AVG(response_time) AS response_time \
260 FROM mirrors_checks WHERE mirror_id = %s \
261 AND timestamp >= NOW() - '24 hours'::interval", self.id)
262
263 return res.response_time
264
265 @property
266 def address(self):
267 return socket.gethostbyname(self.hostname)
268
269 @lazy_property
270 def country_code(self):
271 return self.backend.geoip.guess_from_address(self.address) or "UNKNOWN"
272
273 def get_history(self, *args, **kwargs):
274 kwargs["mirror"] = self
275
276 return self.pakfire.mirrors.get_history(*args, **kwargs)