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