vpac / src / mirrors.v
627 lines · 581 sloc · 20.25 KB · 841315c100c81d9e6b14c4b55a25d4e3d12db762
Raw
1@[has_globals]
2module main
3
4import vile.scheme
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 extension := if config_vile { 'vile' } else { 'scm' }
109 return os.join_path(rank_dir, '${os_name}.${extension}')
110}
111
112struct StatusMirror {
113 url string
114 protocol string
115 last_sync string
116 completion_pct ?f64
117 delay ?i64
118 active bool
119 country_code string
120}
121
122struct StatusList {
123 urls []StatusMirror
124}
125
126// Mirror is a candidate: its full url template, with the repo and arch
127// placeholders left in place the way the config's mirror files hold them, and
128// when it last synced
129struct Mirror {
130 url string
131 last_sync string
132}
133
134// probe_url is the concrete url of one mirror's repo db: the template with
135// the repo and arch substituted in, plus the db file. a path override takes
136// the mirror root instead, which is where a custom file hangs from
137fn probe_url(m Mirror, spec RankOs, override string) string {
138 if override != '' {
139 return m.url.all_before('$') + override
140 }
141 return m.url.replace('$repo', spec.repo).replace('$arch', arch) + '/${spec.repo}.db'
142}
143
144fn with_slash(url string) string {
145 return if url.ends_with('/') { url } else { url + '/' }
146}
147
148// timed_fetch fetches one url with the rank timeout on both directions, and
149// hands back the body: it is what the ranker asks of the network, from the
150// mirror status on to the mirrorlists, since a stalled dns or a captive
151// portal would otherwise visit its hang on the ranking
152fn timed_fetch(url string, what string) !string {
153 return http_text(url, rank_timeout, what, url)
154}
155
156// http_text is one GET bounded by a timeout, in seconds, on both
157// directions, answering the body of an answer that succeeded. what names
158// the fetch and from the server in the error, so a refusal is told from a
159// stall. the ranker's fetches and the pkgbuild rpc both go through it
160fn http_text(url string, seconds int, what string, from string) !string {
161 mut req := http.Request{
162 url: url
163 read_timeout: seconds * time.second
164 write_timeout: seconds * time.second
165 }
166 resp := req.do() or { return error('${what} failed: ${err}') }
167 if resp.status_code < 200 || resp.status_code >= 300 {
168 return error('${what} failed: http ${resp.status_code} from ${from}')
169 }
170 return resp.body
171}
172
173// fetch_status_mirrors reads an os's mirror status and keeps the mirrors that
174// are usable: active, on a configured protocol, fully synced, recently synced,
175// with a known country
176fn fetch_status_mirrors(os_name string, spec RankOs) ![]Mirror {
177 body := timed_fetch(spec.status_json, 'fetching the ${os_name} mirror status')!
178 status := json2.decode[StatusList](body) or {
179 return error('could not read the ${os_name} mirror status: ${err.msg()}')
180 }
181 mut out := []Mirror{}
182 for m in status.urls {
183 completion := m.completion_pct or { continue }
184 delay := m.delay or { continue }
185 if m.active && m.protocol in cfg_protocols && completion >= rank_min_completion
186 && delay <= rank_max_delay && m.country_code != '' {
187 // the status api gives the mirror root; the repo layout of the os
188 // completes it to the template the config's mirror files hold
189 out << Mirror{
190 url: with_slash(m.url) + '$repo/os/$arch'
191 last_sync: m.last_sync
192 }
193 }
194 }
195 return out
196}
197
198// fetch_mirrorlist reads a plain Server = list, for the oses that publish no
199// status api: fetched, or read from the disk when the config names a path
200fn fetch_mirrorlist(spec RankOs) ![]Mirror {
201 if spec.mirrorlist.starts_with('/') {
202 text := os.read_file(spec.mirrorlist) or {
203 return error('could not read the mirrorlist ${spec.mirrorlist}: ${err.msg()}')
204 }
205 return parse_mirrors(text)
206 }
207 body := timed_fetch(spec.mirrorlist, 'fetching the mirrorlist')!
208 return parse_mirrors(body)
209}
210
211// parse_mirrors reads 'Server = url' lines or bare urls, one per line, as the
212// mirrorlists write them. the line already carries the os's repo layout, so
213// it is kept whole
214fn parse_mirrors(text string) []Mirror {
215 mut out := []Mirror{}
216 mut seen := map[string]bool{}
217 for line in text.split_into_lines() {
218 mut s := line.trim_space()
219 if s.starts_with('Server = ') {
220 s = s.all_after('Server = ').trim_space()
221 }
222 if s.starts_with('#') || !(s.starts_with('https://') || s.starts_with('http://')) {
223 continue
224 }
225 if seen[s] {
226 continue
227 }
228 seen[s] = true
229 out << Mirror{
230 url: s
231 }
232 }
233 return out
234}
235
236// stdin_text reads stdin to its end, the lines joined again. a read error is
237// an error here, not an end: a mirror list cut short must not rank as the
238// whole of it
239fn stdin_text() !string {
240 mut lines := []string{}
241 for {
242 lines << stdin_line() or {
243 if err is StdinEnd {
244 break
245 }
246 return err
247 }
248 }
249 return lines.join('\n')
250}
251
252// FetchOutcome is what a fetch hands back over its job's reply channel: the
253// measurement of an answer that came whole, the failure text of one that did
254// not
255struct FetchOutcome {
256 ms i64
257 size int
258 err string
259}
260
261// FetchJob is one fetch for a fetcher thread: the request to make and the
262// channel to answer on. the job crosses to the fetcher as a value: the
263// arguments of a spawned call and heap objects handed across threads have
264// been seen carrying another probe's values, so a fetch travels by copy and
265// the fetcher spawns with no arguments at all
266struct FetchJob {
267 url string
268 range bool
269 limit i64
270 deadline time.Time
271 reply chan FetchOutcome
272}
273
274// fetch_jobs is the queue the fetcher threads serve
275__global fetch_jobs = chan FetchJob{cap: 256}
276
277// timed_get fetches a url and returns the milliseconds it took and the size
278// of the answer. range asks for the first byte only, which measures latency.
279// the timeout comes from the config, and it bounds the probe twice over: each
280// read and write on its own, and the answer as a whole. the socket timeouts
281// alone start over with every read, so a mirror that trickles its db a few
282// bytes at a time would hold a speed probe for as long as it cared to. the
283// request therefore runs on a fetcher thread and the wait on its answer is
284// bounded by the deadline directly — a bound that holds even when no chunk
285// arrives to fire on_progress, as from a mirror that falls silent. the
286// callback stays as the fetcher's own early exit: the first chunk past the
287// deadline unwinds it, so a stalled fetch does not linger past its read_timeout
288fn timed_get(url string, range bool) !(i64, int) {
289 limit := rank_timeout
290 job := FetchJob{
291 url: url
292 range: range
293 limit: limit
294 deadline: time.now().add(limit * time.second)
295 reply: chan FetchOutcome{cap: 1}
296 }
297 fetch_jobs <- job
298 spawn fetch_worker()
299 mut res := FetchOutcome{}
300 mut timed := false
301 select {
302 res = <-job.reply {
303 }
304 // the timeout branch counts nanoseconds, the unit of time.Duration
305 job.deadline - time.now() {
306 timed = true
307 }
308 }
309 if timed {
310 return error('no whole answer within ${limit}s')
311 }
312 if res.err != '' {
313 return error(res.err)
314 }
315 return res.ms, res.size
316}
317
318// fetch_worker serves one queued fetch and dies. it takes no arguments on
319// purpose — the job comes off the queue — and one fetcher per fetch keeps the
320// pairing exact: every queued job has a thread waiting to pop it, whichever
321// thread answers which
322fn fetch_worker() {
323 job := <-fetch_jobs or { return }
324 mut req := http.Request{
325 url: job.url
326 read_timeout: job.limit * time.second
327 write_timeout: job.limit * time.second
328 on_progress: fn [job] (_ &http.Request, _ []u8, _ u64) ! {
329 if time.now() > job.deadline {
330 return error('no whole answer within ${job.limit}s')
331 }
332 }
333 }
334 if job.range {
335 req.header.add_custom('Range', 'bytes=0-0') or {
336 job.reply <- FetchOutcome{ err: err.msg() }
337 return
338 }
339 }
340 start := time.now()
341 resp := req.do() or {
342 job.reply <- FetchOutcome{ err: err.msg() }
343 return
344 }
345 // an answer that needs no body — a 404, a 403 — is a mirror that does
346 // not serve the repo db: a probe without body size is ranked on air
347 // unless the status is turned into the probe's failure
348 if resp.status_code < 200 || resp.status_code >= 300 {
349 job.reply <- FetchOutcome{ err: 'http ${resp.status_code} from ${job.url}' }
350 return
351 }
352 job.reply <- FetchOutcome{
353 ms: (time.now() - start).milliseconds()
354 size: resp.body.len
355 }
356}
357
358fn probe_latency(m Mirror, spec RankOs, override string) Probe {
359 ms, _ := timed_get(probe_url(m, spec, override), true) or {
360 return Probe{
361 url: m.url
362 }
363 }
364 return timed_probe(m.url, ms, 0, false)
365}
366
367fn probe_speed(m Mirror, spec RankOs, override string) Probe {
368 ms, bytes := timed_get(probe_url(m, spec, override), false) or {
369 return Probe{
370 url: m.url
371 }
372 }
373 return timed_probe(m.url, ms, bytes, true)
374}
375
376// timed_probe is a probe's result out of what the timed request measured:
377// the latency always, and with speed the bytes a second of a whole fetch —
378// one that brought no bytes failed, and one quicker than the clock's
379// millisecond counts as one, never a division by zero
380fn timed_probe(url string, ms i64, bytes int, speed bool) Probe {
381 if !speed {
382 return Probe{
383 url: url
384 latency_ms: ms
385 ok: true
386 }
387 }
388 if bytes <= 0 {
389 return Probe{
390 url: url
391 }
392 }
393 elapsed := if ms <= 0 { 1 } else { ms }
394 return Probe{
395 url: url
396 latency_ms: ms
397 speed: f64(bytes) / (f64(elapsed) / 1000.0)
398 ok: true
399 }
400}
401
402// Probe is the result of testing one mirror
403struct Probe {
404 url string
405 latency_ms i64
406 speed f64
407 ok bool
408}
409
410// ProbeFn measures one mirror, the os and the path override closed over. it
411// answers a Probe on every path — a failure is a Probe that is not ok — and
412// that is what lets probe_batch count on one answer per mirror
413type ProbeFn = fn (Mirror) Probe
414
415// probe_batch tests every mirror, rank_parallelism() at a time, and advances
416// the bar by each finished probe. quiet draws no bar, so the output can be
417// piped. the answers come back in the order they finish, not the input's
418fn probe_batch(mut ui TransUI, label string, mirrors []Mirror, probe ProbeFn, quiet bool) []Probe {
419 mut out := []Probe{cap: mirrors.len}
420 if mirrors.len == 0 {
421 return out
422 }
423 mut bar := unsafe { &Meter(nil) }
424 if !quiet {
425 bar = ui.meter(i64(mirrors.len), label)
426 bar.start()
427 }
428 // a parallelism that slipped past the config's floor would start no
429 // worker at all: one at a time is the least
430 conc := if rank_parallelism() < 1 { 1 } else { rank_parallelism() }
431 workers := if conc < mirrors.len { conc } else { mirrors.len }
432 // the whole batch is queued, then the queue closed: a worker that finds
433 // it drained is done. a pool rather than slots of conc means a slow probe
434 // holds back only its own worker, not the next slot's fast ones
435 jobs := chan Mirror{cap: mirrors.len}
436 for m in mirrors {
437 jobs <- m
438 }
439 jobs.close()
440 // the answers channel holds a whole batch, so a worker never waits on the
441 // collector to hand its answer over
442 answers := chan Probe{cap: mirrors.len}
443 for _ in 0 .. workers {
444 spawn probe_worker(jobs, answers, probe)
445 }
446 // one answer per mirror, each sent by the worker that took it: the probe
447 // answers on every path, and a panic in any thread ends the process
448 // rather than stranding this loop. a probe that hangs is bounded by the
449 // network's own timeouts (rank_timeout on read and write, the net
450 // module's on connect) and by timed_get's deadline on the whole answer
451 for _ in 0 .. mirrors.len {
452 out << <-answers
453 if !quiet {
454 bar.add(i64(1))
455 }
456 }
457 return out
458}
459
460// probe_worker measures mirrors until the queue runs dry. the probe runs on
461// this thread: the arguments of a spawned call are evaluated by the caller,
462// so spawning the send of a probe's result runs every probe on the collector,
463// one after another
464fn probe_worker(jobs chan Mirror, answers chan Probe, probe ProbeFn) {
465 for {
466 m := <-jobs or { return }
467 answers <- probe(m)
468 }
469}
470
471fn speed_mib(bytes_per_sec f64) string {
472 return '${bytes_per_sec / 1048576.0:.2f} MiB/s'
473}
474
475fn sync_age(last_sync string) string {
476 if last_sync == '' {
477 return '-'
478 }
479 synced := time.parse_rfc3339(last_sync) or { return '-' }
480 hours := (time.now().unix() - synced.unix()) / 3600
481 return '${hours}h ago'
482}
483
484// Both readers accept bar-escaped identifiers. Keep punctuation in custom
485// mirror names and quotes in downloaded URLs inside their respective literals.
486fn ranked_mirrors(os_name string, urls []string, date string, native bool) !string {
487 name := '|mirrors-' + os_name.replace('\\', '\\\\').replace('|', '\\|') + '|'
488 header := '; mirrors for ${os_name}, ranked by vpac k -w on ${date}\n'
489 mut quoted := []string{}
490 for url in urls { quoted << scheme.write(scheme.string_value(url))! }
491 if native {
492 prior := "if(defined?('${name})) { if(vector?(${name})) { vector->list(${name}) } else { ${name} } } else { list() }"
493 return header + '${name} := append(${prior}, list(' + quoted.join(', ') + '))\n'
494 }
495 return header + "(define ${name} (append (if (defined? '${name}) (if (vector? ${name}) (vector->list ${name}) ${name}) (list)) (list ${quoted.join(' ')})))\n"
496}
497
498// write_config_mirrors writes the ranked urls as the scheme file the config
499// requires
500fn write_config_mirrors(os_name string, urls []string) !string {
501 target := rank_write_target(os_name)
502 os.mkdir_all(os.dir(target))!
503 os.write_file(target, ranked_mirrors(os_name, urls, time.now().custom_format('YYYY-MM-DD'), config_vile)!)!
504 return target
505}
506
507// Ranked is one mirror of a ranking: its probe, and when it last synced as
508// the mirror status says ('' when it is not known)
509struct Ranked {
510 Probe
511 last_sync string
512}
513
514// rank_mirrors measures the mirrors of an os and returns the best of them,
515// at most config.top, fastest first. the probes draw on the ui unless the
516// result goes to a file or a mirrorlist
517fn rank_mirrors(mut ui TransUI, os_name string, config ConfigRank) ![]Ranked {
518 spec := rank_oses[os_name]
519 mirrors := if config.stdin {
520 parse_mirrors(stdin_text()!)
521 } else if spec.status_json != '' {
522 fetch_status_mirrors(os_name, spec)!
523 } else {
524 fetch_mirrorlist(spec)!
525 }
526 if mirrors.len == 0 {
527 return error('no usable mirrors to rank')
528 }
529 mut sync_of := map[string]string{}
530 for m in mirrors {
531 sync_of[m.url] = m.last_sync
532 }
533
534 quiet := config.mirrorlist || config.output != ''
535 override := config.path
536 mut latency := probe_batch(mut ui, 'latency', mirrors, fn [spec, override] (m Mirror) Probe {
537 return probe_latency(m, spec, override)
538 }, quiet).filter(it.ok)
539 latency.sort(a.latency_ms < b.latency_ms)
540 if latency.len > rank_speed_candidates {
541 latency = latency[..rank_speed_candidates].clone()
542 }
543 candidates := latency.map(Mirror{
544 url: it.url
545 last_sync: sync_of[it.url] or { '' }
546 })
547
548 mut results := probe_batch(mut ui, 'speed', candidates, fn [spec, override] (m Mirror) Probe {
549 return probe_speed(m, spec, override)
550 }, quiet).filter(it.ok)
551 results.sort(a.speed > b.speed)
552
553 // the best few are measured again, one at a time, and averaged, so one
554 // lucky or unlucky transfer does not decide the order
555 for i in 0 .. if results.len < rank_retest { results.len } else { rank_retest } {
556 again := probe_speed(Mirror{ url: results[i].url }, spec, config.path)
557 if again.ok {
558 results[i] = Probe{
559 url: results[i].url
560 latency_ms: results[i].latency_ms
561 speed: (results[i].speed + again.speed) / 2.0
562 ok: true
563 }
564 }
565 }
566 results.sort(a.speed > b.speed)
567 ui.stop()
568
569 if results.len == 0 {
570 return error('no mirror answered the speed test')
571 }
572 top := if results.len < config.top { results.len } else { config.top }
573 return results[..top].map(Ranked{
574 Probe: it
575 last_sync: sync_of[it.url] or { '' }
576 })
577}
578
579// rank ranks the mirrors, then writes them where config says, or prints them
580fn rank(config ConfigRank) ! {
581 os_name := rank_os_name(config.query)!
582 mut ui := new_trans_ui()
583 defer {
584 ui.stop()
585 }
586 ranked := rank_mirrors(mut ui, os_name, config)!
587
588 urls := ranked.map(it.url)
589 if config.write {
590 target := write_config_mirrors(os_name, urls)!
591 report('wrote ${urls.len} mirrors to ${target}')
592 }
593 // a frontend gets the ranking itself, and formats it as it needs: the
594 // mirrorlist and output forms shape the printable text, which under
595 // --ui ipc lands in the log anyway, so the event goes out before
596 // whatever those flags do with the result
597 if ipc_on() {
598 emit(MirrorsEvent{
599 mirrors: ranked.map(MirrorEvent{
600 url: it.url
601 latency_ms: it.latency_ms
602 speed: it.speed
603 last_sync: it.last_sync
604 })
605 })
606 }
607 if config.output != '' {
608 os.write_file(config.output, urls.map('Server = ${it}').join('\n') + '\n')!
609 report('wrote ${urls.len} mirrors to ${config.output}')
610 return
611 }
612 if config.mirrorlist {
613 println(urls.map('Server = ${it}').join('\n'))
614 return
615 }
616 if ipc_on() {
617 return
618 }
619 // sync paints the finished spinner frames before the ranking prints
620 ui.sync()
621 mut rows := []Row{}
622 for i, m in ranked {
623 rows << row('${i + 1}', m.url.all_before('$'), '${m.latency_ms} ms', speed_mib(m.speed),
624 sync_age(m.last_sync))
625 }
626 println(table_text(rows, '', ' '))
627}
628