vpac / src / mirrors.v
554 lines · 512 sloc · 17.95 KB · 3609dfbd82867dc1034a443f8f9ced529ddbbedd
Raw
1@[has_globals]
2module main
3
4import blip.vlib.blip.printer
5import json2
6import net.http
7import os
8import time
9
10// mirror ranking, after rate-mirrors (westandskif/rate-mirrors): gather the
11// candidates, drop the unusable ones, time one byte for latency, then time a
12// repo database for speed, and rank by speed. the oses the ranker knows are
13// in rank_oses; the protocols to rank come from the config
14
15// the rank form's filters and sizes, (rank :completion :max-delay :candidates
16// :retest :top): how complete and how fresh a mirror must be to be probed,
17// how many of the lowest latencies get the speed test, how many of the
18// fastest are timed again, and how many are answered when -n names none
19__global rank_min_completion = 1.0
20__global rank_max_delay = i64(86400)
21
22// rank_parallelism is how many mirrors to probe at once: the rank form's
23// :parallel when it sets one, else the network's :parallel
24fn rank_parallelism() int {
25 return if rank_parallel > 0 { rank_parallel } else { parallel_downloads }
26}
27
28__global rank_speed_candidates = 40
29__global rank_retest = 5
30__global rank_top = 10
31
32// RankOs is one os the ranker knows. the mirror data comes from the status
33// api when the os publishes one, else from a plain Server = mirrorlist, which
34// carries no completion or delay to filter by. repo is the repo whose db the
35// speed test pulls, named again in the written urls
36struct RankOs {
37 status_json string
38 mirrorlist string
39 repo string
40}
41
42// default_rank_oses are the oses the ranker knows before the config speaks
43fn default_rank_oses() map[string]RankOs {
44 return {
45 'artix': RankOs{
46 status_json: 'https://status.artixlinux.org/mirrors/status/json/'
47 repo: 'system'
48 }
49 'arch': RankOs{
50 status_json: 'https://archlinux.org/mirrors/status/json/'
51 repo: 'core'
52 }
53 'cachyos': RankOs{
54 mirrorlist: 'https://raw.githubusercontent.com/CachyOS/CachyOS-PKGBUILDS/master/cachyos-mirrorlist/cachyos-mirrorlist'
55 repo: 'cachyos'
56 }
57 }
58}
59
60// rank_oses are the oses the ranker knows: the defaults, and every one the
61// config's (mirrorlist ...) form defines or redefines. rank_dir is where a
62// ranking is written for the config to require, (rank :dir)
63__global rank_oses = default_rank_oses()
64__global rank_dir = '/etc/vpac.d/mirrors'
65
66// rank_os_names spells the known oses for a message, sorted: the text is
67// the same whatever order the config's forms came in
68fn rank_os_names() string {
69 mut names := rank_oses.keys()
70 names.sort()
71 return names.join(', ')
72}
73
74// rank_os_name picks the os to rank: the one named on the command line, or
75// the running system's, read from /etc/os-release
76fn rank_os_name(query []string) !string {
77 if query.len > 1 {
78 return error('rank takes one os: ${rank_os_names()}')
79 }
80 if query.len == 1 {
81 if query[0] !in rank_oses.keys() {
82 return error('the ranker knows ${rank_os_names()}, not "${query[0]}": define it with (mirrorlist :name ...) in the config')
83 }
84 return query[0]
85 }
86 text := os.read_file('/etc/os-release') or {
87 return error('could not read /etc/os-release to detect the os: pass one of ${rank_os_names()}')
88 }
89 mut id := ''
90 mut like := ''
91 for line in text.split_into_lines() {
92 if line.starts_with('ID=') {
93 id = line[3..].trim_space().trim('"\'')
94 } else if line.starts_with('ID_LIKE=') {
95 like = line[8..].trim_space().trim('"\'')
96 }
97 }
98 for candidate in [id, ...like.split(' ')] {
99 if candidate in rank_oses.keys() {
100 return candidate
101 }
102 }
103 return error('this system (${id}) is not one the ranker knows: pass one of ${rank_os_names()}, or define it with (mirrorlist :name ...) in the config')
104}
105
106// rank_write_target is where a ranked os is written for the config to require
107fn rank_write_target(os_name string) string {
108 return os.join_path(rank_dir, '${os_name}.lip')
109}
110
111struct StatusMirror {
112 url string
113 protocol string
114 last_sync string
115 completion_pct ?f64
116 delay ?i64
117 active bool
118 country_code string
119}
120
121struct StatusList {
122 urls []StatusMirror
123}
124
125// Mirror is a candidate: its full url template, with the repo and arch
126// placeholders left in place the way the config's mirror files hold them, and
127// when it last synced
128struct Mirror {
129 url string
130 last_sync string
131}
132
133// probe_url is the concrete url of one mirror's repo db: the template with
134// the repo and arch substituted in, plus the db file. a path override takes
135// the mirror root instead, which is where a custom file hangs from
136fn probe_url(m Mirror, spec RankOs, override string) string {
137 if override != '' {
138 return m.url.all_before('$') + override
139 }
140 return m.url.replace('$repo', spec.repo).replace('$arch', arch) + '/${spec.repo}.db'
141}
142
143fn with_slash(url string) string {
144 return if url.ends_with('/') { url } else { url + '/' }
145}
146
147// timed_fetch fetches one url with the rank timeout on both directions, and
148// hands back the body: it is what the ranker asks of the network, from the
149// mirror status on to the mirrorlists, since a stalled dns or a captive
150// portal would otherwise visit its hang on the ranking
151fn timed_fetch(url string, what string) !string {
152 return http_text(url, rank_timeout, what, url)
153}
154
155// http_text is one GET bounded by a timeout, in seconds, on both
156// directions, answering the body of an answer that succeeded. what names
157// the fetch and from the server in the error, so a refusal is told from a
158// stall. the ranker's fetches and the pkgbuild rpc both go through it
159fn http_text(url string, seconds int, what string, from string) !string {
160 mut req := http.Request{
161 url: url
162 read_timeout: seconds * time.second
163 write_timeout: seconds * time.second
164 }
165 resp := req.do() or { return error('${what} failed: ${err}') }
166 if resp.status_code < 200 || resp.status_code >= 300 {
167 return error('${what} failed: http ${resp.status_code} from ${from}')
168 }
169 return resp.body
170}
171
172// fetch_status_mirrors reads an os's mirror status and keeps the mirrors that
173// are usable: active, on a configured protocol, fully synced, recently synced,
174// with a known country
175fn fetch_status_mirrors(os_name string, spec RankOs) ![]Mirror {
176 body := timed_fetch(spec.status_json, 'fetching the ${os_name} mirror status')!
177 status := json2.decode[StatusList](body) or {
178 return error('could not read the ${os_name} mirror status: ${err.msg()}')
179 }
180 mut out := []Mirror{}
181 for m in status.urls {
182 completion := m.completion_pct or { continue }
183 delay := m.delay or { continue }
184 if m.active && m.protocol in cfg_protocols && completion >= rank_min_completion
185 && delay <= rank_max_delay && m.country_code != '' {
186 // the status api gives the mirror root; the repo layout of the os
187 // completes it to the template the config's mirror files hold
188 out << Mirror{
189 url: with_slash(m.url) + '$repo/os/$arch'
190 last_sync: m.last_sync
191 }
192 }
193 }
194 return out
195}
196
197// fetch_mirrorlist reads a plain Server = list, for the oses that publish no
198// status api: fetched, or read from the disk when the config names a path
199fn fetch_mirrorlist(spec RankOs) ![]Mirror {
200 if spec.mirrorlist.starts_with('/') {
201 text := os.read_file(spec.mirrorlist) or {
202 return error('could not read the mirrorlist ${spec.mirrorlist}: ${err.msg()}')
203 }
204 return parse_mirrors(text)
205 }
206 body := timed_fetch(spec.mirrorlist, 'fetching the mirrorlist')!
207 return parse_mirrors(body)
208}
209
210// parse_mirrors reads 'Server = url' lines or bare urls, one per line, as the
211// mirrorlists write them. the line already carries the os's repo layout, so
212// it is kept whole
213fn parse_mirrors(text string) []Mirror {
214 mut out := []Mirror{}
215 mut seen := map[string]bool{}
216 for line in text.split_into_lines() {
217 mut s := line.trim_space()
218 if s.starts_with('Server = ') {
219 s = s.all_after('Server = ').trim_space()
220 }
221 if s.starts_with('#') || !(s.starts_with('https://') || s.starts_with('http://')) {
222 continue
223 }
224 if seen[s] {
225 continue
226 }
227 seen[s] = true
228 out << Mirror{
229 url: s
230 }
231 }
232 return out
233}
234
235// stdin_text reads stdin to its end, the lines joined again. a read error is
236// an error here, not an end: a mirror list cut short must not rank as the
237// whole of it
238fn stdin_text() !string {
239 mut lines := []string{}
240 for {
241 lines << stdin_line() or {
242 if err is StdinEnd {
243 break
244 }
245 return err
246 }
247 }
248 return lines.join('\n')
249}
250
251// timed_get fetches a url and returns the milliseconds it took and the size
252// of the answer. range asks for the first byte only, which measures latency.
253// the timeout comes from the config, and it bounds the probe twice over: each
254// read and write on its own, and the answer as a whole. the socket timeouts
255// alone start over with every read, so a mirror that trickles its db a few
256// bytes at a time would hold a speed probe for as long as it cared to; the
257// deadline is looked at on each chunk that arrives, and an answer still
258// arriving past it is the probe's failure
259fn timed_get(url string, range bool) !(i64, int) {
260 limit := rank_timeout
261 deadline := time.now().add(limit * time.second)
262 mut req := http.Request{
263 url: url
264 read_timeout: limit * time.second
265 write_timeout: limit * time.second
266 on_progress: fn [deadline, limit] (_ &http.Request, _ []u8, _ u64) ! {
267 if time.now() > deadline {
268 return error('no whole answer within ${limit}s')
269 }
270 }
271 }
272 if range {
273 req.header.add_custom('Range', 'bytes=0-0')!
274 }
275 start := time.now()
276 resp := req.do()!
277 // an answer that needs no body — a 404, a 403 — is a mirror that does
278 // not serve the repo db: a probe without body size is ranked on air
279 // unless the status is turned into the probe's failure
280 if resp.status_code < 200 || resp.status_code >= 300 {
281 return error('http ${resp.status_code} from ${url}')
282 }
283 return (time.now() - start).milliseconds(), resp.body.len
284}
285
286fn probe_latency(m Mirror, spec RankOs, override string) Probe {
287 ms, _ := timed_get(probe_url(m, spec, override), true) or {
288 return Probe{
289 url: m.url
290 }
291 }
292 return timed_probe(m.url, ms, 0, false)
293}
294
295fn probe_speed(m Mirror, spec RankOs, override string) Probe {
296 ms, bytes := timed_get(probe_url(m, spec, override), false) or {
297 return Probe{
298 url: m.url
299 }
300 }
301 return timed_probe(m.url, ms, bytes, true)
302}
303
304// timed_probe is a probe's result out of what the timed request measured:
305// the latency always, and with speed the bytes a second of a whole fetch —
306// one that brought no bytes failed, and one quicker than the clock's
307// millisecond counts as one, never a division by zero
308fn timed_probe(url string, ms i64, bytes int, speed bool) Probe {
309 if !speed {
310 return Probe{
311 url: url
312 latency_ms: ms
313 ok: true
314 }
315 }
316 if bytes <= 0 {
317 return Probe{
318 url: url
319 }
320 }
321 elapsed := if ms <= 0 { 1 } else { ms }
322 return Probe{
323 url: url
324 latency_ms: ms
325 speed: f64(bytes) / (f64(elapsed) / 1000.0)
326 ok: true
327 }
328}
329
330// Probe is the result of testing one mirror
331struct Probe {
332 url string
333 latency_ms i64
334 speed f64
335 ok bool
336}
337
338// ProbeFn measures one mirror, the os and the path override closed over. it
339// answers a Probe on every path — a failure is a Probe that is not ok — and
340// that is what lets probe_batch count on one answer per mirror
341type ProbeFn = fn (Mirror) Probe
342
343// probe_batch tests every mirror, rank_parallelism() at a time, and advances
344// the bar by each finished probe. quiet draws no bar, so the output can be
345// piped. the answers come back in the order they finish, not the input's
346fn probe_batch(mut ui TransUI, label string, mirrors []Mirror, probe ProbeFn, quiet bool) []Probe {
347 mut out := []Probe{cap: mirrors.len}
348 if mirrors.len == 0 {
349 return out
350 }
351 mut bar := unsafe { &Meter(nil) }
352 if !quiet {
353 bar = ui.meter(i64(mirrors.len), label)
354 bar.start()
355 }
356 // a parallelism that slipped past the config's floor would start no
357 // worker at all: one at a time is the least
358 conc := if rank_parallelism() < 1 { 1 } else { rank_parallelism() }
359 workers := if conc < mirrors.len { conc } else { mirrors.len }
360 // the whole batch is queued, then the queue closed: a worker that finds
361 // it drained is done. a pool rather than slots of conc means a slow probe
362 // holds back only its own worker, not the next slot's fast ones
363 jobs := chan Mirror{cap: mirrors.len}
364 for m in mirrors {
365 jobs <- m
366 }
367 jobs.close()
368 // the answers channel holds a whole batch, so a worker never waits on the
369 // collector to hand its answer over
370 answers := chan Probe{cap: mirrors.len}
371 for _ in 0 .. workers {
372 spawn probe_worker(jobs, answers, probe)
373 }
374 // one answer per mirror, each sent by the worker that took it: the probe
375 // answers on every path, and a panic in any thread ends the process
376 // rather than stranding this loop. a probe that hangs is bounded by the
377 // network's own timeouts (rank_timeout on read and write, the net
378 // module's on connect) and by timed_get's deadline on the whole answer
379 for _ in 0 .. mirrors.len {
380 out << <-answers
381 if !quiet {
382 bar.add(i64(1))
383 }
384 }
385 return out
386}
387
388// probe_worker measures mirrors until the queue runs dry. the probe runs on
389// this thread: the arguments of a spawned call are evaluated by the caller,
390// so spawning the send of a probe's result runs every probe on the collector,
391// one after another
392fn probe_worker(jobs chan Mirror, answers chan Probe, probe ProbeFn) {
393 for {
394 m := <-jobs or { return }
395 answers <- probe(m)
396 }
397}
398
399fn speed_mib(bytes_per_sec f64) string {
400 return '${bytes_per_sec / 1048576.0:.2f} MiB/s'
401}
402
403fn sync_age(last_sync string) string {
404 if last_sync == '' {
405 return '-'
406 }
407 synced := time.parse_rfc3339(last_sync) or { return '-' }
408 hours := (time.now().unix() - synced.unix()) / 3600
409 return '${hours}h ago'
410}
411
412// mirrors_lip is the blip file of the ranked urls: mirrors/<os>.lip defines
413// mirrors-<os>, the way repos.lip expects. each url is a string literal
414// escaped by blip's own printer: the urls come from the network and the file
415// is config that vpac runs as root, so a quote in a url must stay inside its
416// string
417fn mirrors_lip(os_name string, urls []string, date string) string {
418 var := 'mirrors-${os_name}'
419 mut content := '; mirrors for ${os_name}, ranked by vpac k -w on ${date}\n'
420 content += '(unless (defined? ${var}) (define ${var} []))\n'
421 content += '(array-append! ${var} [${urls.map(printer.quote_string(it)).join(' ')}])\n'
422 return content
423}
424
425// write_config_mirrors writes the ranked urls as the blip file the config
426// requires
427fn write_config_mirrors(os_name string, urls []string) !string {
428 target := rank_write_target(os_name)
429 os.mkdir_all(os.dir(target))!
430 os.write_file(target, mirrors_lip(os_name, urls, time.now().custom_format('YYYY-MM-DD')))!
431 return target
432}
433
434// Ranked is one mirror of a ranking: its probe, and when it last synced as
435// the mirror status says ('' when it is not known)
436struct Ranked {
437 Probe
438 last_sync string
439}
440
441// rank_mirrors measures the mirrors of an os and returns the best of them,
442// at most config.top, fastest first. the probes draw on the ui unless the
443// result goes to a file or a mirrorlist
444fn rank_mirrors(mut ui TransUI, os_name string, config ConfigRank) ![]Ranked {
445 spec := rank_oses[os_name]
446 mirrors := if config.stdin {
447 parse_mirrors(stdin_text()!)
448 } else if spec.status_json != '' {
449 fetch_status_mirrors(os_name, spec)!
450 } else {
451 fetch_mirrorlist(spec)!
452 }
453 if mirrors.len == 0 {
454 return error('no usable mirrors to rank')
455 }
456 mut sync_of := map[string]string{}
457 for m in mirrors {
458 sync_of[m.url] = m.last_sync
459 }
460
461 quiet := config.mirrorlist || config.output != ''
462 override := config.path
463 mut latency := probe_batch(mut ui, 'latency', mirrors, fn [spec, override] (m Mirror) Probe {
464 return probe_latency(m, spec, override)
465 }, quiet).filter(it.ok)
466 latency.sort(a.latency_ms < b.latency_ms)
467 if latency.len > rank_speed_candidates {
468 latency = latency[..rank_speed_candidates].clone()
469 }
470 candidates := latency.map(Mirror{
471 url: it.url
472 last_sync: sync_of[it.url] or { '' }
473 })
474
475 mut results := probe_batch(mut ui, 'speed', candidates, fn [spec, override] (m Mirror) Probe {
476 return probe_speed(m, spec, override)
477 }, quiet).filter(it.ok)
478 results.sort(a.speed > b.speed)
479
480 // the best few are measured again, one at a time, and averaged, so one
481 // lucky or unlucky transfer does not decide the order
482 for i in 0 .. if results.len < rank_retest { results.len } else { rank_retest } {
483 again := probe_speed(Mirror{ url: results[i].url }, spec, config.path)
484 if again.ok {
485 results[i] = Probe{
486 url: results[i].url
487 latency_ms: results[i].latency_ms
488 speed: (results[i].speed + again.speed) / 2.0
489 ok: true
490 }
491 }
492 }
493 results.sort(a.speed > b.speed)
494 ui.stop()
495
496 if results.len == 0 {
497 return error('no mirror answered the speed test')
498 }
499 top := if results.len < config.top { results.len } else { config.top }
500 return results[..top].map(Ranked{
501 Probe: it
502 last_sync: sync_of[it.url] or { '' }
503 })
504}
505
506// rank ranks the mirrors, then writes them where config says, or prints them
507fn rank(config ConfigRank) ! {
508 os_name := rank_os_name(config.query)!
509 mut ui := new_trans_ui()
510 defer {
511 ui.stop()
512 }
513 ranked := rank_mirrors(mut ui, os_name, config)!
514
515 urls := ranked.map(it.url)
516 if config.write {
517 target := write_config_mirrors(os_name, urls)!
518 report('wrote ${urls.len} mirrors to ${target}')
519 }
520 // a frontend gets the ranking itself, and formats it as it needs: the
521 // mirrorlist and output forms shape the printable text, which under
522 // --ui ipc lands in the log anyway, so the event goes out before
523 // whatever those flags do with the result
524 if ipc_on() {
525 emit(MirrorsEvent{
526 mirrors: ranked.map(MirrorEvent{
527 url: it.url
528 latency_ms: it.latency_ms
529 speed: it.speed
530 last_sync: it.last_sync
531 })
532 })
533 }
534 if config.output != '' {
535 os.write_file(config.output, urls.map('Server = ${it}').join('\n') + '\n')!
536 report('wrote ${urls.len} mirrors to ${config.output}')
537 return
538 }
539 if config.mirrorlist {
540 println(urls.map('Server = ${it}').join('\n'))
541 return
542 }
543 if ipc_on() {
544 return
545 }
546 // sync paints the finished spinner frames before the ranking prints
547 ui.sync()
548 mut rows := []Row{}
549 for i, m in ranked {
550 rows << row('${i + 1}', m.url.all_before('$'), '${m.latency_ms} ms', speed_mib(m.speed),
551 sync_age(m.last_sync))
552 }
553 println(table_text(rows, '', ' '))
554}
555